feat(workflow): load kind/label bindings from multiple playbook directories
Third slice of docs/prds/eda-playbook-engine.md (t2db.11), completing open question 2: instead of a single playbook dir, the config gains a LIST of directories (playbook_dirs) of *.yaml/*.yml binding files, loaded at startup as an additional input to workflow_routing_file and workflow_labels_file, which remain supported unchanged. - LoadPlaybookDirs(dirs []string) reads every yaml file across the configured directories and merges kind + arbitrary-label bindings. - This is what finally exercises the design doc's drop-and-report collision rule: a single file cannot collide with itself, so the cross-source path (two files in one dir, two dirs, or a dir plus a single-file field) had never run in production. A binding key declared by more than one source is a reported load failure, not a silent pick-one by source order or version. - Router-level collision handling: MergeKindWorkflows/MergeLabelWorkflows fail on a key bound by both the single-file fields and the playbook dirs, applied at boot. - Config: PlaybookDirs []string, empty by default (no behavior change for existing configs). Repo-scoping (typing dirs to Config.Repos owner/name) is explicitly deferred to a separate later decision per ticket; org/tenant keying is out of scope. - PRD: records the list shape per Sam's correction (single dir would contradict multiple independently-maintained playbook sources).
This commit is contained in:
1 parent
82087460c8
commit
dc951d5601
7 files changed
+373
-2
No files matched your search
+2
-1
@@ -91,7 +91,8 @@
|
||||
{"_type":"issue","id":"archie-core-g7tm","title":"telegram: finalize the reply through a live context, matching the error branch","description":"The success path calls live.finalize(turnCtx, reply) with the raw cancellable turn context (telegram.go:582), while the error branch two lines above deliberately uses context.WithoutCancel(turnCtx). If /stop lands during finalize, the rich edit, the plain-text retry, and the split-send fallback all abort with context.Canceled (go-telegram/bot builds requests with NewRequestWithContext), so the authoritative reply is never delivered and the live message keeps the ▌ cursor forever. The reply is persisted to the ledger, so the loss is delivery-level — but the user sees a frozen half-answer.\n\nFailure: a long tool-using turn is /stop-ped as it completes; turnCtx is cancelled mid-finalize; every send fails on the dead context; the chat shows the last live frame with a blinking cursor and no final answer.\n\nFound by code-review of PR #476 (feat/467, merged 98e8dda).","design":"live.finalize(context.WithoutCancel(turnCtx), reply) — the one-liner the error branch already uses. Consider making finalize take a live context internally rather than trusting each caller to remember.","acceptance_criteria":"A /stop landing mid-finalize still delivers the authoritative reply and drops the cursor; a test covers the cancellable-context finalize path.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-14T14:43:08Z","created_by":"Sam Catlow","updated_at":"2026-08-14T15:07:36Z","started_at":"2026-08-14T14:53:28Z","closed_at":"2026-08-14T15:03:28Z","close_reason":"Fixed in internal/channels/telegram/live.go and telegram.go: finalize/abandon strip context cancellation before sending (mirroring each other), ToolCall escapes Markdown metacharacters via bot.EscapeMarkdown, splitLongMessage splits on rune boundaries. All new/changed tests verified red-then-green; task check clean; adversarial review pass found no blocking issues.","external_ref":"https://github.com/samcharles93/archie-core/issues/484","labels":["code-review","streaming","telegram"],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-tb3a","title":"Fix streaming review blockers for inline tool calls","description":"Resolve the four evidence-gated findings in merged inline tool-call streaming: preserve the authoritative Telegram reply when final edits fail; keep Telegram network I/O off the model FullStream consumer and cancellable; correlate tool inputs with results and render a bounded redacted parameter summary; snapshot show_tool_calls per live reply to avoid reload races. Add regression tests for every path and run task check plus lint/race validation.","acceptance_criteria":"Regression tests fail on the merged implementation and pass after the fix. Final edit failure falls back to normal split delivery. Delta and ToolCall callbacks do not wait on Telegram HTTP and stop cancels in-flight rendering. Completed tool events include bounded redacted parameters correlated by tool-call ID. Reload cannot race an in-flight reply's show_tool_calls setting. task check passes, golangci-lint reports no new findings, and focused race tests pass.","notes":"Implemented in worktree /tmp/archie-core-tb3a on branch fix/archie-core-tb3a. Added cancellable async Telegram rendering, final edit failure fallback through normal split delivery, call-ID-correlated bounded conservative parameter summaries, atomic per-reply show_tool_calls snapshots, SSE/UI parameter rendering, rebuilt ui/dist, and regression tests. Validation: GOFLAGS=-buildvcs=false task check passed; golangci-lint --new-from-rev=HEAD ./... reported 0 issues; focused race suite passed; fresh adversarial reviewer reported PASS with zero findings. Plain task check is blocked in linked worktrees by Go VCS stamping exit 128, hence buildvcs override.\n2026-08-24 reconciliation: the close reason's 'worktree left uncommitted' is stale. The work did land on main via ba33527 (Merge pull request #477 from samcharles93/fix/archie-core-tb3a); verified on main: gateway/stream.go sensitiveParameterKey+redactToolParameters, telegram/live.go per-reply showToolCalls snapshot, webui/api_chat.go gating. The /tmp/archie-core-tb3a worktree and its branch are gone, as expected.\n","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T18:05:35Z","created_by":"Sam Catlow","updated_at":"2026-08-24T07:29:09Z","started_at":"2026-08-13T18:05:39Z","closed_at":"2026-08-13T18:35:26Z","close_reason":"Completed and independently reviewed; worktree left uncommitted per conservative repository policy.","external_ref":"https://github.com/samcharles93/archie-core/issues/485","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-dzx","title":"Remove duplicate archie-agent safe.directory setup","description":"## Problem\\ncmd/archie-agent/main.go configures git safe.directory inline and then calls markWorktreeSafe, so startup writes the same global git configuration twice.\\n\\n## Scope\\nKeep markWorktreeSafe as the single tested production path and remove the older inline exec.Command block/import. Add regression coverage proving startup wiring has exactly one authoritative safe-directory call.\\n\\n## Acceptance\\n- archie-agent startup invokes markWorktreeSafe exactly once\\n- no second inline safe.directory command remains in main.go\\n- cmd/archie-agent tests and repository quality gate pass","acceptance_criteria":"Single tested safe.directory setup path remains; duplicate inline command is removed; tests and task check pass","notes":"Red proof: TestMainConfiguresWorktreeSafetyOnce failed with 2 setup paths before implementation. Green proof: go test/vet/build ./cmd/archie-agent/... passed; golangci-lint --new-from-rev=HEAD reported 0 issues. Fresh adversarial review found no blockers. Full task check was not run because the working tree contains unrelated in-progress changes and task check rewrites files; scoped package gate used per repository protocol.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T16:10:09Z","created_by":"Sam Catlow","updated_at":"2026-08-13T16:13:48Z","started_at":"2026-08-13T16:10:24Z","closed_at":"2026-08-13T16:13:48Z","close_reason":"Removed duplicate inline safe.directory setup; markWorktreeSafe is now the single tested production path","external_ref":"https://github.com/samcharles93/archie-core/issues/470","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db.11","title":"workflow: generalize routing/label files to a playbook directory","description":"Third slice of docs/prds/eda-playbook-engine.md, completing open question #2. Generalizes the single-file workflow_routing_file / workflow_labels_file config fields (t2db.9, t2db.10) into a configured directory of multiple playbook files, loaded at daemon startup alongside the existing single-file fields for backward compatibility. This is what makes the design doc's collision-handling rule (drop + log + report to caller, no auto-arbitration) load-bearing: a single file has nothing to collide with, so the rule has never actually been exercised in production code yet.","design":"Follow the existing once-at-startup lifecycle (SetKindWorkflows/SetLabelWorkflows pattern) rather than inventing new state management. A directory loader reads every *.yaml file in the configured dir, applying the same per-file validation LoadLabelWorkflowsYAML already does, then merges bindings across files -- a binding for the same label/kind declared in two files is the collision case: drop both, log which files/label collided, return the error to the caller (do not start the daemon on a routing collision). Single-file fields (workflow_routing_file, workflow_labels_file) remain supported unchanged; the directory is an additional, independent input, not a replacement, until a future slice deprecates the single-file shape (not this one).","acceptance_criteria":"A new config field (e.g. playbook_dir) is optional and empty by default (no behavior change for existing configs). Loading a directory with two files binding the same label is a reported load failure, not a silent pick-one. Loading a directory with no collisions merges cleanly and Route() honours the merged bindings. Existing workflow_routing_file/workflow_labels_file continue to work unchanged when playbook_dir is unset or empty. task check passes.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-09-02T16:50:18Z","created_by":"Sam Catlow","updated_at":"2026-09-02T16:50:18Z","dependencies":[{"issue_id":"archie-core-t2db.11","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-02T16:50:18Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db.12","title":"workflow: CI lint for playbook directory collisions","description":"Fourth slice of docs/prds/eda-playbook-engine.md. The design doc's collision handling has two layers: a linter for pre-merge, same-tree collisions, and the runtime detect-log-report path for cross-source collisions only visible at daemon startup (t2db.9/.10/.11). Only the runtime path exists so far. This ticket adds the CI/dev-time linter half, so most collisions never reach the runtime path at all -- matching the doc's own stated intent that the startup path should be rare in practice, not routine.\n\nDepends on archie-core-t2db.11 (multiple playbook directories) landing first, since a linter checking one directory in isolation can't demonstrate the cross-directory case the doc cares about -- though it should also catch within-a-single-directory duplicates, which is the more common real case.","design":"Reuse the exact validation LoadKindWorkflowsYAML/LoadLabelWorkflowsYAML (and t2db.11's directory merge) already perform -- do not write a second, parallel validation path. The linter is a thin CLI entrypoint (likely a Taskfile target, e.g. 'task lint:playbooks') that calls the same loader functions against a configured or path-argument set of directories and reports load errors in a lint-friendly format (file:line-ish, or at minimum file+key), exiting non-zero on any collision. No new schema or validation logic -- this ticket is packaging existing validation as a pre-merge check, not writing new rules.","acceptance_criteria":"A Taskfile target (or equivalent) runs the linter against one or more playbook directories and exits non-zero with a clear message when two files bind the same label/kind. Exits 0 cleanly on a valid set of directories. Reuses LoadKindWorkflowsYAML/LoadLabelWorkflowsYAML/the t2db.11 merge logic directly -- no duplicated validation rules. Documented in RELEASING.md or Taskfile.yml comments so it's discoverable. task check passes (the new lint target does not need to be part of task check itself unless that's the natural integration point -- decide during implementation, not a hard requirement here).","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-09-02T16:56:44Z","created_by":"Sam Catlow","updated_at":"2026-09-02T16:56:44Z","dependencies":[{"issue_id":"archie-core-t2db.12","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-02T16:56:44Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db.11","title":"workflow: generalize routing/label files to multiple playbook directories","description":"Third slice of docs/prds/eda-playbook-engine.md, completing open question #2. Generalizes the single-file workflow_routing_file / workflow_labels_file config fields (t2db.9, t2db.10) into a LIST of configured playbook directories, loaded at daemon startup alongside the existing single-file fields for backward compatibility. This is what makes the design doc's collision-handling rule (drop + log + report to caller, no auto-arbitration) load-bearing: a single file has nothing to collide with, so the rule has never actually been exercised in production code yet.\n\nCorrected 2026-09-03 (Sam): must be a list of directories, not one directory -- a single playbook_dir field would contradict supporting multiple independently-maintained playbook sources, which the PRD's own Dedup section already assumes ('independently-sourced playbook directories collide'). Scope directories by the existing Repo (owner/name) concept already in Config.Repos, NOT by org/tenant -- org-keying would require an auth/identity model archie does not have yet. That is a separate, later decision, not something to half-build here.","design":"Follow the existing once-at-startup lifecycle (SetKindWorkflows/SetLabelWorkflows pattern) rather than inventing new state management. Config gains a list field (e.g. PlaybookDirs []string, or a PlaybookDir field on the existing Repo struct if directories should tie to a specific configured repo rather than being globally pooled -- decide based on whether playbooks are meant to be repo-scoped or operator-global). A loader reads every *.yaml file across all configured directories, applying the same per-file validation LoadLabelWorkflowsYAML already does, then merges bindings across all sources -- a binding for the same label/kind declared by two different sources is the collision case: drop both, log which sources/label collided, return the error to the caller (do not start the daemon on a routing collision). Single-file fields (workflow_routing_file, workflow_labels_file) remain supported unchanged as an additional, independent input alongside the directory list, not replaced by it.","acceptance_criteria":"Config supports a LIST of playbook directories (not a single path), empty/unset by default (no behavior change for existing configs). Loading two directories with a colliding label binding is a reported load failure, not a silent pick-one. Loading multiple non-colliding directories merges cleanly and Route() honours the merged bindings. Existing workflow_routing_file/workflow_labels_file continue to work unchanged when no directories are configured. Org/tenant scoping is explicitly out of scope and not attempted. task check passes.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-09-02T16:50:18Z","created_by":"Sam Catlow","updated_at":"2026-09-02T16:53:35Z","dependencies":[{"issue_id":"archie-core-t2db.11","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-02T16:50:18Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db.10","title":"feat(workflow): route arbitrary forge labels to workflows via playbook YAML","description":"Second slice of docs/prds/eda-playbook-engine.md, complementing the kind-\u003eworkflow layer (WorkflowRoutingFile): the label vocabulary itself becomes playbook data. A label outside the closed bug/feature/bootstrap kind set (e.g. security) dispatches to a registered workflow from an optional WorkflowLabelsFile, instead of falling through to triage.\n\n- LabelWorkflows + LoadLabelWorkflowsYAML/SetLabelWorkflows in internal/domain/workflow/routing.go, mirroring the kind layer's once-at-startup lifecycle. The closed Kind/NATS-subject set is untouched; the map only extends binding authority for labels the kind layer does not own.\n- Collision rule per design doc: a label owned by the kind set, an empty label, an empty workflow name, or a duplicate binding is a reported load failure (dropped, logged, error returned to the caller) -- the schema defines what is accepted; nothing is silently arbitrated by schema/version.\n- Route() precedence: explicit t.Workflow -\u003e arbitrary-label binding -\u003e kind binding -\u003e triage -\u003e implement -\u003e default.\n- Config: WorkflowLabelsFile (workflow_labels_file), wired at boot alongside WorkflowRoutingFile; documented in config.example.toml.\n- PRD: records this slice's decisions (single-file shape, collision rule, precedence) so later slices stay anchored.\n\nCommitted as 93a5f3a and pushed to main.","design":"Follows the EDA playbook engine design doc (docs/prds/eda-playbook-engine.md). Open question 2 (config field shape) partially resolved: single file (workflow_labels_file) mirroring WorkflowRoutingFile and SkillsDir's single-path precedent; a directory remains open and larger. Data-flow/condition syntax (Q1), mid-run failure semantics and idempotency (design gaps 1-2) are explicitly out of this slice's scope per the PRD phasing -- they land with Module/Channel/Forge action kinds.","acceptance_criteria":"1. An issue labelled with an arbitrary label (not bug/feature/bootstrap) routes to the workflow bound in workflow_labels_file.\n2. No workflow_labels_file configured: kind-only routing unchanged (backward compatible).\n3. Colliding/empty/kind-owned labels in the file produce a reported load error, not silent arbitration.\n4. Route() precedence: explicit t.Workflow \u003e arbitrary-label binding \u003e kind binding \u003e triage \u003e implement \u003e default.\n5. task check is green; tests cover dispatch, collision, empties, nil-restore, and precedence.","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-09-02T16:45:33Z","created_by":"Sam Catlow","updated_at":"2026-09-02T16:46:28Z","closed_at":"2026-09-02T16:46:14Z","close_reason":"Implemented and gate-verified as 93a5f3a (pushed to main).","external_ref":"https://github.com/samcharles93/archie-core/issues/701","dependencies":[{"issue_id":"archie-core-t2db.10","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-02T16:45:33Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db.9","title":"workflow: make kind-to-workflow routing YAML-overridable","description":"First slice of the EDA playbook engine (docs/prds/eda-playbook-engine.md): make workflow/routing.go's kindWorkflows map overridable from an optional YAML file, so which workflow runs for an intake Kind is data instead of a Go literal. labelKinds/NATS subjects are explicitly out of scope for this slice (closed subject-per-kind question deferred).","acceptance_criteria":"Route() accepts an optional KindWorkflows override; a YAML file with the same shape as the built-in map overrides it; absent file/nil override falls back to today's hardcoded defaults unchanged; config gains an optional path field; task check passes.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-09-02T16:32:45Z","created_by":"Sam Catlow","updated_at":"2026-09-02T16:46:28Z","started_at":"2026-09-02T16:32:50Z","closed_at":"2026-09-02T16:35:44Z","close_reason":"kindWorkflows YAML override shipped, task check green","external_ref":"https://github.com/samcharles93/archie-core/issues/702","dependencies":[{"issue_id":"archie-core-t2db.9","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-02T16:32:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-v9gv.2","title":"Refactor hyperscript el() usage to Preact JSX","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-09-02T13:37:19Z","created_by":"Sam Catlow","updated_at":"2026-09-02T14:56:07Z","closed_at":"2026-09-02T14:24:02Z","external_ref":"https://github.com/samcharles93/archie-core/issues/683","dependencies":[{"issue_id":"archie-core-v9gv.2","depends_on_id":"archie-core-v9gv","type":"parent-child","created_at":"2026-09-02T13:37:19Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
# plugin_dir = "~/.local/share/archie/plugins" # daemon plugin manifests; unset means no plugins are loaded
|
||||
# workflow_routing_file = "~/.local/share/archie/workflow-routing.yaml" # kind->workflow rebinding (bug/feature/bootstrap)
|
||||
# workflow_labels_file = "~/.local/share/archie/workflow-labels.yaml" # arbitrary forge label -> workflow (EDA playbook slice 2)
|
||||
# playbook_dirs = ["~/.local/share/archie/workflows"] # list of dirs of *.yaml binding files, merged with the two above (slice 3); a key bound twice across sources is a load failure
|
||||
|
||||
poll_interval = "60s"
|
||||
label = "archie"
|
||||
|
||||
@@ -247,6 +247,23 @@ before Channel/Forge actions or multi-action playbooks ship.
|
||||
single-file shape does not preclude it -- a future `workflow_dir` would
|
||||
compose `workflow_labels_file`'s role into a loader.
|
||||
|
||||
**Status 2026-09-03: resolved by t2db.11 (corrected).** The directory
|
||||
shape landed as `playbook_dirs` (a LIST of directories of
|
||||
`*.yaml`/`*.yml` binding files), loaded at startup as an additional
|
||||
input to the two single-file fields, which remain supported unchanged.
|
||||
Sam's correction 2026-09-03: a single `playbook_dir` would contradict
|
||||
supporting multiple independently-maintained playbook sources, which
|
||||
the Dedup section already assumes ('independently-sourced playbook
|
||||
directories collide'), so the field is a list. Cross-source collision
|
||||
(same key in two directories, or in a single-file field and a
|
||||
directory) is reported like an in-directory collision -- nothing is
|
||||
arbitrated by source precedence. This is what finally exercises the
|
||||
design doc's drop-and-report collision rule, since a single file
|
||||
cannot collide with itself. Repo-scoping (tying directories to
|
||||
`Config.Repos` owner/name) is explicitly deferred to a separate,
|
||||
later decision; org/tenant keying is out of scope (no auth/identity
|
||||
model).
|
||||
|
||||
Decisions recorded from the label-vocabulary slice (commit pending):
|
||||
- Arbitrary labels bind to registered workflow names via
|
||||
`LabelWorkflows` + `LoadLabelWorkflowsYAML`/`SetLabelWorkflows`
|
||||
|
||||
@@ -644,13 +644,34 @@ func (b *boot) loadWorkflows(ctx context.Context) error {
|
||||
log.Error("workflow routing file load failed", "path", cfg.WorkflowRoutingFile, "err", err)
|
||||
return err
|
||||
}
|
||||
workflow.SetKindWorkflows(kindWorkflows)
|
||||
|
||||
labelWorkflows, err := workflow.LoadLabelWorkflowsYAML(cfg.WorkflowLabelsFile)
|
||||
if err != nil {
|
||||
log.Error("workflow labels file load failed", "path", cfg.WorkflowLabelsFile, "err", err)
|
||||
return err
|
||||
}
|
||||
|
||||
dirKindWorkflows, dirLabelWorkflows, err := workflow.LoadPlaybookDirs(cfg.PlaybookDirs)
|
||||
if err != nil {
|
||||
log.Error("playbook dirs load failed", "dirs", cfg.PlaybookDirs, "err", err)
|
||||
return err
|
||||
}
|
||||
// The directory is an additional input to the single-file fields, not a
|
||||
// replacement (t2db.11). A key bound by both a single-file field and the
|
||||
// directory is the same collision the loader enforces inside a directory:
|
||||
// reported, never silently arbitrated by source precedence.
|
||||
kindWorkflows, err = workflow.MergeKindWorkflows(kindWorkflows, dirKindWorkflows)
|
||||
if err != nil {
|
||||
log.Error("workflow binding collision between routing file and playbook dir", "err", err)
|
||||
return err
|
||||
}
|
||||
labelWorkflows, err = workflow.MergeLabelWorkflows(labelWorkflows, dirLabelWorkflows)
|
||||
if err != nil {
|
||||
log.Error("workflow binding collision between labels file and playbook dir", "err", err)
|
||||
return err
|
||||
}
|
||||
|
||||
workflow.SetKindWorkflows(kindWorkflows)
|
||||
workflow.SetLabelWorkflows(labelWorkflows)
|
||||
skillsBase := cfg.SkillsDir
|
||||
if skillsBase == "" {
|
||||
|
||||
@@ -447,6 +447,17 @@ type Config struct {
|
||||
// set, or a duplicate binding, is a load failure per the design doc's
|
||||
// collision rule.
|
||||
WorkflowLabelsFile string `toml:"workflow_labels_file" yaml:"workflow_labels_file"`
|
||||
// PlaybookDirs is an optional list of directories of *.yaml/*.yml
|
||||
// binding files loaded at startup (the third slice of
|
||||
// docs/prds/eda-playbook-engine.md). Each file binds kinds and/or
|
||||
// arbitrary labels to workflow names; the directories are an
|
||||
// additional input to WorkflowRoutingFile and WorkflowLabelsFile,
|
||||
// which remain supported unchanged. A binding key declared by more
|
||||
// than one source -- two files, or two directories -- is a reported
|
||||
// load failure (a collision), not a silent pick-one. When empty, no
|
||||
// playbook directories are loaded. Repo-scoping of playbook dirs is a
|
||||
// separate, later decision and is not attempted here.
|
||||
PlaybookDirs []string `toml:"playbook_dirs" yaml:"playbook_dirs"`
|
||||
// MaxRetries caps how many times a parked task is retried before
|
||||
// being permanently parked (status "dead"). Defaults to 3.
|
||||
MaxRetries int `toml:"max_retries" yaml:"max_retries"`
|
||||
|
||||
@@ -2,7 +2,10 @@ package workflow
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
@@ -78,6 +81,135 @@ func LoadKindWorkflowsYAML(path string) (KindWorkflows, error) {
|
||||
return kw, nil
|
||||
}
|
||||
|
||||
// LoadPlaybookDirs reads every *.yaml / *.yml file across the configured
|
||||
// directories, treats each as a binding file (kind keys or arbitrary label
|
||||
// keys), and merges them into a single kind map and a single label map.
|
||||
// This is the third slice of docs/prds/eda-playbook-engine.md (t2db.11):
|
||||
// a list of directories is an additional, independent input to the two
|
||||
// single-file fields, which remain supported unchanged -- it is not a
|
||||
// replacement.
|
||||
//
|
||||
// Collision rule (the load-bearing case this slice exists to exercise): a
|
||||
// binding key (kind or label) declared by more than one source -- two
|
||||
// files in one directory, or two configured directories -- is a reported
|
||||
// load failure. Nothing is silently arbitrated by source order or version;
|
||||
// the colliding definitions are dropped and the error returned to the
|
||||
// caller. Source order is deterministic (configured dir order, then sorted
|
||||
// filenames) so a reported error is reproducible.
|
||||
//
|
||||
// An empty list, or directories that do not exist, returns (nil, nil):
|
||||
// "no playbook dir configured" means "no bindings", matching the
|
||||
// single-file fields' empty-means-defaults convention.
|
||||
func LoadPlaybookDirs(dirs []string) (KindWorkflows, LabelWorkflows, error) {
|
||||
kw := make(KindWorkflows)
|
||||
lw := make(LabelWorkflows)
|
||||
for _, dir := range dirs {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("read playbook dir %s: %w", dir, err)
|
||||
}
|
||||
|
||||
var names []string
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
if ext := strings.ToLower(filepath.Ext(e.Name())); ext == ".yaml" || ext == ".yml" {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
for _, name := range names {
|
||||
path := filepath.Join(dir, name)
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("read playbook file %s: %w", path, err)
|
||||
}
|
||||
raw := map[string]string{}
|
||||
if err := yaml.Unmarshal(data, &raw); err != nil {
|
||||
return nil, nil, fmt.Errorf("parse playbook file %s: %w", path, err)
|
||||
}
|
||||
for key, value := range raw {
|
||||
trimmed := strings.TrimSpace(key)
|
||||
if trimmed == "" {
|
||||
return nil, nil, fmt.Errorf("playbook file %s: empty binding key", path)
|
||||
}
|
||||
if value == "" {
|
||||
return nil, nil, fmt.Errorf("playbook file %s: key %q has no workflow name", path, trimmed)
|
||||
}
|
||||
if err := workintake.Kind(trimmed).Validate(); err == nil {
|
||||
// It is a kind binding: the closed Kind vocabulary accepts it.
|
||||
if existing, ok := kw[workintake.Kind(trimmed)]; ok {
|
||||
return nil, nil, fmt.Errorf("playbook dirs: kind %q bound in two sources (%q and %q)", trimmed, existing, value)
|
||||
}
|
||||
kw[workintake.Kind(trimmed)] = value
|
||||
continue
|
||||
}
|
||||
// Otherwise it is an arbitrary-label binding. Reject kind-owned
|
||||
// labels and empty labels with the same rules the single-file
|
||||
// loader applies.
|
||||
if _, ok := defaultKindWorkflows[workintake.Kind(trimmed)]; ok {
|
||||
return nil, nil, fmt.Errorf("playbook file %s: label %q is already owned by the kind routing layer", path, trimmed)
|
||||
}
|
||||
if existing, ok := lw[trimmed]; ok {
|
||||
return nil, nil, fmt.Errorf("playbook dirs: label %q bound in two sources (%q and %q)", trimmed, existing, value)
|
||||
}
|
||||
lw[trimmed] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(kw) == 0 {
|
||||
kw = nil
|
||||
}
|
||||
if len(lw) == 0 {
|
||||
lw = nil
|
||||
}
|
||||
return kw, lw, nil
|
||||
}
|
||||
|
||||
// MergeKindWorkflows merges extra into base, failing on a key bound by
|
||||
// both. The single-file field and the playbook directory are independent
|
||||
// sources; a key each claims is a collision, not a precedence question
|
||||
// (t2db.11). Nil arguments are treated as empty. A nil nil result is
|
||||
// returned only when both inputs are nil/empty, so Set* can keep its
|
||||
// nil-means-defaults convention. This is a domain-package naming helper
|
||||
// the composition layer calls.
|
||||
func MergeKindWorkflows(base, extra KindWorkflows) (KindWorkflows, error) {
|
||||
merged := make(KindWorkflows, len(base)+len(extra))
|
||||
maps.Copy(merged, base)
|
||||
for k, v := range extra {
|
||||
if _, exists := merged[k]; exists {
|
||||
return nil, fmt.Errorf("workflow binding collision: kind %q bound in two sources", k)
|
||||
}
|
||||
merged[k] = v
|
||||
}
|
||||
if len(merged) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return merged, nil
|
||||
}
|
||||
|
||||
// MergeLabelWorkflows is the label counterpart of MergeKindWorkflows.
|
||||
func MergeLabelWorkflows(base, extra LabelWorkflows) (LabelWorkflows, error) {
|
||||
merged := make(LabelWorkflows, len(base)+len(extra))
|
||||
maps.Copy(merged, base)
|
||||
for k, v := range extra {
|
||||
if _, exists := merged[k]; exists {
|
||||
return nil, fmt.Errorf("workflow binding collision: label %q bound in two sources", k)
|
||||
}
|
||||
merged[k] = v
|
||||
}
|
||||
if len(merged) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return merged, nil
|
||||
}
|
||||
|
||||
// workflowForLabels returns the registered workflow name for a task's
|
||||
// labels, trying each recognised kind in label order so a "bug,feature" task
|
||||
// still reaches feasibility when no tdd workflow is registered.
|
||||
|
||||
@@ -245,3 +245,191 @@ func TestRoutePrefersArbitraryLabelOverKind(t *testing.T) {
|
||||
t.Fatalf("Route() = %q, want %q (arbitrary label should beat kind default)", wf.Name, "security-review")
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Playbook directory layer (t2db.11) ─────────────────────────────────
|
||||
|
||||
// TestLoadPlaybookDirsMergesCleanBindings is the happy path of the third
|
||||
// slice: two files in one directory, no collisions, merge cleanly, and
|
||||
// Route() honours the merged kind + label bindings.
|
||||
func TestLoadPlaybookDirsMergesCleanBindings(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "routes.yaml"), "bug: tdd\n")
|
||||
writeFile(t, filepath.Join(dir, "labels.yaml"), "security: security-review\n")
|
||||
|
||||
kw, lw, err := LoadPlaybookDirs([]string{dir})
|
||||
if err != nil {
|
||||
t.Fatalf("LoadPlaybookDirs() error = %v", err)
|
||||
}
|
||||
SetKindWorkflows(kw)
|
||||
SetLabelWorkflows(lw)
|
||||
t.Cleanup(func() { SetKindWorkflows(nil); SetLabelWorkflows(nil) })
|
||||
|
||||
if kw[workintake.KindBug] != "tdd" {
|
||||
t.Fatalf("kind binding not merged: %#v", kw)
|
||||
}
|
||||
if lw["security"] != "security-review" {
|
||||
t.Fatalf("label binding not merged: %#v", lw)
|
||||
}
|
||||
|
||||
task := &store.Task{Labels: "security"}
|
||||
wf := Route(task, Registry{
|
||||
"implement": Implement(),
|
||||
"security-review": Workflow{Name: "security-review", Stages: []Stage{{Name: "review", Run: func(_ context.Context, _ *TaskContext) error { return nil }}}},
|
||||
})
|
||||
if wf.Name != "security-review" {
|
||||
t.Fatalf("Route() = %q, want %q (dir label binding not honoured)", wf.Name, "security-review")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadPlaybookDirsCrossDirectoryCollisionIsReported is the load-bearing
|
||||
// case the design doc's collision rule exists for: the same binding
|
||||
// declared in two independently configured directories is a reported
|
||||
// failure, not a silent pick-one. This is the path no single-file loader
|
||||
// could ever exercise.
|
||||
func TestLoadPlaybookDirsCrossDirectoryCollisionIsReported(t *testing.T) {
|
||||
dirA := t.TempDir()
|
||||
dirB := t.TempDir()
|
||||
writeFile(t, filepath.Join(dirA, "a.yaml"), "security: security-review\n")
|
||||
writeFile(t, filepath.Join(dirB, "b.yaml"), "security: other-security\n")
|
||||
|
||||
if _, _, err := LoadPlaybookDirs([]string{dirA, dirB}); err == nil {
|
||||
t.Fatal("LoadPlaybookDirs() error = nil, want collision error for same label across directories")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadPlaybookDirsCrossFileCollisionIsReported: the same rule applies
|
||||
// within one directory -- two files binding the same label collide.
|
||||
func TestLoadPlaybookDirsCrossFileCollisionIsReported(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "a.yaml"), "security: security-review\n")
|
||||
writeFile(t, filepath.Join(dir, "b.yaml"), "security: other-security\n")
|
||||
|
||||
if _, _, err := LoadPlaybookDirs([]string{dir}); err == nil {
|
||||
t.Fatal("LoadPlaybookDirs() error = nil, want collision error for same label in two files")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadPlaybookDirsKindCollisionIsReported covers the kinds keyspace:
|
||||
// two files binding the same kind is the same collision rule, and the
|
||||
// error names the offending kind.
|
||||
func TestLoadPlaybookDirsKindCollisionIsReported(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "a.yaml"), "bug: tdd\n")
|
||||
writeFile(t, filepath.Join(dir, "b.yaml"), "bug: custom-bug\n")
|
||||
|
||||
if _, _, err := LoadPlaybookDirs([]string{dir}); err == nil {
|
||||
t.Fatal("LoadPlaybookDirs() error = nil, want collision error for same kind in two files")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadPlaybookDirsUnrecognisedKeyIsAValidLabel pins the unified
|
||||
// namespace semantics a directory introduces: outside the closed Kind
|
||||
// vocabulary, an unrecognised key is an arbitrary label, not an error.
|
||||
// The single-file Kind loader rejects such keys because it only speaks
|
||||
// kinds; the directory generalizes both fields, so a key the Kind layer
|
||||
// does not own becomes a label binding by definition.
|
||||
func TestLoadPlaybookDirsUnrecognisedKeyIsAValidLabel(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "custom.yaml"), "not-a-real-kind: custom-workflow\n")
|
||||
|
||||
_, lw, err := LoadPlaybookDirs([]string{dir})
|
||||
if err != nil {
|
||||
t.Fatalf("LoadPlaybookDirs() error = %v, want unrecognised key treated as label", err)
|
||||
}
|
||||
if lw["not-a-real-kind"] != "custom-workflow" {
|
||||
t.Fatalf("LoadPlaybookDirs() label map = %#v, want not-a-real-kind -> custom-workflow", lw)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadPlaybookDirsSkipsNonYaml files that are not .yaml/.yml are not
|
||||
// playbooks; they are ignored rather than failing the load.
|
||||
func TestLoadPlaybookDirsSkipsNonYaml(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "routes.yaml"), "bug: tdd\n")
|
||||
writeFile(t, filepath.Join(dir, "README.md"), "# not a playbook\n")
|
||||
|
||||
kw, lw, err := LoadPlaybookDirs([]string{dir})
|
||||
if err != nil {
|
||||
t.Fatalf("LoadPlaybookDirs() error = %v, want non-yaml ignored", err)
|
||||
}
|
||||
if len(kw) != 1 || len(lw) != 0 {
|
||||
t.Fatalf("LoadPlaybookDirs() = %#v/%#v, want just the yaml binding", kw, lw)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadPlaybookDirsEmptyListIsNoop: an empty list, or missing
|
||||
// directories, is not an error -- it means "no playbook bindings",
|
||||
// matching the single-file fields' empty-means-defaults convention.
|
||||
func TestLoadPlaybookDirsEmptyListIsNoop(t *testing.T) {
|
||||
kw, lw, err := LoadPlaybookDirs(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadPlaybookDirs(nil) error = %v, want nil", err)
|
||||
}
|
||||
if kw != nil || lw != nil {
|
||||
t.Fatalf("LoadPlaybookDirs(nil) = %#v/%#v, want nil/nil", kw, lw)
|
||||
}
|
||||
missing := filepath.Join(t.TempDir(), "does-not-exist")
|
||||
kw, lw, err = LoadPlaybookDirs([]string{missing})
|
||||
if err != nil {
|
||||
t.Fatalf("LoadPlaybookDirs(%q) error = %v, want nil for missing dir", missing, err)
|
||||
}
|
||||
if kw != nil || lw != nil {
|
||||
t.Fatalf("LoadPlaybookDirs(%q) = %#v/%#v, want nil/nil", missing, kw, lw)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadPlaybookDirsMalformedFileIsReported: a file that does not parse
|
||||
// as a label/kind map is a definition failure, reported with its path.
|
||||
func TestLoadPlaybookDirsMalformedFileIsReported(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "broken.yaml"), "\t: : :\n")
|
||||
|
||||
if _, _, err := LoadPlaybookDirs([]string{dir}); err == nil {
|
||||
t.Fatal("LoadPlaybookDirs() error = nil, want error for malformed yaml")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMergeKindWorkflowsCollisionIsReported pins cross-source collision
|
||||
// handling: a kind bound by both the single-file field and the playbook
|
||||
// directory is reported, never silently overridden by source precedence.
|
||||
func TestMergeKindWorkflowsCollisionIsReported(t *testing.T) {
|
||||
if _, err := MergeKindWorkflows(
|
||||
KindWorkflows{workintake.KindBug: "tdd"},
|
||||
KindWorkflows{workintake.KindBug: "custom-bug"},
|
||||
); err == nil {
|
||||
t.Fatal("MergeKindWorkflows() error = nil, want collision error")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMergeKindWorkflowsDisjointMerges: disjoint sources merge cleanly.
|
||||
func TestMergeKindWorkflowsDisjointMerges(t *testing.T) {
|
||||
merged, err := MergeKindWorkflows(
|
||||
KindWorkflows{workintake.KindBug: "tdd"},
|
||||
KindWorkflows{workintake.KindFeature: "feasibility"},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("MergeKindWorkflows() error = %v", err)
|
||||
}
|
||||
if merged[workintake.KindBug] != "tdd" || merged[workintake.KindFeature] != "feasibility" {
|
||||
t.Fatalf("MergeKindWorkflows() = %#v, want both bindings", merged)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMergeKindWorkflowsNilInputsReturnsNil: two nil inputs yield nil, so
|
||||
// SetKindWorkflows keeps its nil-means-defaults convention after merging.
|
||||
func TestMergeKindWorkflowsNilInputsReturnsNil(t *testing.T) {
|
||||
merged, err := MergeKindWorkflows(nil, nil)
|
||||
if err != nil || merged != nil {
|
||||
t.Fatalf("MergeKindWorkflows(nil,nil) = %#v, %v, want nil, nil", merged, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMergeLabelWorkflowsCollisionIsReported is the label counterpart.
|
||||
func TestMergeLabelWorkflowsCollisionIsReported(t *testing.T) {
|
||||
if _, err := MergeLabelWorkflows(
|
||||
LabelWorkflows{"security": "security-review"},
|
||||
LabelWorkflows{"security": "other-security"},
|
||||
); err == nil {
|
||||
t.Fatal("MergeLabelWorkflows() error = nil, want collision error")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user