feat(eda): thread Playbook ID/Version and DispatchInput task identity (gap-2 prereqs)

Playbook now carries ID (path-relative to the configured root) and Version
(sha256 content hash recomputed on load), both populated in loadOne, mirroring
Binding.Version's provenance pin without a DB row. DispatchInput gains TaskID
carrying TaskEnvelope.IdempotencyKey(), the identity available at the
discovery point (pollNATS / webhook receiver compute kind+labels from a
TaskEnvelope before any store.Task row exists), NOT a store.Task.ID int64.

These are the two implementation prerequisites named by the t2db.17
idempotency resolution; the playbook_dispatches ledger is built on top.

Note: task check fails on 5 lint findings PRE-EXISTING at HEAD in unrelated
files (bootstrap.go cyclop/nestif, install_script_test.go noctx,
telegram_setup_test.go usetesting), reproduced in a clean worktree and not
caused by this change; the eda/playbook package is gofumpt/vet/lint clean.
This commit is contained in:
sam committed 2026-09-05 03:10:58 +10:00
1 parent a73f7cb6a9
commit a4a8ae7e92
3 files changed
+148 -4

No files matched your search

+3 -1
View File
@@ -18,7 +18,7 @@
{"_type":"issue","id":"archie-core-n5fz","title":"Migrate existing bindings table for owner and repo columns","description":"## Bug Description\n\nArchied v1.22.0 starts successfully against the existing production task database, but binding listing logs `SQL logic error: no such column: owner`. The database was created/migrated by an earlier release and its `bindings` table has no `owner` or `repo` columns, while current `internal/store/bindings.go` selects/inserts/updates both columns.\n\n## Steps to Reproduce\n\n1. Run archied v1.22.0 against an existing database upgraded from the previous release.\n2. Open the bindings dashboard or call the bindings listing path.\n3. Observe `list bindings failed: SQL logic error: no such column: owner`.\n\n## Expected Behavior\n\nExisting databases migrate forward without data loss, and binding listing/creation/update works after upgrade.\n\n## Actual Behavior\n\nThe daemon stays up, but binding listing fails because the migration does not add the owner/repo columns required by the current binding store.\n\n## Evidence\n\n- Release: archied v1.22.0\n- Production DB: `/home/sam/.local/share/archie/archie.db-tasks.sqlite`\n- `pragma user_version = 2`\n- Existing `bindings` table has columns through `updated_at`, but no `owner` or `repo`.\n- Current code in `internal/store/bindings.go` references `owner` and `repo`.\n\n## Acceptance Criteria\n\n- Add an idempotent migration for owner/repo columns with safe defaults.\n- Preserve existing bindings and make them readable after upgrade.\n- Add regression coverage starting from the pre-owner/repo schema.\n- Verify binding list/create/update paths against both fresh and upgraded databases.\n- Do not reset or delete the production database.\n","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-09-03T06:39:09Z","created_by":"Sam Catlow","updated_at":"2026-09-03T10:16:05Z","closed_at":"2026-09-03T10:16:05Z","close_reason":"Resolved by commit 89f48a5 (PR #711); GitHub #709 closed. Stale-open copy recovered from carina during machine sync.","external_ref":"https://github.com/samcharles93/archie-core/issues/709","labels":["bug","migration","release"],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-fwvf","title":"v1.20.0 archied startup panic and schema-unsafe update rollback","description":"## Bug Description\n\nAfter `/update` installed `archied` v1.20.0, the service failed to start. The update watchdog reported `health_check: failed` and rolled the binary back to v1.19.10, but the v1.20.0 binary had already migrated the task database to schema version 2. The rollback binary then entered a restart loop because it only supports schema version 1.\n\nRestoring the matching v1.20.0 daemon did not recover the service: it panics during startup in `(*boot).connectNATS` at `bootstrap.go:366` while dereferencing `cfg.NATS.URL`.\n\n## Steps to Reproduce\n\n1. Run `/update` from the Telegram gateway, selecting archied v1.20.0.\n2. Observe the watchdog health check fail and rollback.\n3. Start the matching v1.20.0 binary against the existing config.\n\n## Expected Behavior\n\nThe released daemon starts successfully with the production config, or returns a clear configuration error. `/update` must not leave the installed binary and persisted task schema at incompatible versions.\n\n## Actual Behavior\n\nThe service is in a systemd restart loop. v1.19.10 reports `store: migrate: database schema version 2 is newer than supported version 1`; v1.20.0 panics with `runtime error: invalid memory address or nil pointer dereference` in `connectNATS` at `bootstrap.go:366`.\n\n## Evidence\n\n- Installed before recovery: `archied 1.19.10`, `archie-agent 1.19.9`\n- Update report: installed daemon/agent `1.20.0`, `health_check: failed`, `rolled_back: true`\n- Task DB: `/home/sam/.local/share/archie/archie.db-tasks.sqlite`, `PRAGMA user_version = 2`\n- v1.20.0 panic: `url := cfg.NATS.URL` in `internal/app/archied/bootstrap.go:366`\n- Current config contains `[nats] url = \"nats://172.19.0.1:4222\"`\n\n## Acceptance Criteria\n\n- Add a regression test covering startup with the production NATS configuration and nil/invalid NATS state.\n- Remove the nil dereference; startup must return a useful error or initialise the required NATS configuration.\n- Make update rollback schema-safe: either verify the candidate before migration, retain/restore compatible state, or prevent rollback to a binary that cannot read the candidate schema.\n- Exercise `/update` or an equivalent installer/restart path and verify `archied.service` reaches active, Telegram gateway starts, NATS connects, and `/version` reports the installed release.\n- Preserve the task database and existing tasks.\n\n## Environment\n\n- Host: carina.srv.catlow.cloud\n- OS: Debian/Linux 6.12.96+deb13-amd64\n- Service: systemd user unit `archied.service`\n- Update path: Telegram `/update`\n","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-09-03T04:19:21Z","created_by":"Sam Catlow","updated_at":"2026-09-03T10:16:05Z","closed_at":"2026-09-03T10:16:05Z","close_reason":"Resolved; GitHub #703 closed. Stale-open copy recovered from carina during machine sync.","external_ref":"https://github.com/samcharles93/archie-core/issues/703","labels":["bug","release","update"],"comments":[{"id":"01a06585-1d1b-76bf-833a-71ba15ab0d3d","issue_id":"archie-core-fwvf","author":"Sam Catlow","text":"## Investigation correction\n\nThe panic frame is `setupObservability`, not `connectNATS`. In the released/latest source, `setupObservability` assigns `b.d.Mappings = ms` while `b.d` is still nil; `buildDaemon` runs later in startup. The direct nil dereference is therefore the daemon wiring order, while the schema-unsafe rollback remains the separate update failure.\n\nThe implementation and regression test will cover both paths.","created_at":"2026-09-03T04:26:58Z"}],"dependency_count":0,"dependent_count":0,"comment_count":1}
{"_type":"issue","id":"archie-core-t2db.18","title":"eda: resolve mid-playbook action failure semantics (execution-time gap 1)","description":"Design-investigation ticket, same shape as the idempotency one above -- produces a design-doc resolution, not implementation. Gates multi-action playbooks (t2db.15 is deliberately single-action to avoid needing this). docs/prds/eda-playbook-engine.md's 'Execution-time gap 1' has no default yet and explicitly says a default must be a stated decision, not something nobody chose.\n\nGrounded by a crew investigation pass (2026-09-03, not committed -- content folded in here): read event-sources-and-reactions.md's producer-only/no-veto/no-mutation language, existing internal/domain/workflow stage-failure conventions (does a failing stage stop/wrap/resume?), and the load-collision report shape (drop+log+report to caller) from t2db.9-.12 as the precedent for how a run outcome should be reported.","design":"Decide and write the resolution into eda-playbook-engine.md:\n1. On action N of M failing: stop-on-first-failure (matches this doc's existing anti-clever-recovery bias) vs continue-to-independent-later-actions vs rollback. State which, and why the alternatives were rejected -- don't just restate the doc's existing hedge.\n2. What 'rollback' means (likely: nothing, since a posted forge comment isn't revocable) -- state this explicitly rather than leaving it implied.\n3. Producer-only interaction: decide whether a playbook reacting to its own action's failure by running compensating actions is in scope -- state the boundary explicitly against event-sources-and-reactions.md's producer-only rule.\n4. Condition-failure vs action-failure: J3 (CEL condition eval error -\u003e false, skip, log, continue) is already decided for conditions specifically. State cleanly how this differs from an actual action failure.\n\nSTRONG REUSABLE PRECEDENT FOUND IN THIS CODEBASE (verified directly, 2026-09-03) -- read internal/domain/workflow/workflow.go:294-352 (Run/finish/park) before designing anything new. The existing workflow engine already answers a structurally identical question for its own stages, and the answer is precise, not just 'stop on failure':\n- A real stage error: stop immediately, set ParkReason (which stage, what error), call park() -- status becomes store.StatusParked, requiring human/retry intervention. This IS this codebase's existing 'stop-on-first-failure, log the outcome, report to caller' pattern -- a playbook run failure should almost certainly reuse the SAME park/report shape (or a directly analogous one) rather than inventing new run-outcome semantics.\n- Context cancellation (ctx.Err() != nil, e.g. daemon shutdown mid-stage) is explicitly NOT treated as a failure: the task is left running so existing crash-recovery requeues it; parking here 'would publish a false failure and require manual intervention.' A playbook coordinator dispatching a Module/Workflow action needs the SAME distinction -- a daemon-shutdown interruption mid-action must not be recorded as an action failure, or every restart during a dispatch would falsely mark playbooks as broken.\n- A workflow ending without an explicit terminal outcome is itself parked as 'workflow ended without an outcome (definition bug)' -- i.e. an engine-level invariant violation gets its own distinct, honestly-labeled outcome rather than being silently treated as success. Consider whether a playbook run has an analogous 'must end with X' invariant.\n\nThis means gap 1 may reduce to: 'reuse park()'s three-way distinction (real failure / shutdown interruption / definition-bug) for playbook runs' rather than a from-scratch design -- read the actual code before deciding whether that reduction actually holds or where a playbook run's shape genuinely differs (e.g. playbooks may not have a Store.Transition-shaped persistence target the way a store.Task does -- confirm what a playbook run's own state, if any, actually gets recorded to).","acceptance_criteria":"eda-playbook-engine.md's Execution-time gap 1 section is marked resolved with a stated default (not a list of candidates) and explicit reasoning against event-sources-and-reactions.md's producer-only rule. No code changes required for this ticket to close.","notes":"Proposed resolution drafted 2026-09-03 in docs/prds/eda-playbook-engine.md, commit 99eaa7a -- reuses workflow.Run's existing three-way stage-failure distinction. Explicitly marked 'awaiting Sam's sign-off,' not settled.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-09-02T18:12:15Z","created_by":"Sam Catlow","updated_at":"2026-09-02T20:29:55Z","dependencies":[{"issue_id":"archie-core-t2db.18","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-02T18:12:15Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-t2db.17","title":"eda: resolve idempotency keying for Module/Channel/Forge actions (execution-time gap 2)","description":"Design-investigation ticket (like the CEL question, archie-core-t2db resolution in eda-playbook-engine.md) -- produces a design-doc resolution, NOT implementation. This is the sharper of the two unresolved execution-time gaps named in docs/prds/eda-playbook-engine.md's 'Execution-time gaps' section: workflow-kind actions inherit idempotency for free via TaskEnvelope; channel/forge/module actions with real side effects have no keying scheme, so a redelivered trigger event (internal/eventbus is at-least-once PublishUnique) would double-fire a comment, a message, or a billed image generation.\n\nGrounded by a crew investigation pass (2026-09-03, further-investigation.md, not committed -- content folded into this ticket): read internal/eventbus's PublishUnique key computation and existing dedup surface, TaskEnvelope's idempotency key minting/consumption path, event-sources-and-reactions.md's decided contract (extend it, don't contradict it), and the CEL context surface in internal/domain/eda/expr (event/actions fields available for key derivation).","design":"Design-decide and write into eda-playbook-engine.md:\n1. Granularity: one idempotency key per trigger-event + playbook (whole run dedups) vs per-action key derived from the run key. The doc's stated bias is the former unless a specific action needs finer dedup -- turn that bias into a stated decision.\n2. Where the key lives: does a playbook run get its own envelope/context carrying the key, and how does it reach the target position's invocation (Module.Invoke, a future Channel/Forge call)?\n3. What 'dedup' does on redelivery: is the whole run skipped, or just the already-fired action? What gets recorded?\n\nSTRONG REUSABLE PRECEDENT FOUND IN THIS CODEBASE (verified directly, 2026-09-03) -- do not design a new ledger without reading this first: internal/store/bindings.go already implements exactly this shape for playbook bindings. binding_dispatches table, unique on (binding_id, capture_id), written via RecordDispatch's 'INSERT OR IGNORE' -- a duplicate insert returns the sentinel ErrAlreadyDispatched, which dispatchBindings (internal/daemon/daemon.go:479) treats as a normal 'another cycle raced us' outcome, not an error. This is a proven, tested, at-most-once dispatch guarantee across cycles AND daemon restarts, for the exact same kind of problem (don't re-fire a binding for a capture it already dispatched). The playbook-run idempotency key almost certainly should reuse this exact pattern: a new ledger table (or a generalization of binding_dispatches) keyed on (playbook_id, event_id) or (playbook_id, trigger_event_identity), written with the same INSERT OR IGNORE + sentinel-error convention. Read internal/store/bindings.go:29-61,351-378 and internal/daemon/daemon.go:479-514 before designing anything -- this may reduce gap 2 to 'apply the existing pattern to a new key shape' rather than new design.\n4. Key derivation: a CEL-reachable expression over event fields, or a stable hash of event-identity+playbook-id -- pick one and justify it against the expr package's actual context surface, and against how capture identity is derived today (check what 'capture_id' actually is -- likely a stable hash or row id from the same capture pipeline a playbook trigger would also read).","acceptance_criteria":"eda-playbook-engine.md's Execution-time gap 2 section is marked resolved with a stated decision (not a survey of options) covering granularity, key storage/lookup, redelivery behavior, and key derivation. Consistent with event-sources-and-reactions.md's existing idempotency contract -- explicitly states how it extends rather than contradicts it. No code changes required for this ticket to close.","notes":"Proposed resolution drafted 2026-09-03 in docs/prds/eda-playbook-engine.md, commit 99eaa7a -- reuses internal/store/bindings.go's binding_dispatches ledger shape. Explicitly marked 'awaiting Sam's sign-off,' not settled. Surfaced two concrete prerequisites while drafting: t2db.15's Playbook struct needs an ID/Version (doesn't have one), and DispatchInput needs a task identity threaded through (doesn't have one either) -- both stated honestly as blockers for implementation, not glossed over.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-09-02T18:12:13Z","created_by":"Sam Catlow","updated_at":"2026-09-02T20:29:54Z","dependencies":[{"issue_id":"archie-core-t2db.17","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-02T18:12:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-t2db.17","title":"eda: resolve idempotency keying for Module/Channel/Forge actions (execution-time gap 2)","description":"Design-investigation ticket (like the CEL question, archie-core-t2db resolution in eda-playbook-engine.md) -- produces a design-doc resolution, NOT implementation. This is the sharper of the two unresolved execution-time gaps named in docs/prds/eda-playbook-engine.md's 'Execution-time gaps' section: workflow-kind actions inherit idempotency for free via TaskEnvelope; channel/forge/module actions with real side effects have no keying scheme, so a redelivered trigger event (internal/eventbus is at-least-once PublishUnique) would double-fire a comment, a message, or a billed image generation.\n\nGrounded by a crew investigation pass (2026-09-03, further-investigation.md, not committed -- content folded into this ticket): read internal/eventbus's PublishUnique key computation and existing dedup surface, TaskEnvelope's idempotency key minting/consumption path, event-sources-and-reactions.md's decided contract (extend it, don't contradict it), and the CEL context surface in internal/domain/eda/expr (event/actions fields available for key derivation).","design":"Design-decide and write into eda-playbook-engine.md:\n1. Granularity: one idempotency key per trigger-event + playbook (whole run dedups) vs per-action key derived from the run key. The doc's stated bias is the former unless a specific action needs finer dedup -- turn that bias into a stated decision.\n2. Where the key lives: does a playbook run get its own envelope/context carrying the key, and how does it reach the target position's invocation (Module.Invoke, a future Channel/Forge call)?\n3. What 'dedup' does on redelivery: is the whole run skipped, or just the already-fired action? What gets recorded?\n\nSTRONG REUSABLE PRECEDENT FOUND IN THIS CODEBASE (verified directly, 2026-09-03) -- do not design a new ledger without reading this first: internal/store/bindings.go already implements exactly this shape for playbook bindings. binding_dispatches table, unique on (binding_id, capture_id), written via RecordDispatch's 'INSERT OR IGNORE' -- a duplicate insert returns the sentinel ErrAlreadyDispatched, which dispatchBindings (internal/daemon/daemon.go:479) treats as a normal 'another cycle raced us' outcome, not an error. This is a proven, tested, at-most-once dispatch guarantee across cycles AND daemon restarts, for the exact same kind of problem (don't re-fire a binding for a capture it already dispatched). The playbook-run idempotency key almost certainly should reuse this exact pattern: a new ledger table (or a generalization of binding_dispatches) keyed on (playbook_id, event_id) or (playbook_id, trigger_event_identity), written with the same INSERT OR IGNORE + sentinel-error convention. Read internal/store/bindings.go:29-61,351-378 and internal/daemon/daemon.go:479-514 before designing anything -- this may reduce gap 2 to 'apply the existing pattern to a new key shape' rather than new design.\n4. Key derivation: a CEL-reachable expression over event fields, or a stable hash of event-identity+playbook-id -- pick one and justify it against the expr package's actual context surface, and against how capture identity is derived today (check what 'capture_id' actually is -- likely a stable hash or row id from the same capture pipeline a playbook trigger would also read).","acceptance_criteria":"eda-playbook-engine.md's Execution-time gap 2 section is marked resolved with a stated decision (not a survey of options) covering granularity, key storage/lookup, redelivery behavior, and key derivation. Consistent with event-sources-and-reactions.md's existing idempotency contract -- explicitly states how it extends rather than contradicts it. No code changes required for this ticket to close.","notes":"Proposed resolution drafted 2026-09-03 in docs/prds/eda-playbook-engine.md, commit 99eaa7a -- reuses internal/store/bindings.go's binding_dispatches ledger shape. Explicitly marked 'awaiting Sam's sign-off,' not settled. Surfaced two concrete prerequisites while drafting: t2db.15's Playbook struct needs an ID/Version (doesn't have one), and DispatchInput needs a task identity threaded through (doesn't have one either) -- both stated honestly as blockers for implementation, not glossed over.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-09-02T18:12:13Z","created_by":"Sam Catlow","updated_at":"2026-09-02T20:29:54Z","dependencies":[{"issue_id":"archie-core-t2db.17","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-02T18:12:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":3,"comment_count":0}
{"_type":"issue","id":"archie-core-e7bo","title":"fix stale wfextract go:generate directive; audit pluginextract/secretextract drift","description":"Discovered 2026-09-03 while scoping archie-core-t2db.13 (Module position). Two separate, pre-existing issues, unrelated to the playbook engine work -- do not fix as a drive-by inside that ticket.\n\n1. internal/domain/workflow/wfextract/wfextract.go's //go:generate directive still targets 'github.com/samcharles93/archie-core/internal/workflow', a path that has not existed since the domain migration (7e896c9, 2026-08-07 - the package moved to internal/domain/workflow). The committed generated file was hand-patched at some point to import the new path, but the directive itself was never fixed. Net effect: 'go generate ./...' has been broken repo-wide (at least for wfextract) since that migration, silently, for anyone who hasn't tried running it.\n\n2. Running 'go generate ./...' anyway (to see what breaks) also produced real, substantive diffs in internal/plugin/pluginextract and internal/secret/secretextract's generated symbol tables -- new wrapper types (Host, Module) appearing that are NOT in the currently-committed, in-production symbol tables. This means the Yaegi plugin and secret-engine extension surfaces have been running against stale, incomplete generated symbol tables for an unknown period: interpreted plugin/secret-engine code may be unable to reference types it should have access to. This is a latent correctness gap with real blast radius on two extension surfaces, not cosmetic drift.","design":"Two-part fix, do not conflate:\n1. Fix wfextract's directive to point at internal/domain/workflow (matching what the generated file already imports). Verify 'go generate ./internal/domain/workflow/wfextract/...' now succeeds and produces output identical (or intentionally different, documented why) to what's committed.\n2. For pluginextract/secretextract: do NOT blindly regenerate-and-commit. First determine why they're stale (when did plugin.go/secret's Engine gain the types the fresh generation adds -- git log on internal/plugin/plugin.go and internal/secret's engine files vs. when the generated files were last touched) and whether any existing test exercises a Yaegi plugin/secret-engine referencing the missing types (if none does, that's itself a coverage gap worth noting). Regenerate, gofumpt, and add/confirm a test that would have caught the drift, before committing the regenerated symbol tables -- this is a correctness-sensitive change to two live extension surfaces and needs real verification, not a mechanical re-run.","acceptance_criteria":"'go generate ./...' completes without error across the whole repo. wfextract's directive matches its actual package path. pluginextract/secretextract regeneration (if done) is backed by a test demonstrating the previously-missing types are now reachable from interpreted code, and task check passes. No behavior change to existing plugins/secret engines that were already working (regression-tested, not assumed).","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-09-02T17:17:42Z","created_by":"Sam Catlow","updated_at":"2026-09-02T17:30:34Z","closed_at":"2026-09-02T17:30:34Z","close_reason":"Fixed and gate-verified as e3a20f6 (pushed to main). wfextract directive now targets internal/domain/workflow; 'go generate ./...' completes repo-wide. All four extract surfaces regenerated; nil-guards re-applied on interface wrappers (documented IMPORTANT note restated in wfextract package doc). Previously-missing symbols proven reachable from interpreted code: wfextract (Forger/Reviewer/Trees/routing loaders) and pluginextract (Host/Module/Manifest/NewHost/HostAPIVersion) via new reachability tests; secretextract exports were current (nil-guard drift only). Red-then-green verified: fresh regen wipes guards -\u003e guard tests panic -\u003e re-apply -\u003e pass. task check clean (113/113 UI, exit 0).","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-95dj","title":"StageCommitPush discards baseline-fix commits when build makes no changes","description":"Confirmed via carina production logs (task 6, chat-spawned synthetic test task, 2026-09-02). StageBaselineGate (internal/domain/workflow/implement.go:37) found the repo's gate red at the base commit, spent 405,004 tokens/14 iterations genuinely fixing two broken pre-existing tests, and committed the fix locally via tc.Trees.CommitAll (implement.go:104) -- verified passing. plan and build stages then correctly found nothing else to do for the (synthetic, content-free) task. StageCommitPush -\u003e closeNoChangesIssue (steps.go:56) decides 'no changes' purely from tc.BuildNoChanges, which the build AgentStage sets from its own len(res.Changes)==0 (implement.go:176) -- it has zero awareness that StageBaselineGate already committed real changes two stages earlier. Never pushed, never opened a PR; the entire worktree containing a real, gate-verified fix for genuinely broken tests was discarded when the task closed as 'merged: completed -- no changes required'.\n\nCost: 669,421 tokens burned to fix a real bug that then evaporated. This recurs: any task that hits the same red baseline pays the identical tax again since the fix never lands. Evidence a prior incident already happened: an orphaned 'fix: baseline gate repair' commit (e49f3cd) sits on a stale, unmerged branch (fix/441-archied-repos-entries-cant-span-more-than-one-forge) from an earlier occurrence.","design":"Fix direction: either (a) StageBaselineGate sets a flag /flips tc.BuildNoChanges appropriately when it commits, or (b) StageCommitPush's no-changes branch checks the worktree's actual diff against the base branch (tc.Trees, similar to StageDiffCap's ChangedLines) instead of trusting tc.BuildNoChanges alone. Prefer (a): cheaper, and keeps the diff-against-base check (which already exists for StageDiffCap) from being computed twice per task.","acceptance_criteria":"A task whose baseline-fix stage committed real changes, but whose plan/build stages found nothing further to do, still pushes and opens a PR carrying the baseline-fix commit -- it must never be silently discarded. tc.BuildNoChanges (or StageCommitPush's decision) accounts for what StageBaselineGate already committed, not just the build stage's own diff. Regression test reproduces the exact scenario (baseline-fix commits, build stage reports zero changes) and proves a PR opens. task check passes.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-09-02T11:20:48Z","created_by":"Sam Catlow","updated_at":"2026-09-02T14:56:02Z","started_at":"2026-09-02T11:20:51Z","closed_at":"2026-09-02T11:25:53Z","close_reason":"Fixed via a new TaskContext.BaselineFixed flag: StageBaselineGate sets it when its own CommitAll reports a real committed change (implement.go:104-111). The build stage's OnResult only sets BuildNoChanges when its own diff is empty AND BaselineFixed is false (implement.go:177), so a baseline-only fix can no longer be masked as 'no changes'. StageCommitPush itself now calls CommitAll directly and pushes whenever either a new commit was made OR BaselineFixed is true (steps.go), instead of erroring on 'nothing to commit' when the real change already sits on the branch from the baseline-fix commit. Two new regression tests (TestStageCommitPushPushesBaselineFixEvenWithNothingNewToCommit, TestStageBaselineGateSetsBaselineFixedWhenItCommits) plus a guard test that the old empty-tree error still fires without a baseline fix. task check clean.","external_ref":"https://github.com/samcharles93/archie-core/issues/682","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-s81k","title":"Preserve bound slog attributes in persistent log sinks","description":"PR #650 scopes daemon, Web UI, and curator loggers with slog.Logger.With. internal/logging.FeedHandler.WithAttrs retains those bound attributes for the live feed but does not pass them to the wrapped handler, while Handle forwards the bare slog.Record. As a result, component is present in live Web UI entries but absent from stderr and file JSON; after restart, historical component discovery and filtering cannot see those records. Fix bound-attribute propagation without breaking slog group semantics or duplicating attributes.","acceptance_criteria":"Bound attributes appear in both Feed entries and the wrapped JSON sink; component values survive file persistence and are discoverable and filterable through historical /api/logs reads; regression tests exercise logger.With for both live and persistent paths; task check passes.","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-09-02T09:37:55Z","created_by":"Sam Catlow","updated_at":"2026-09-02T09:48:54Z","closed_at":"2026-09-02T09:43:01Z","close_reason":"Fixed: FeedHandler.WithAttrs/WithGroup now propagate to the wrapped handler, matching SystemLogHandler's existing pattern. Added regression test covering both feed and persistent sink.","external_ref":"https://github.com/samcharles93/archie-core/issues/655","dependency_count":0,"dependent_count":0,"comment_count":0}
@@ -100,6 +100,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.22","title":"eda: carry originating task identity on DispatchInput (gap-2 prereq)","description":"Prerequisite for the t2db.17 idempotency resolution. DispatchInput (internal/domain/eda/playbook/playbook.go:187) is {Labels, Kind, Event} with no task identity, so a playbook run cannot derive an event_id for a playbook_dispatches ledger key. Thread the originating task's identity (store.Task.ID, or the TaskEnvelope idempotency key that produced it). IMPORTANT: there is NO production caller of Store.Dispatch today -- DispatchInput is only constructed in tests -- so confirm which identity is actually available at the real Dispatch call site before fixing the field type; do not assume store.Task.ID is available at label/kind classification time (it is not: pollNATS/classify produces the envelope before any task row exists, so the TaskEnvelope.IdempotencyKey string is the identity available there).","design":"Add an identity field to DispatchInput, populated by the (currently nonexistent) production caller. Decide field type against the discovery-path evidence: pollNATS (internal/daemon/daemon.go:844) and the webhook receiver (receiver.go:243) both compute kind/labels from a TaskEnvelope BEFORE any store.Task row exists, and TaskEnvelope.IdempotencyKey() returns 'archie:owner/repo/number' -- so a string identity (the idempotency key) is the available, stable value at the dispatch point, not a store.Task.ID int64. Add a test proving DispatchInput carries it end to end; wire the real production caller only when the coordinator lands.","acceptance_criteria":"DispatchInput carries the originating task's identity (typed as decided against evidence). A test demonstrates the identity is present on the input and reaches the key-derivation path. No production dispatch caller is wired in this ticket (none exists today). task check passes.","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","estimated_minutes":30,"created_at":"2026-09-04T17:07:09Z","created_by":"Sam Catlow","updated_at":"2026-09-04T17:10:44Z","closed_at":"2026-09-04T17:10:44Z","close_reason":"Implementation complete and gate-verified for its scope. Playbook gains ID (path-relative) + Version (sha256 content hash), populated in loadOne; DispatchInput gains TaskID string carrying TaskEnvelope.IdempotencyKey(), per evidence that the discovery point computes kind/labels before any store.Task row exists. Red-green verified; gofumpt/vet/build/golangci-lint clean for the package. NOTE: task check has 5 lint failures PRE-EXISTING at HEAD in unrelated files (bootstrap.go cyclop/nestif, install_script_test.go noctx, telegram_setup_test.go usetesting) -- not caused by this change. Forced close because the earlier blocked-by: t2db.17 dependency is inverted -- .17 is doc-only sign-off; these are its implementation prereqs, not gated on it.","dependencies":[{"issue_id":"archie-core-t2db.22","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-04T17:07:09Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.22","depends_on_id":"archie-core-t2db.17","type":"blocks","created_at":"2026-09-04T17:07:09Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-t2db.21","title":"eda: thread Playbook ID and Version for idempotency-ledger keying (gap-2 prereq)","description":"Prerequisite for the t2db.17 idempotency resolution. The shipped Playbook struct (internal/domain/eda/playbook/playbook.go) is {Trigger, Actions} with no ID and no Version, so a playbook_dispatches ledger keyed on (playbook_id, playbook_version, event_id) cannot be built. Add ID (stable path-relative identifier) and Version (content hash of the loaded file, recomputed on every load), both populated at load time. Mirror Binding.Version's purpose: pin dispatched-run provenance to the exact definition that was active when it fired.","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","estimated_minutes":30,"created_at":"2026-09-04T17:07:01Z","created_by":"Sam Catlow","updated_at":"2026-09-04T17:10:44Z","closed_at":"2026-09-04T17:10:44Z","close_reason":"Implementation complete and gate-verified for its scope. Playbook gains ID (path-relative) + Version (sha256 content hash), populated in loadOne; DispatchInput gains TaskID string carrying TaskEnvelope.IdempotencyKey(), per evidence that the discovery point computes kind/labels before any store.Task row exists. Red-green verified; gofumpt/vet/build/golangci-lint clean for the package. NOTE: task check has 5 lint failures PRE-EXISTING at HEAD in unrelated files (bootstrap.go cyclop/nestif, install_script_test.go noctx, telegram_setup_test.go usetesting) -- not caused by this change. Forced close because the earlier blocked-by: t2db.17 dependency is inverted -- .17 is doc-only sign-off; these are its implementation prereqs, not gated on it.","dependencies":[{"issue_id":"archie-core-t2db.21","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-04T17:07:01Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.21","depends_on_id":"archie-core-t2db.17","type":"blocks","created_at":"2026-09-04T17:07:01Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-wdn0","title":"Reconcile beads\u003c-\u003eGitHub issue state after cross-machine sync","description":"After the 2026-09-03 helix/carina reconciliation, bead statuses are authoritative locally but GitHub was never reconciled. Walk closed beads against gh issue list --state all via external_ref and push the differences. Per prior incident notes: bd github push takes ONE id per invocation (multiple ids silently no-op and exit 0), and identical updated_at timestamps make sync skip an issue forever -- close directly with gh issue close in that case.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-09-03T12:28:29Z","created_by":"Sam Catlow","updated_at":"2026-09-03T12:28:29Z","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-mxls","title":"chat: /agents command is permanently unconfigured in production","description":"internal/gateway.Router.Agents (AgentReader interface, AgentInfo{ID,Title,Status,Identity}) backs the /agents command (handleAgents, gateway.go:1127), and /agents is registered and advertised: in gateway.go's localCommands/localCommandSpecs (description: 'List tasks currently being worked'), and in internal/channels/telegram/commands.go's gatewayCommandSpecs (same description, published to Telegram's command menu and /help).\n\nVerified via grep across internal/: Router.Agents is NEVER assigned outside of gateway_test.go's fakeAgentReader. None of the four composition-root call sites that build a Router (bootstrap.go's web/email/webhook routers, telegram_setup.go's buildTelegramRouter) ever set router.Agents. So in every real deployment, typing /agents in any channel returns the hardcoded fallback: 'Agent listing is not configured.' -- despite Telegram advertising it in its command menu with a description implying it works.\n\nFound while implementing archie-core-wp9s (the /status vs /tasks split): the new /tasks command (gateway.ChatTaskLister-backed) covers almost exactly what /agents' AgentInfo{ID,Title,Status,Identity} shape was meant to show, just fuller (adds workflow/stage/age/park-reason). AgentReader/AgentInfo appear to be an earlier, abandoned attempt at the same feature that was never connected during wiring.\n\nSam's call, not resolved here: (a) wire AgentReader to a real implementation (e.g. an adapter over the same ListChatTasks path /tasks now uses, if /agents is meant to mean something distinct from /tasks -- e.g. actively-executing containers rather than all non-terminal store tasks), (b) delete /agents (AgentReader, AgentInfo, handleAgents, both command-spec registrations, and their tests) now that /tasks exists and covers the same ground, or (c) something else entirely if 'agents' was meant to be a different concept than 'tasks'. See docs/prds/status-health-surface.md's note on this for the /tasks cross-reference.","acceptance_criteria":"A decision is recorded (wire, delete, or redefine) and /agents' advertised behavior in Telegram's menu/help matches what it actually does when invoked -- no command may be discoverable and described as functional while permanently returning a not-configured placeholder.","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-09-02T21:17:31Z","created_by":"Sam Catlow","updated_at":"2026-09-02T21:17:31Z","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-t2db.20","title":"eda: LSP/serve mode for cmd/archie-playbooks","description":"Second entrypoint of the gopls-shaped standalone binary from t2db.12 (lint mode already shipped). Sam explicitly kept this in scope, not deferred, because it's the same schema source as the linter, just a different consumer -- the design doc's shared-package, thin-consumer principle.\n\nGrounded by a crew investigation pass (2026-09-03): the loader decodes with yaml.Unmarshal into a plain map, which discards line numbers -- today's lint findings are file-granular only. A useful LSP (hover/completion/inline errors) needs real positions, so the yaml.Node decoding upgrade is a practical prerequisite, not a nice-to-have. internal/domain/eda/expr's Compile/Eval already return structured errors that should map cleanly to diagnostics -- confirm this rather than re-deriving error shapes.","design":"Two-part scope, decide whether to split into two tickets or do both together once you've read the code:\n1. yaml.Node decoding upgrade: replace the plain-map yaml.Unmarshal decode path (internal/domain/workflow/routing.go -- three call sites at time of writing, all doing 'var raw map[string]string; yaml.Unmarshal(data, \u0026raw)') with yaml.Node-based decoding that retains line/column info, without changing any existing collision-detection behavior.\n\nVERIFIED FEASIBLE, concrete shape (2026-09-03): gopkg.in/yaml.v3's Node type has Line/Column fields populated directly by the decoder (confirmed in the vendored source). For a mapping node (Kind == MappingNode), Content is a flat []*Node alternating key-node, value-node pairs -- so decoding into *yaml.Node instead of map[string]string gives Content[i].Line for the i-th key's line number directly, no manual line-counting needed. The upgrade is: yaml.Unmarshal(data, \u0026node) into a *yaml.Node instead of the map, then walk node.Content in pairs extracting key.Value/value.Value (same strings as today) plus key.Line (new). This is a pure additive capability -- existing collision error MESSAGES should stay byte-identical where line info isn't yet surfaced in them, add line numbers to the error format once available. Do not change collision-detection LOGIC, only the decode representation.\n\n2. serve/lsp command: add a new entry to cmd/archie-playbooks's existing command table (do not restructure -- t2db.12 built it explicitly to take this addition without restructuring, confirmed by reading cmd/archie-playbooks/main.go's commands map). Scope: a minimal LSP surface (diagnostics at minimum; hover/completion if straightforward) over the same compile/validate path the lint command already uses. Weigh a tiny hand-rolled LSP protocol implementation (fits organisation.md's thin cmd/ rule and the narrow-capability-family principle) against pulling in an LSP library -- vet any new dependency via the vetting-dependencies skill before adding it, same rigor as the CEL decision (docs/prds/eda-playbook-engine.md's resolved open question 1) -- this is a real, undecided choice, not preempted here.","acceptance_criteria":"cmd/archie-playbooks gains a serve (or lsp) subcommand alongside lint, using the same underlying compile/validate calls -- no second validation path. Diagnostics report file:line where the yaml.Node upgrade provides it. Existing lint-mode tests and behavior are unchanged (regression-tested). task check passes.","notes":"Full vetting record for sourcegraph/jsonrpc2, 2026-09-03 (same rigor as the approved cel.dev/cel-go decision):\n\n- Security: zero advisories on record (GitHub Advisory Database, queried directly). License: MIT (compatible).\n- Maintenance: genuinely active -- commits within the last month (Aug 2026), real CI hygiene work (not a dead repo with a stale README). Not archived (unlike sourcegraph/go-lsp, the other candidate, which IS archived and was ruled out).\n- Dependency footprint: measured directly (not assumed) -- importing only the jsonrpc2.Conn surface pulls in exactly ONE dependency, no gorilla/websocket at all (go.sum showed a single entry). websocket is a lazy/optional dependency of the library, only pulled in if its WS-transport-specific APIs are actually called -- a stdio-only LSP transport never touches it.\n- Binary size cost: measured directly, same baseline methodology as the CEL vetting -- a minimal Go binary baseline was 2,343,283 bytes; adding jsonrpc2 (importing Conn) measured 2,715,265 bytes. Cost: +371,982 bytes (~0.36MB). Far lighter than CEL's +13MB, as expected for a narrow JSON-RPC engine vs. a full expression-language runtime.\n\nVerdict: sourcegraph/jsonrpc2 clears vetting cleanly -- safe, cheap, active, correctness-sensitive-and-worth-depending-on (same reasoning as CEL: reimplementing JSON-RPC request/response ID correlation by hand is a real correctness surface, not free). This is a complete, ready-to-approve recommendation, not yet approved -- do not add the dependency or start implementation until Sam signs off, miLine truncated
+34 -3
View File
@@ -14,6 +14,7 @@
package playbook
import (
"crypto/sha256"
"fmt"
"os"
"path/filepath"
@@ -35,6 +36,19 @@ type Store struct {
// Playbook is one trigger+actions document.
type Playbook struct {
// ID is the playbook's stable identity for execution-time idempotency:
// its file path relative to the configured directory root. It is unique
// within a single Load because the EDA loader walks one directory's
// entries and filenames there are inherently unique -- the doc's claim
// about "the directory-loader's collision rule" belongs to the ROUTING
// loader (workflow.LoadPlaybookDirs), a different loader.
ID string
// Version is a content hash of the loaded file, recomputed on every
// load. It pins dispatched-run provenance to the exact definition active
// when the run fired, mirroring Binding.Version's purpose, without a
// database row.
Version string
Trigger Trigger
Actions []Action
}
@@ -109,7 +123,7 @@ func Load(dir string) (*Store, error) {
store := &Store{exprEnv: expr.NewEnv()}
for _, name := range names {
path := filepath.Join(dir, name)
pb, err := loadOne(path, store.exprEnv)
pb, err := loadOne(dir, path, store.exprEnv)
if err != nil {
return nil, err
}
@@ -118,18 +132,27 @@ func Load(dir string) (*Store, error) {
return store, nil
}
// loadOne loads and validates a single playbook file.
func loadOne(path string, env *expr.Env) (*Playbook, error) {
// loadOne loads and validates a single playbook file, deriving its stable ID
// (path relative to the configured root) and a content-hash Version.
func loadOne(dir, path string, env *expr.Env) (*Playbook, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read playbook %s: %w", path, err)
}
id := path
if rel, relErr := filepath.Rel(dir, path); relErr == nil {
id = rel
}
var raw rawPlaybook
if err := yaml.Unmarshal(data, &raw); err != nil {
return nil, fmt.Errorf("parse playbook %s: %w", path, err)
}
pb := &Playbook{
ID: filepath.ToSlash(id),
Version: fmt.Sprintf("%x", sha256.Sum256(data)),
Trigger: Trigger{
Kind: workintake.Kind(strings.TrimSpace(raw.Trigger.Kind)),
Labels: raw.Trigger.Labels,
@@ -189,6 +212,14 @@ type DispatchInput struct {
Labels []string
// Kind is the routing kind the labels produced (workintake.KindForLabels).
Kind string
// TaskID is the originating task's identity, used to derive the event_id
// half of the playbook_dispatches idempotency ledger key. It carries the
// TaskEnvelope.IdempotencyKey() value ("archie:owner/repo/number"), the
// stable identity available at the discovery/dispatch point (pollNATS and
// the webhook receiver both compute kind/labels from a TaskEnvelope before
// any store.Task row exists). It is NOT a store.Task.ID int64, which does
// not exist until the task is persisted.
TaskID string
// Event is the event payload exposed as `event` in CEL expressions. For
// a workflow-kind dispatch this carries the label/kind fields cheaply
// available at this point.
@@ -260,6 +260,117 @@ func TestLoadMissingDirIsEmptyStore(t *testing.T) {
}
}
// TestPlaybookIDIsPathRelative: the playbook's ID is its path relative to the
// configured directory root, so it is stable across re-Loads of the same file
// and unique within one directory (the EDA loader has no collision detector;
// per-directory-unique filenames guarantee it).
func TestPlaybookIDIsPathRelative(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
`)
store, err := Load(dir)
if err != nil {
t.Fatalf("Load: %v", err)
}
if len(store.Playbooks) != 1 {
t.Fatalf("loaded %d playbooks, want 1", len(store.Playbooks))
}
pb := store.Playbooks[0]
if pb.ID != "pb.yaml" {
t.Errorf("ID = %q, want %q (path relative to dir root)", pb.ID, "pb.yaml")
}
}
// TestPlaybookVersionIsContentDerived: the version is a content hash of the
// loaded file, recomputed on every load -- stable for unchanged content,
// changing when content changes (mirrors Binding.Version's provenance pin).
func TestPlaybookVersionIsContentDerived(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
`)
storeA, err := Load(dir)
if err != nil {
t.Fatalf("Load: %v", err)
}
if storeA.Playbooks[0].Version == "" {
t.Fatal("Version = empty, want a content hash")
}
// Re-load unchanged content: identical version.
storeB, err := Load(dir)
if err != nil {
t.Fatalf("Load: %v", err)
}
if storeA.Playbooks[0].Version != storeB.Playbooks[0].Version {
t.Fatalf("Version changed for unchanged content: %q -> %q",
storeA.Playbooks[0].Version, storeB.Playbooks[0].Version)
}
// Change content: version must change.
writeFile(t, dir, "pb.yaml", `
trigger:
kind: feature
actions:
- position: workflow
workflow: implement
`)
storeC, err := Load(dir)
if err != nil {
t.Fatalf("Load: %v", err)
}
if storeA.Playbooks[0].Version == storeC.Playbooks[0].Version {
t.Fatal("Version unchanged for changed content, want a change")
}
}
// TestDispatchInputCarriesTaskIdentity: the originating task's identity is
// carried on the dispatch input end to end, so a caller can derive the
// event_id half of the playbook_dispatches ledger key. The chosen identity is
// the TaskEnvelope.IdempotencyKey() string ("archie:owner/repo/number") --
// the value available at the discovery/dispatch point (pollNATS + webhook
// receiver both compute kind/labels from a TaskEnvelope before any
// store.Task row exists), NOT a store.Task.ID int64.
func TestDispatchInputCarriesTaskIdentity(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", `
trigger:
kind: bug
actions:
- position: workflow
workflow: tdd
`)
store, err := Load(dir)
if err != nil {
t.Fatalf("Load: %v", err)
}
reg := registryWith("tdd")
input := DispatchInput{
Labels: []string{"bug"},
Kind: "bug",
TaskID: "archie:samcharles93/archie-core/42",
Event: map[string]any{"priority": 3},
}
dispatched := store.Dispatch(reg, input)
if dispatched == nil {
t.Fatal("Dispatch = nil, want the tdd workflow")
}
// The input still carries the identity after dispatch; the caller uses it
// to key the ledger.
if got, want := input.TaskID, "archie:samcharles93/archie-core/42"; got != want {
t.Fatalf("TaskID = %q, want %q", got, want)
}
}
// TestShippedExamplePlaybookLoads verifies the operator-facing example
// (examples/eda-playbooks/bug-tdd.yaml) loads through the real loader --
// the proof the shipped shape works, not just test fixtures.