From 030b4ed17628e009e7275b7f2bda923bb9f52bb4 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 3 Oct 2026 21:47:46 +1000 Subject: [PATCH] refactor: strip doc and issue narration from code comments Remove PRD/doc paths, bead IDs, phase notes and deleted-test references from comments; drop test-only hooks left by the test deletion. Includes in-progress archied bootstrap, gateway and query changes. --- cmd/archie-prbench/main.go | 48 -- cmd/archie-state-store/main.go | 3 +- cmd/archie-state-store/recovery.go | 2 +- cmd/archie-ui/main.go | 2 - examples/modules/log.go | 6 +- internal/agentexec/loop_runner.go | 2 +- internal/agentexec/protocol.go | 6 +- internal/agentexec/subjects.go | 4 +- internal/agentexec/systemlog.go | 2 +- internal/agentexec/toolset.go | 5 +- internal/app/agentworker/task_execution.go | 34 +- internal/app/agentworker/worker.go | 15 +- internal/app/archied/access_reset.go | 3 +- internal/app/archied/binding_cipher.go | 6 +- internal/app/archied/bootstrap.go | 534 ++---------------- internal/app/archied/chat_identity.go | 7 +- internal/app/archied/chat_setup.go | 7 +- internal/app/archied/control_plane.go | 11 +- internal/app/archied/control_plane_watch.go | 39 +- internal/app/archied/gateway.go | 15 +- internal/app/archied/gateway_runtime.go | 4 - internal/app/archied/health.go | 9 +- internal/app/archied/kit_launcher.go | 1 - internal/app/archied/main.go | 41 +- internal/app/archied/mcp_reconcile.go | 1 - internal/app/archied/plugin_reconcile.go | 3 +- internal/app/archied/readiness.go | 5 +- internal/app/archied/reload.go | 34 +- internal/app/archied/sd_notify.go | 6 +- internal/app/archied/state_store.go | 43 +- internal/app/archied/state_store_client.go | 2 +- internal/app/archied/state_store_recovery.go | 1 - internal/app/archied/state_store_toolcalls.go | 8 - internal/app/archied/step_vocabulary.go | 7 +- internal/app/archied/update_relay.go | 2 +- .../app/archiemessaging/channel_status.go | 6 +- internal/app/archiemessaging/compose.go | 6 +- internal/app/archiemessaging/config.go | 3 +- internal/app/archiemessaging/options.go | 5 +- internal/app/archiemessaging/reconcile.go | 5 +- internal/app/archiemessaging/supervise.go | 3 +- .../app/archiemessaging/telegram_features.go | 16 +- internal/app/archieplaybooks/lint.go | 2 +- internal/app/archieui/compose.go | 50 +- internal/app/archieui/config.go | 20 +- internal/app/archieui/options.go | 29 +- internal/app/archieui/readiness.go | 1 - internal/app/archieui/run.go | 7 +- internal/app/controlplane/agent_profiles.go | 15 +- internal/app/controlplane/channel_settings.go | 4 +- internal/app/controlplane/client.go | 6 +- .../app/controlplane/container_settings.go | 8 +- .../app/controlplane/credential_bindings.go | 1 - .../app/controlplane/operational_settings.go | 15 +- internal/app/controlplane/registry.go | 11 +- internal/app/controlplane/review_settings.go | 1 - internal/app/controlplane/runtime_config.go | 7 +- internal/app/controlplane/schema.go | 1 - .../app/controlplane/workflow_projector.go | 2 +- internal/buildinfo/buildinfo.go | 2 +- internal/channels/email/email.go | 1 - internal/channels/status/status.go | 2 +- internal/channels/telegram/commands.go | 9 +- internal/channels/telegram/live.go | 17 +- internal/channels/telegram/richblocks.go | 14 +- internal/channels/telegram/telegram.go | 6 +- internal/channels/webhook/webhook.go | 3 +- internal/config/chat_frontends.go | 4 +- internal/config/config.go | 129 ++--- internal/config/secret_ref.go | 1 - internal/config/services.go | 2 +- internal/container/pool.go | 18 +- internal/daemon/agent_status.go | 11 +- internal/daemon/daemon.go | 64 +-- internal/daemon/pr_review_prefetch.go | 14 +- internal/daemon/reactions.go | 8 +- internal/domain/access/access.go | 2 +- internal/domain/access/authorizer.go | 2 +- internal/domain/access/request.go | 2 +- internal/domain/access/roles.go | 1 - internal/domain/access/store.go | 4 +- internal/domain/applystatus/applystatus.go | 2 +- internal/domain/binding/binding.go | 7 +- internal/domain/curator/activity.go | 2 +- internal/domain/curator/contract.go | 16 +- internal/domain/curator/definition_engine.go | 5 +- internal/domain/curator/registrar.go | 13 +- internal/domain/curator/registry.go | 4 +- internal/domain/curator/runtime.go | 4 +- internal/domain/curator/wake.go | 2 +- internal/domain/eda/expr/expr.go | 7 +- internal/domain/eda/module/log/log.go | 8 +- internal/domain/eda/module/module.go | 13 +- internal/domain/eda/playbook/coordinator.go | 4 +- internal/domain/eda/playbook/playbook.go | 23 +- internal/domain/eda/playbook/run.go | 2 +- internal/domain/embedding/contract.go | 7 +- internal/domain/eventtype/eventtype.go | 10 +- .../domain/harnesssecret/harnesssecret.go | 12 +- internal/domain/image/contract.go | 8 +- internal/domain/mapping/mapping.go | 6 +- internal/domain/memory/contract.go | 14 +- internal/domain/messaging/chat_contract.go | 2 +- internal/domain/messaging/chat_stream.go | 1 - internal/domain/messaging/inbound.go | 4 +- internal/domain/messaging/message.go | 12 +- internal/domain/messaging/session_store.go | 6 +- internal/domain/org/org.go | 6 +- internal/domain/org/store.go | 4 +- internal/domain/sampling/contract.go | 10 +- internal/domain/sampling/staleness.go | 2 +- internal/domain/scheduling/contract.go | 2 +- internal/domain/source/source.go | 4 +- .../domain/storecontract/storecontract.go | 116 ++-- internal/domain/storepkg/authority.go | 9 +- internal/domain/storepkg/installed.go | 2 +- internal/domain/taskactions/service.go | 33 +- internal/domain/workflow/agent.go | 11 +- internal/domain/workflow/command_run.go | 13 +- internal/domain/workflow/definition.go | 4 +- internal/domain/workflow/feasibility.go | 39 +- internal/domain/workflow/gate_environment.go | 4 +- internal/domain/workflow/implement.go | 10 +- internal/domain/workflow/outputs.go | 2 +- .../domain/workflow/prreview/bench/bench.go | 1 - internal/domain/workflow/prreview/budget.go | 8 +- internal/domain/workflow/prreview/coverage.go | 10 +- internal/domain/workflow/prreview/diff.go | 3 +- .../domain/workflow/prreview/dimension.go | 9 +- internal/domain/workflow/prreview/intake.go | 8 +- internal/domain/workflow/prreview/scoring.go | 24 +- internal/domain/workflow/prreview_headless.go | 4 +- internal/domain/workflow/prreview_own_pr.go | 20 +- internal/domain/workflow/prreview_stages.go | 199 ++----- .../domain/workflow/prreview_stages_verify.go | 123 ++-- internal/domain/workflow/remediate.go | 14 +- internal/domain/workflow/routing.go | 54 +- internal/domain/workflow/steps.go | 4 +- internal/domain/workflow/task/caller.go | 12 +- internal/domain/workflow/task/interface.go | 20 +- internal/domain/workflow/task/review_gate.go | 6 +- internal/domain/workflow/task/step.go | 10 +- internal/domain/workflow/task/task.go | 44 +- internal/domain/workflow/task_aliases.go | 4 +- internal/domain/workflow/triage.go | 6 +- internal/domain/workflow/workflow.go | 39 +- internal/domain/workflow/workflow_call.go | 15 +- internal/domain/workintake/envelope.go | 17 +- internal/domain/workintake/review_envelope.go | 6 +- internal/domain/workintake/subjects.go | 2 +- internal/eventbus/doc.go | 4 - internal/events/events.go | 20 +- internal/forge/webhook/receiver.go | 19 +- internal/gateway/chat_contract_aliases.go | 2 +- internal/gateway/compression.go | 16 +- internal/gateway/gateway.go | 6 +- internal/gateway/message_dedup.go | 1 - internal/gateway/session_commands.go | 2 +- internal/gateway/session_store_memory.go | 10 +- internal/gateway/slash_access.go | 15 +- internal/gateway/tasks.go | 20 +- internal/gateway/turn.go | 3 +- internal/gateway/turn_memory.go | 17 +- internal/gateway/turn_memory_tool.go | 10 +- internal/infrastructure/access/engine.go | 3 +- .../agenttransport/nats/transport.go | 24 +- .../infrastructure/bindingcipher/cipher.go | 4 +- .../infrastructure/captureintake/receiver.go | 24 +- .../infrastructure/configuration/defaults.go | 8 +- .../configuration/denied_keys.go | 2 +- internal/infrastructure/configuration/doc.go | 16 +- .../infrastructure/configuration/loader.go | 10 +- .../configuration/setup/step_provider.go | 8 +- .../configuration/tomlwrite/tomlwrite.go | 23 +- .../infrastructure/configuration/validate.go | 19 +- .../infrastructure/controlplanerpc/client.go | 2 +- internal/infrastructure/egress/grants.go | 10 +- internal/infrastructure/egress/oauth.go | 2 +- internal/infrastructure/eventbus/nats/doc.go | 1 - .../infrastructure/eventbus/nats/embedded.go | 2 +- internal/infrastructure/gatewayrpc/auth.go | 2 +- .../infrastructure/kit/credential_file.go | 12 +- internal/infrastructure/kit/kit.go | 2 +- internal/infrastructure/kitrun/launcher.go | 20 +- .../infrastructure/memory/builtin_engine.go | 25 +- internal/infrastructure/memory/history.go | 15 +- internal/infrastructure/memory/marker.go | 11 +- internal/infrastructure/postgres/access.go | 4 +- internal/infrastructure/postgres/orgs.go | 1 - .../infrastructure/postgres/pgtest/pgtest.go | 2 - .../postgres/postgresdb/access.sql.go | 17 +- .../postgres/postgresdb/audit.sql.go | 2 - .../postgres/postgresdb/call_tasks.sql.go | 10 +- .../postgres/postgresdb/edastore.sql.go | 3 - .../postgres/queries/access.sql | 18 +- .../infrastructure/postgres/queries/audit.sql | 2 - .../postgres/queries/call_tasks.sql | 10 +- .../postgres/queries/edastore.sql | 3 - internal/infrastructure/postgres/steps.go | 28 +- internal/infrastructure/postgres/store.go | 30 +- internal/infrastructure/prsource/archive.go | 15 +- internal/infrastructure/prsource/prsource.go | 22 +- internal/infrastructure/readiness/probes.go | 7 +- .../servicediscovery/nats/doc.go | 10 +- .../infrastructure/sessioncurator/adapter.go | 14 +- .../sessioncurator/sessioncurator.go | 18 +- .../skillcurator/skillcurator.go | 22 +- internal/infrastructure/skillcurator/store.go | 17 +- internal/infrastructure/staterpc/access.go | 2 +- .../infrastructure/staterpc/access_client.go | 4 +- internal/infrastructure/staterpc/auth.go | 5 +- internal/infrastructure/staterpc/client.go | 17 +- internal/infrastructure/staterpc/dial.go | 4 +- internal/infrastructure/staterpc/server.go | 47 +- .../infrastructure/staterpc/task_grants.go | 18 +- internal/infrastructure/staterpc/values.go | 20 +- internal/infrastructure/taskactions/store.go | 4 +- .../workflowsteps/workflowsteps.go | 16 +- internal/pairing/store.go | 5 +- internal/plugin/host.go | 2 +- internal/plugin/plugin.go | 6 +- internal/releaseupdate/command.go | 2 +- internal/sdnotify/sdnotify.go | 12 +- internal/secret/secret.go | 2 +- internal/servicediscovery/doc.go | 14 +- internal/skill/plugin.go | 2 +- internal/skill/skill.go | 14 +- internal/skillscript/yaegi.go | 2 +- internal/taskstate/taskstate.go | 7 +- .../taskstate/taskstatetest/taskstatetest.go | 105 ---- internal/taskstate/transitions.go | 4 +- internal/tools/builtin/bridge.go | 2 +- internal/tools/builtin/builtin.go | 2 +- internal/tools/builtin/edit.go | 2 +- internal/tools/builtin/find.go | 2 +- internal/tools/builtin/fsutil.go | 2 +- internal/tools/builtin/grep.go | 2 +- internal/tools/builtin/mutation.go | 2 +- internal/tools/builtin/pathutil.go | 2 +- internal/tools/builtin/procgroup_unix.go | 2 +- internal/tools/builtin/procgroup_windows.go | 2 +- internal/tools/builtin/read.go | 2 +- internal/tools/builtin/read_outline.go | 2 +- internal/tools/builtin/read_tracker.go | 2 +- internal/tools/builtin/registry.go | 2 +- internal/tools/builtin/shell.go | 2 +- internal/tools/builtin/truncate.go | 2 +- internal/tools/builtin/write.go | 2 +- internal/tools/command/parse.go | 2 +- internal/webhookguard/doc.go | 8 +- internal/webhookguard/ratelimit.go | 15 +- internal/webhookguard/redact.go | 14 +- internal/webui/api_apply_status.go | 2 +- internal/webui/api_chat.go | 7 +- internal/webui/api_config.go | 8 +- internal/webui/api_curators.go | 6 +- internal/webui/api_harness.go | 16 +- internal/webui/api_mapping.go | 8 +- internal/webui/api_skills.go | 2 +- internal/webui/api_source.go | 9 +- internal/webui/api_tasks.go | 7 +- internal/webui/api_tasks_attempts.go | 8 +- internal/webui/api_workflows.go | 1 - internal/webui/authorize.go | 21 +- internal/webui/config_schema.go | 9 +- internal/webui/event_pump.go | 19 +- internal/webui/server.go | 50 +- internal/webui/sse.go | 5 - internal/worktree/worktree.go | 15 +- 269 files changed, 1201 insertions(+), 2609 deletions(-) delete mode 100644 cmd/archie-prbench/main.go delete mode 100644 internal/taskstate/taskstatetest/taskstatetest.go diff --git a/cmd/archie-prbench/main.go b/cmd/archie-prbench/main.go deleted file mode 100644 index cab820189..000000000 --- a/cmd/archie-prbench/main.go +++ /dev/null @@ -1,48 +0,0 @@ -// Command archie-prbench scores the PR reviewer on the Martian -// Code-Review-Bench problems. See docs/prds/pr-review-agent.md, Verification. -package main - -import ( - "context" - "flag" - "fmt" - "os" - "os/signal" - "strings" - "syscall" - - "github.com/samcharles93/archie-core/internal/app/prbench" - "github.com/samcharles93/archie-core/internal/infrastructure/configuration" -) - -func main() { os.Exit(run()) } - -func run() int { - var opts prbench.Options - var problems string - flag.StringVar(&opts.Config, "config", configuration.DefaultConfigPath(), "configuration file whose providers serve the reviewer and judge") - flag.StringVar(&opts.Fixtures, "findings", "", "directory of .json findings to rescore; omit to review live") - flag.StringVar(&opts.ReviewModel, "review-model", "", "provider/model for the review role in live runs") - flag.StringVar(&opts.ClassifyModel, "classification-model", "", "provider/model for the classification role in live runs") - flag.StringVar(&opts.JudgeModel, "judge-model", "anthropic/claude-sonnet-4.6", "provider/model of the independent judge") - flag.StringVar(&opts.Out, "out", "bin/prbench-results", "directory for per-problem results and summary.json") - flag.StringVar(&opts.Resume, "resume", "", "reuse complete results from a previous run with the same models") - flag.StringVar(&problems, "problems", "", "comma-separated problem ids (default: all)") - flag.IntVar(&opts.Concurrency, "concurrency", 4, "problems judged at once") - flag.Parse() - opts.GitHubToken = os.Getenv("GH_TOKEN") - if opts.GitHubToken == "" { - opts.GitHubToken = os.Getenv("GITHUB_TOKEN") - } - if problems != "" { - opts.Problems = strings.Split(problems, ",") - } - - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) - defer stop() - if _, err := prbench.Run(ctx, opts, os.Stdout); err != nil { - fmt.Fprintln(os.Stderr, "archie-prbench:", err) - return 1 - } - return 0 -} diff --git a/cmd/archie-state-store/main.go b/cmd/archie-state-store/main.go index 30cf1c573..0048c25fd 100644 --- a/cmd/archie-state-store/main.go +++ b/cmd/archie-state-store/main.go @@ -1,6 +1,5 @@ // Command archie-state-store hosts the State Store's gRPC contract and is the -// only process that owns the PostgreSQL stores behind it. See -// docs/prds/state-store-contract.md §5, §9 and §11. +// only process that owns the PostgreSQL stores behind it. package main import ( diff --git a/cmd/archie-state-store/recovery.go b/cmd/archie-state-store/recovery.go index d22be66e2..42ff19115 100644 --- a/cmd/archie-state-store/recovery.go +++ b/cmd/archie-state-store/recovery.go @@ -14,7 +14,7 @@ import ( // recoveryUsage is the whole flag surface of the offline recovery commands. // They are subcommands of this binary rather than a recovery binary of their // own: offline database maintenance belongs to the process that owns the file -// and its path layout (docs/architecture/organisation.md#process-boundaries). +// and its path layout. const recoveryUsage = `usage: archie-state-store [flags] With no command, archie-state-store serves the State Store gRPC contract. diff --git a/cmd/archie-ui/main.go b/cmd/archie-ui/main.go index 55cca4cf1..020d28e32 100644 --- a/cmd/archie-ui/main.go +++ b/cmd/archie-ui/main.go @@ -3,8 +3,6 @@ // contracts. It is the .5.2 companion to archie-gateway and // archie-state-store: a thin main that parses process inputs and hands them // to archieui.Run. -// -// See docs/prds/ui-service-boundary.md for the ratified boundary. package main import ( diff --git a/examples/modules/log.go b/examples/modules/log.go index 34080bad0..465aed7cb 100644 --- a/examples/modules/log.go +++ b/examples/modules/log.go @@ -1,8 +1,8 @@ //go:build ignore -// log module implementation for archied's EDA playbook engine (Module -// position, t2db.13). The first action kind: side-effect-free -- it only -// writes a line to the daemon's log, so it proves the schema -> go:generate +// log module implementation for archied's EDA playbook engine. The first action +// kind: side-effect-free -- it only writes a line to the daemon's log, so it +// proves the schema -> go:generate // -> Yaegi load -> ModuleRegistry -> dispatch mechanism end to end without // needing an idempotency answer. // diff --git a/internal/agentexec/loop_runner.go b/internal/agentexec/loop_runner.go index eeba495ae..c1863e306 100644 --- a/internal/agentexec/loop_runner.go +++ b/internal/agentexec/loop_runner.go @@ -358,7 +358,7 @@ func isNonEmptyString(object map[string]json.RawMessage, field string) bool { } // scriptToolSet exposes run_go_script: interpreting a Yaegi Go script -// bundled with a skill (.agents/skills//scripts/*.go) or living +// bundled with a skill or living // anywhere else in the workspace, and returning what it printed. This is // how an agent following a skill's instructions ("run scripts/gitleaks.go // to scan for secrets") actually executes a .go helper without a Go diff --git a/internal/agentexec/protocol.go b/internal/agentexec/protocol.go index 3c7fe8fc9..f619e74e2 100644 --- a/internal/agentexec/protocol.go +++ b/internal/agentexec/protocol.go @@ -84,9 +84,9 @@ type Request struct { Protection Protection `json:"protection"` Notes string `json:"notes,omitempty"` CaptureTools []CaptureTool `json:"capture_tools,omitempty"` - // Plugins are bundled Yaegi plugins from the skill's plugins/ - // directory. Each entry carries the name and source so the agent - // can register them as tools. PRD section 5 Layer 1. + // Plugins are bundled Yaegi plugins from the skill's plugins/ directory. + // Each entry carries the name and source so the agent can register them as + // tools. Plugins []PluginSpec `json:"plugins,omitempty"` // Harness, when set, runs the stage on an external coding-agent CLI // instead of the built-in loop. The worker in a Kit container is the diff --git a/internal/agentexec/subjects.go b/internal/agentexec/subjects.go index 7fecbd3df..3e17b62b4 100644 --- a/internal/agentexec/subjects.go +++ b/internal/agentexec/subjects.go @@ -9,9 +9,7 @@ import ( // // These belong to this package because it defines what an agent request and // response mean. They previously sat in the NATS package, which made the -// transport the owner of Archie's agent protocol; see -// docs/architecture/dependencies-and-contracts.md -- message schemas and the -// subjects addressing them stay with the domain that defines them. +// transport the owner of Archie's agent protocol. const ( // SubjectSystemWildcard matches every task's system subject, for a // daemon subscribing to all of them at once with a single core NATS diff --git a/internal/agentexec/systemlog.go b/internal/agentexec/systemlog.go index 6558eadc8..818bc0ed1 100644 --- a/internal/agentexec/systemlog.go +++ b/internal/agentexec/systemlog.go @@ -33,7 +33,7 @@ type LogPublisher interface { // decode() moves it into Fields itself. Handing decode() this payload // instead of json.Unmarshal would nest everything one level too deep, under // a literal "fields" key, and silently lose every real field name. A future -// consumer of this subject (see GitHub issue #454) must unmarshal directly +// consumer of this subject must unmarshal directly // into logging.Entry, not call decode() on these bytes. // // Publishing is fire-and-forget. A core NATS Publish call is already diff --git a/internal/agentexec/toolset.go b/internal/agentexec/toolset.go index 1f0ebe8e2..f4bee842e 100644 --- a/internal/agentexec/toolset.go +++ b/internal/agentexec/toolset.go @@ -78,9 +78,8 @@ type ToolSetOptions struct { Approval tools.ApprovalRequester // OnToolCall, when non-nil, is notified once per completed tool call. - // LoopRunner populates it so a workflow stage can surface tool - // activity on the task timeline (archie-core-467's task-transcript - // counterpart). Nil means no one is listening. + // LoopRunner populates it so a workflow stage can surface tool activity on + // the task timeline. Nil means no one is listening. OnToolCall ToolCallReporter } diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index 3e7ca4593..b1becc0a3 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -42,12 +42,12 @@ type hybridTrees struct { localDir string branch string // worktreeUID and worktreeGID are the daemon's own host UID/GID - // (WORKTREE_UID/WORKTREE_GID, set by containerEnv), or -1 when unset. - // The agent runs as root inside the container, so a commit it writes - // to the bind-mounted worktree lands owned by UID 0 on the host; Push - // reconciles ownership back to the daemon's UID before handing off, - // since the daemon -- running as its own non-root host user -- is the - // one that reads those objects to actually push (archie-core#520). + // (WORKTREE_UID/WORKTREE_GID, set by containerEnv), or -1 when unset. The + // agent runs as root inside the container, so a commit it writes to the + // bind-mounted worktree lands owned by UID 0 on the host; Push reconciles + // ownership back to the daemon's UID before handing off, since the daemon + // -- running as its own non-root host user -- is the one that reads those + // objects to actually push. worktreeUID, worktreeGID int } @@ -185,7 +185,7 @@ type taskDependencies struct { // steps is the workflow step vocabulary pinned definitions are compiled // against, registered at the composition root and injected: this is the // executing half of the contract whose validating half is the control - // plane's (archie-core-fwmp). + // plane's. steps *workflow.Manager // guardrails is the guardrail engine agent stages record tool outcomes // against. It is built by this process's composition root (the workflow @@ -270,13 +270,12 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen } // The agent process runs as root inside the container, so everything this // run writes into the bind-mounted worktree is owned by UID 0 on the host; - // CommitAll and Push hand it back on the success path (archie-core#520). - // Doing the same here covers every OTHER way a run can end -- a gate - // failure that parks the task, a stage error, an early return -- because - // the daemon is the one that later cleans and resets this directory, as its - // own non-root host user, and it cannot even unlink a root-owned directory. - // Without this, a parked attempt left a worktree the next attempt could not - // start from. + // CommitAll and Push hand it back on the success path. Doing the same here + // covers every OTHER way a run can end -- a gate failure that parks the + // task, a stage error, an early return -- because the daemon is the one + // that later cleans and resets this directory, as its own non-root host + // user, and it cannot even unlink a root-owned directory. Without this, a + // parked attempt left a worktree the next attempt could not start from. defer restoreWorktreeOwnership(trees, workDir, log)() // The MCP providers a task hosts share the same model runtime its agent @@ -305,7 +304,7 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen // processes connected only by NATS. Without this bridge, tc.Emit is a // silent no-op for every stage/outcome/park event this run produces, // which is why the dashboard timeline showed nothing for any task - // executed through the container/NATS path (archie-core-518). Nil + // executed through the container/NATS path. Nil // dependencies.events (a caller with no NATS connection, e.g. tests // that construct taskDependencies directly) leaves bus nil, and // TaskContext.Emit is already nil-safe. @@ -335,7 +334,6 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen // prefetchPRReview, writing under workDir/.archie-pr-review -- the same // host directory Docker bind-mounts at storage.WorktreeMountDir) -- never // over the network, and never with a forge credential in this process. - // See docs/development/agent.md, "Giving the agent something new". if req.Task.Workflow == "pr-review" { tc.PRSource = prsource.NewFromMount(filepath.Join(workDir, prsource.PrefetchDirName)) } @@ -362,9 +360,7 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen // CompilePinnedWorkflow resolves and compiles the immutable definition the task // request carries, against this process's step vocabulary. Production execution -// and the workflow step-vocabulary contract test -// (internal/app/controlplane/step_vocabulary_agreement_test.go) both enter -// through it. +// and the workflow step-vocabulary contract test both enter through it. // // A request that carries no definition is routed and pinned from the shipped // definitions, which writes the resolved workflow name, YAML, and digest back diff --git a/internal/app/agentworker/worker.go b/internal/app/agentworker/worker.go index 097e106cb..313cf0355 100644 --- a/internal/app/agentworker/worker.go +++ b/internal/app/agentworker/worker.go @@ -36,11 +36,9 @@ type Settings struct { NATSToken string WorkDir string - // StateStoreTarget and StateStoreToken are the daemon-injected State - // Store gRPC endpoint and bearer token (docs/prds/state-store-contract.md - // §6: STATE_STORE_URL/STATE_STORE_TOKEN, mirroring the NATS_URL/NATS_TOKEN - // handoff). StateStoreTarget is required: the legacy NATS storerpc path - // is deleted (docs/prds/state-store-contract.md §12 step 4). + // StateStoreTarget and StateStoreToken are the daemon-injected State Store + // gRPC endpoint and bearer token. StateStoreTarget is required: the legacy + // NATS storerpc path is deleted. StateStoreTarget string StateStoreToken string } @@ -72,12 +70,7 @@ type workerDependencies struct { guardrails *tools.GuardrailEngine } -// productionWorkerDependencies builds the worker's process dependencies. The -// workflow step vocabulary is registered here, at the executing side's -// composition root, before the first task is served: -// internal/app/agentworker's step_vocabulary_test.go calls this function and -// fails if it stops using the shared provider set -// (internal/infrastructure/workflowsteps). +// productionWorkerDependencies builds the worker's process dependencies. func productionWorkerDependencies() (workerDependencies, error) { steps, err := workflowsteps.NewManager() if err != nil { diff --git a/internal/app/archied/access_reset.go b/internal/app/archied/access_reset.go index c6fa14475..6c92aca2b 100644 --- a/internal/app/archied/access_reset.go +++ b/internal/app/archied/access_reset.go @@ -1,6 +1,5 @@ // The `archied access reset` command: the locked-out-org and broken-instance -// recovery surface (docs/prds/orgs-and-access.md, "Recovering from a -// locked-out org"). It restores the shipped role policies for one org and +// recovery surface. It restores the shipped role policies for one org and // removes its other org-level policies, or removes the stored instance // policies; the cross-org forbid is engine-enforced and survives any reset. // diff --git a/internal/app/archied/binding_cipher.go b/internal/app/archied/binding_cipher.go index 968cfc2fa..34d3cf293 100644 --- a/internal/app/archied/binding_cipher.go +++ b/internal/app/archied/binding_cipher.go @@ -10,9 +10,9 @@ import ( ) // bindingCipherFromConfig resolves the binding at-rest encryption key from -// config through the secret registry and returns the EDA store's cipher. An unset -// encryption_key returns a nil cipher, keeping the legacy plaintext path (the -// store's default). See docs/prds/binding-secret-encryption.md. +// config through the secret registry and returns the EDA store's cipher. An +// unset encryption_key returns a nil cipher, keeping the legacy plaintext path +// (the store's default). func bindingCipherFromConfig(cfg config.Config, secrets *secret.Registry) (bindingcipher.BindingCipher, error) { if cfg.Bindings.EncryptionKey == (secret.SecretRef{}) { return nil, nil diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index be3fcf1bd..aac3f8b88 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -124,11 +124,10 @@ type boot struct { // stateStore is the State Store contract adapter every daemon and gateway // store consumer depends on. It is ALWAYS the remote *staterpc.Client // dialed to the standalone archie-state-store gRPC service at - // [services.state].target (the daemon and gateway no longer own archie.db - // in-process, per docs/prds/state-store-contract.md §12 step 7). It is set - // by openStateStoreAdapter, which requires [services.state].target to be - // set. The b.st field remains solely for the standalone archie-state-store - // binary, which serves the task store from Postgres. + // [services.state].target. It is set by openStateStoreAdapter, which + // requires [services.state].target to be set. The b.st field remains solely + // for the standalone archie-state-store binary, which serves the task store + // from Postgres. stateStore storecontract.TaskStore // accessChain is the daemon's policy engine, built once from the stored // policies (openAccessChain); accessProblems is what the readiness @@ -358,7 +357,7 @@ func (b *boot) cleanup() { // loadConfig resolves the file config. A Resolve failure is reported on // stderr because the file log destination is itself configuration that has // not been read yet. -func (b *boot) loadConfig(ctx context.Context, cfgPath, overlayPath string) error { +func (b *boot) loadConfig(_ context.Context, cfgPath, overlayPath string) error { loader := configuration.New(b.log) b.loader = loader doc, err := loader.Resolve(cfgPath, overlayPath) @@ -367,11 +366,9 @@ func (b *boot) loadConfig(ctx context.Context, cfgPath, overlayPath string) erro return err } b.doc = doc - // A stray/misspelled key parses and validates cleanly (unknown TOML - // keys are otherwise silently discarded), so it must be visible - // somewhere rather than just quietly doing nothing -- see - // docs/architecture/configuration.md's startup policy: an invalid - // config is fatal, but a typo like this is not that, only a warning. + // A stray/misspelled key parses and validates cleanly (unknown TOML keys + // are otherwise silently discarded), so it must be visible somewhere rather + // than just quietly doing nothing. if len(doc.UnknownKeys) > 0 { b.log.Warn("config file has unrecognised keys; check for typos", "keys", doc.UnknownKeys) } @@ -381,24 +378,13 @@ func (b *boot) loadConfig(ctx context.Context, cfgPath, overlayPath string) erro return b.setupLogging() } -// setupLogging re-creates the logger now the config is known. Everything -// before this point logs to stderr only, which is unavoidable: the log -// destination is itself configuration. A file that cannot be opened is -// reported and the daemon continues on stderr -- losing the durable copy -// must not take the daemon down with it. func (b *boot) setupLogging() error { cfg := b.cfg if b.stderrLog { - // The stderr logger newBootstrap installed is the whole destination. - // Nothing below this line is set up: the feed, the task-log registry and - // the rotating file all belong to a running daemon. return nil } logFeed := logging.NewFeed(1000) b.logFeed = logFeed - // Task logs live in the state directory rather than under cfg.Log.File's - // directory: cfg.Log.File is optional (file logging can be off), while - // state_dir always resolves. taskLogs := logging.NewTaskRegistry(filepath.Join(cfg.StateDir, "logs", "tasks"), logFeed, logging.TaskSinkOptions{}) b.taskLogs = taskLogs fileLog, logCloser, logErr := logging.New(logging.Options{ @@ -409,8 +395,6 @@ func (b *boot) setupLogging() error { Stderr: !cfg.Log.Quiet, Feed: logFeed, }) - // All daemon diagnostics carry an explicit component so the dashboard's - // component filter does not have to infer ownership from message text. b.log = fileLog.With("component", "daemon") b.addCleanup(func() { _ = logCloser.Close() }) if logErr != nil { @@ -436,25 +420,9 @@ func (b *boot) openStores(ctx context.Context) error { } b.forgeClient, b.token = resolveForge(cfg.Forge, secrets, log) - // The daemon and gateway do not serve the State Store's tables: the - // standalone archie-state-store process does, and both consumers dial its gRPC State Store contract. openStateStoreAdapter - // (called by Run and RunGateway after openStores) resolves b.stateStore as - // the remote *staterpc.Client. There is no local store to open here - // (docs/prds/state-store-contract.md §12 step 7, no dual-store ownership). return b.openChatSessions(ctx) } -// openStateStoreAdapter resolves the State Store contract adapter as the -// remote *staterpc.Client dialed to [services.state].target, so every daemon -// and gateway store consumer uses one endpoint -- the standalone -// archie-state-store service. It requires [services.state].target to be set: -// after .4.6 the daemon and gateway no longer own archie.db in-process, so the -// local default of earlier phases is removed (no dual-store ownership; -// docs/prds/state-store-contract.md §12 step 7). The token the daemon also -// injects into agent containers (STATE_STORE_TOKEN) is the same one this -// client authenticates with, resolved from [services.state].target_token or -// the STATE_STORE_TOKEN secret (§10). It runs after openStores has resolved -// b.secrets, and before setupObservability / buildDaemon wire consumers. func (b *boot) openStateStoreAdapter() error { target := strings.TrimSpace(b.cfg.Services.Get(config.ServiceNameState).Target) if target == "" { @@ -466,13 +434,6 @@ func (b *boot) openStateStoreAdapter() error { return err } b.stateStore = client - // The daemon reads workflow definitions through the workflow-definitions - // client, built by the daemon root (openDaemonWorkflowDefinitions) on this - // process's step vocabulary, so the daemon resolves the same vocabulary the - // State Store server validates against. It is not built here because the - // gateway root shares this adapter and resolves no step type. That agreement - // holds within one build: the State Store is a separate binary, and a skewed - // deploy is only fixed by a matching deploy. b.controlPlaneRPC = client.ControlPlane() b.controlPlane = controlplane.NewRPCClient(b.controlPlaneRPC) b.applyStatus = applystatus.New(b.processName, client, b.log) @@ -482,10 +443,6 @@ func (b *boot) openStateStoreAdapter() error { return nil } -// openStateStage opens the state-store adapter and its daemon-side surfaces -// plus the policy chain, in one step of the composition sequence: the three -// are ordered but not interleaved, and any failure fails the boot -// (openStateStoreAdapter, openDaemonStateSurfaces, openAccessChain). func (b *boot) openStateStage(ctx context.Context) error { if err := b.openStores(ctx); err != nil { return err @@ -496,15 +453,10 @@ func (b *boot) openStateStage(ctx context.Context) error { return b.openAccessChain(ctx) } -// openAccessChain builds the policy chain the daemon dispatches through -// (docs/prds/orgs-and-access.md, "Where it lives"): the stored policies over -// the wire, compiled once at boot. An invalid instance policy fails the boot; -// an invalid org, workspace or object policy is retained as a health problem -// and its level denies everything. func (b *boot) openAccessChain(ctx context.Context) error { source, ok := b.stateStore.(access.PolicySource) if !ok { - return nil // no policy store wired: the chain is not built + return nil } stored, err := source.Policies(ctx) if err != nil { @@ -523,9 +475,6 @@ func (b *boot) openAccessChain(ctx context.Context) error { return nil } -// openChatSessions opens the conversation store on its own pool from -// database_url. The daemon reads it (session curator) and the Gateway serves -// it; only the Gateway claims serve ownership (claimGatewayOwnership). func (b *boot) openChatSessions(ctx context.Context) error { pool, err := openServicePool(ctx, b.cfg.DatabaseURL, "the conversation store") if err != nil { @@ -542,10 +491,6 @@ func (b *boot) openChatSessions(ctx context.Context) error { return nil } -// claimGatewayOwnership holds the Gateway's serve claim for the process's -// life, so a second Gateway (whose turn recovery would fail this one's -// in-flight turns) refuses to start. It runs after openChatSessions, so its -// cleanup releases the claim before the conversation store closes the pool. func (b *boot) claimGatewayOwnership(ctx context.Context) error { ownership, err := postgres.AcquireOwnership(ctx, b.chatPool, postgres.OwnerGateway) if err != nil { @@ -593,11 +538,6 @@ func (b *boot) setCatalogState(snapshot modelcatalog.Snapshot, models []string) b.catalogModels = models } -// loadCatalog reads the model catalog once at boot and merges it into the -// running config. A catalog that cannot be read is not fatal -- the configured -// providers and models keep running, and the refresh loop retries the same -// read -- but a catalog that *is* read must reach the config the process runs -// on, not just the boot struct the chat runtime was built from. func (b *boot) loadCatalog(ctx context.Context, cfgPath string) { b.catalogCachePath = filepath.Join(filepath.Dir(cfgPath), "models.json") catalog, err := modelcatalog.Load(ctx, b.catalogOptions(b.catalogCachePath)) @@ -606,23 +546,11 @@ func (b *boot) loadCatalog(ctx context.Context, cfgPath string) { return } models := applyModelCatalog(&b.cfg, catalog) - // applyModelCatalog writes into the boot struct, while every consumer - // reads config.Holder. Publishing the merged copy here is what puts the - // catalog's model limits and discovered providers into the running config; - // without it the first live update would be the first snapshot to carry - // them. b.cfgHolder.Set(b.cfg.Clone()) b.setCatalogState(catalog, models) b.log.Info("model catalog loaded", "providers", len(catalog.Providers), "models", len(models)) } -// seedSoul writes the starter SOUL beside the config on first run, so the -// identity a user can edit exists before the SOUL loader (#439) reads it. It -// runs on the full process's boot tail rather than in loadConfig: an offline -// command such as `-requeue` reads the config but must not write the operator's -// files. A failure is logged, not fatal -- the loader falls back to the embedded -// default, so a read-only config directory must not stop the process -// (docs/prds/soul.md, "Prompt and failure contract"). func (b *boot) seedSoul(cfgPath string) { result, err := configuration.SeedSoul(cfgPath, agent.ShippedSoul()) if err != nil { @@ -634,14 +562,6 @@ func (b *boot) seedSoul(cfgPath string) { } } -// refreshModelCatalog re-reads the catalog and republishes everything derived -// from it, so a credential that becomes resolvable after boot or a model added -// upstream reaches the running config, the dashboard and the chat runtime -// without a restart. It is the live half of loadCatalog. -// -// A failed read keeps the snapshot already running: the model list must not go -// blank because the catalog service had a bad minute. The caller decides -// whether the failure is fatal to it -- the refresh loop logs and retries. func (b *boot) refreshModelCatalog(ctx context.Context) error { catalog, err := modelcatalog.Load(ctx, b.catalogOptions(b.catalogCachePath)) if err != nil { @@ -653,8 +573,6 @@ func (b *boot) refreshModelCatalog(ctx context.Context) error { if err != nil { return err } - // Committed only once the layered config passed validation, so a refused - // layering leaves the catalog the process is running alone. b.setCatalogState(catalog, models) b.publishConfig(ctx, cfg) b.rebuildChatModelRuntime(cfg) @@ -662,12 +580,6 @@ func (b *boot) refreshModelCatalog(ctx context.Context) error { return nil } -// catalogOptions is the one place the catalog read options are built: boot and -// every live refresh read the same endpoint, the same cache file and the same -// credential lookup. Getenv is the secrets registry, not the raw process -// environment, so a key a secret engine starts resolving after boot is visible -// to the next refresh. A variable exported into the shell after the process -// started is not, and cannot be: the process environment is fixed at exec. func (b *boot) catalogOptions(cachePath string) modelcatalog.Options { opts := modelcatalog.Options{ URL: b.catalogURL, @@ -682,19 +594,8 @@ func (b *boot) catalogOptions(cachePath string) modelcatalog.Options { return opts } -// modelCatalogRefreshInterval is how often the running daemon re-reads the -// model catalog. The document itself changes on the order of weeks, but a -// credential a secret engine starts resolving can appear at any moment, so the -// interval trades one cheap HTTP read against how long an operator waits for a -// newly usable provider to show up. It is deliberately the daemon's own -// cadence and not an operator setting: the catalog is derived state, not a -// stored resource, and a knob with no second consumer would be a setting that -// parses and does nothing. const modelCatalogRefreshInterval = time.Hour -// startModelCatalogRefresh re-reads the catalog on an interval for the life of -// the process. It belongs to the daemon, which owns the published -// configuration; the standalone Gateway reads the catalog once at boot. func (b *boot) startModelCatalogRefresh(ctx context.Context) { every := b.catalogRefreshInterval if every <= 0 { @@ -716,34 +617,18 @@ func (b *boot) startModelCatalogRefresh(ctx context.Context) { }() } -// setupObservability builds the event bus and dashboard server. Every event is persisted (stamped with its row id) and -// then fanned out to live dashboard connections. func (b *boot) setupObservability(ctx context.Context) { cfg, log := b.cfg, b.log bus := events.NewBus() b.bus = bus b.addCleanup(func() { bus.Close() }) - // The watchdog leaves its verdict in a file on this host, so the daemon - // reads it and publishes the outcome as an event; the dashboard renders - // what it receives, wherever it runs (archie-core-8cda.5.4). b.startUpdateRelay(ctx, updateReportPath(cfg.WorkDir, "webui")) sink := bus.Subscribe(256) go persistEvents(ctx, sink, b.stateStore, log) } -// reactionStreamMaxAge bounds how long a reaction survives in the fan-out -// stream before JetStream discards it. Reactions are producer-only wake -// events (docs/prds/event-sources-and-reactions.md): a dropped reaction only -// delays work until the next poll, never loses it, because the authoritative -// state is re-read at pass time. One day therefore tolerates a consumer that -// is down or lagging for a full maintenance window without letting -// acknowledged reactions accumulate without bound. const reactionStreamMaxAge = 24 * time.Hour -// connectNATS opens the NATS client. External mode dials cfg.NATS.URL; -// embedded mode starts an in-process nats-server and dials it, so single- -// process deployments get task distribution and reaction delivery without a -// separate server. Broker deployment never changes the worker executor. func (b *boot) connectNATS(ctx context.Context) error { //nolint:nestif // embedded broker discovery and startup require explicit fallback branches cfg, log := b.cfg, b.log url := cfg.NATS.URL @@ -764,8 +649,6 @@ func (b *boot) connectNATS(ctx context.Context) error { //nolint:nestif // embed url, natsToken = endpoint.URL, endpoint.Token if probe, err := nats.Connect(ctx, nats.Config{URL: url, Token: natsToken, Subjects: []string{workintake.SubjectTaskWildcard}, FilterSubject: workintake.SubjectTaskWildcard}, log); err == nil { probe.Close() - // The endpoint is live; the connection is recreated below with the - // same subject configuration and becomes the daemon's owner. url, natsToken = endpoint.URL, endpoint.Token } else { url, natsToken, err = b.startEmbeddedNATS(ctx) @@ -782,8 +665,6 @@ func (b *boot) connectNATS(ctx context.Context) error { //nolint:nestif // embed } } - // Composition owns the subject list: the bus must not know which - // subjects belong to which domain. natsClient, err := nats.Connect(ctx, nats.Config{ URL: url, Token: natsToken, @@ -795,13 +676,6 @@ func (b *boot) connectNATS(ctx context.Context) error { //nolint:nestif // embed return err } - // Reactions are producer-only fan-out events: every interested consumer - // must see each one, so they get their own stream under LimitsPolicy - // rather than the work-queue policy ARCHIE_TASKS uses (which lets a - // second consumer on an overlapping filter silently receive nothing). - // LimitsPolicy retains every message until a limit is reached, so without - // a finite limit acknowledged reactions would accumulate forever; the - // MaxAge cap bounds that by time. reactionMaxAge := reactionStreamMaxAge reactionClient, err := nats.Connect(ctx, nats.Config{ URL: url, @@ -822,24 +696,14 @@ func (b *boot) connectNATS(ctx context.Context) error { //nolint:nestif // embed b.natsURL = url b.natsToken = natsToken b.addCleanup(func() { natsClient.Close() }) - // The reaction client is kept only so its connection stays open for the - // daemon's lifetime and is closed at shutdown; the stream it provisions - // is the deliverable. A future producer (bead archie-core-8li9.3) will - // need its own publisher surface, wired when that step lands. b.addCleanup(func() { reactionClient.Close() }) b.reactionClient = reactionClient log.Info("nats connected", "url", url, "task_stream", nats.DefaultStreamName, "reaction_stream", nats.DefaultReactionStreamName) return nil } -// startEmbeddedNATS starts the in-process nats-server and returns the client -// URL and token to dial it with. Its shutdown is registered BEFORE the caller -// registers the client close, so the client closes first (cleanups run LIFO). func (b *boot) startEmbeddedNATS(ctx context.Context) (string, string, error) { cfg, log := b.cfg, b.log - // An empty state_dir would put the store and its endpoint file in the - // process's working directory. Defaults always set it, so empty means a - // caller skipped them. if cfg.StateDir == "" { return "", "", errors.New("embedded nats: state_dir is required") } @@ -864,10 +728,6 @@ func (b *boot) startEmbeddedNATS(ctx context.Context) (string, string, error) { return srv.ClientURL(), srv.Token(), nil } -// setupContainers builds the managed autonomous-worker pool. Failure degrades -// rather than aborting because the native interactive agent and dashboard do -// not require Docker; repository tasks park instead of falling back to a host -// model loop. func (b *boot) setupContainers(ctx context.Context) func() { containerPool, storeBackend, closeDocker := startContainers(ctx, b.cfgHolder, b.secrets, b.log) b.containerPool = containerPool @@ -875,14 +735,6 @@ func (b *boot) setupContainers(ctx context.Context) func() { return closeDocker } -// setupEmbeddings builds the optional embedding capability. A client is -// wired only when models["embedding"] names a provider/model and that -// provider's credential resolves -- the same credential-missing-degrades- -// not-fatal rule registerMinimaxTool follows for generate_video. No -// warning when the role was simply never configured; a warning when it was -// configured but couldn't be made to work, so a broken setup doesn't go -// unnoticed the way AGENTS.md already warns an unnoticed optional-provider -// degradation can. func (b *boot) setupEmbeddings(cfg config.Config, log *slog.Logger) { if client, ok := infraembedding.New(cfg, infraembedding.Options{}); ok { b.embeddings = client @@ -892,14 +744,6 @@ func (b *boot) setupEmbeddings(cfg config.Config, log *slog.Logger) { } } -// setupTranscriber builds the optional voice-transcription capability. It is -// the model-owning side of the Messaging Service boundary: the channel -// frontend carries a voice note's audio bytes across the inbound wire but -// holds no provider credential, so this process turns them into text before -// the turn's message is recorded. Like setupEmbeddings, a client is wired only -// when models["transcription"] names a provider/model and that provider's -// credential resolves; a configured-but-unusable role is logged so the -// degradation is visible, while a role never configured is silent. func (b *boot) setupTranscriber(cfg config.Config, log *slog.Logger) { client, ok := transcription.New(cfg.Models, cfg.Providers, transcription.Options{ ResolveSecret: b.secrets.Resolve, @@ -912,14 +756,9 @@ func (b *boot) setupTranscriber(cfg config.Config, log *slog.Logger) { } } -// setupLLMAndChat wires the runtime, tool registry, model management, -// personas and the dashboard's chat service. func (b *boot) setupLLMAndChat(ctx context.Context) error { cfg, log := b.cfg, b.log - // Telegram/email keep their own in-process routers rather than going - // through ChatContract: their streaming responder is a callback, and - // ChatContract's wire-safe interface can't carry one. if err := b.setupChatRuntime(ctx, cfg); err != nil { return err } @@ -930,23 +769,13 @@ func (b *boot) setupLLMAndChat(ctx context.Context) error { return err } b.addCleanup(cleanup) - // Channel routers execute turns locally and need the conversation store's TurnLedger. - // The remote contract serves web chat; it must not replace their store. b.chat = &webui.ChatService{Contract: contract, Updates: b.updateService} b.setupReadinessProbes() return nil } -// rateLimiterEvictInterval is how often an active Limiter sweeps entries -// whose hits have all aged out of the window, per internal/ratelimit's own -// documented ticker contract. const rateLimiterEvictInterval = time.Minute -// startRateLimiter constructs b.rateLimiter from cfg when configured, and -// drives its documented EvictStale ticker for the life of ctx. Leaves -// b.rateLimiter nil (rate limiting off) when cfg is not enabled. Only the -// Gateway process calls it: it owns the sole Router, so it is the one place -// an inbound budget can be applied to every channel's turns. func (b *boot) startRateLimiter(ctx context.Context, cfg config.RateLimitConfig) { if !cfg.Enabled() { return @@ -967,9 +796,7 @@ func (b *boot) startRateLimiter(ctx context.Context, cfg config.RateLimitConfig) }() } -// loadWorkflows loads routing inputs. Executable definitions are supplied by -// the State Store control plane and pinned before each dispatch. -func (b *boot) loadWorkflows(ctx context.Context) error { +func (b *boot) loadWorkflows() error { cfg, log := b.cfg, b.log if err := b.loadWorkflowRouting(cfg, log); err != nil { return err @@ -982,20 +809,9 @@ func (b *boot) loadWorkflows(ctx context.Context) error { } log.Info("workflow step registry built", "shipped_workflows", len(workflow.ShippedDefinitions().Definitions)) - // The dashboard is served by the archie-ui process from the cutover - // change (archie-core-8cda.5.4, PRD gate 7): the daemon runs no webui - // listener, and [web].listen is the archie-ui process's bind address. - // The daemon still renders the configuration snapshot via the - // standalone webui.BuildConfigView, not through a Server. return nil } -// loadWorkflowRouting loads the kind/label -> workflow-name bindings from -// the single-file fields and the playbook directories, merges them, and -// installs the result via workflow.SetKindWorkflows/SetLabelWorkflows. -// Split out of loadWorkflows (t2db.16) to keep the top-level function's -// complexity within the lint gate -- pure extraction, same log messages -// and error-return order as before. func (b *boot) loadWorkflowRouting(cfg config.Config, log *slog.Logger) error { kindWorkflows, err := workflow.LoadKindWorkflowsYAML(cfg.WorkflowRoutingFile) if err != nil { @@ -1014,10 +830,6 @@ func (b *boot) loadWorkflowRouting(cfg config.Config, log *slog.Logger) error { 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) @@ -1036,13 +848,13 @@ func (b *boot) loadWorkflowRouting(cfg config.Config, log *slog.Logger) error { return nil } -// loadModules builds the daemon's Module registry (EDA playbook Module -// position, t2db.13): operator-trusted, in-process, Yaegi-interpreted. A -// broken module is a startup failure -- the daemon does not start with a -// partial module set, matching the routing-file load pattern (not the -// degrade-and-skip plugin pattern). Kinds whose file is not present in the -// directory are simply not loaded. Split out of loadWorkflows (t2db.16); -// pure extraction, same log messages and error-return order as before. +// loadModules builds the daemon's Module registry: operator-trusted, +// in-process, Yaegi-interpreted. A broken module is a startup failure -- the +// daemon does not start with a partial module set, matching the routing-file +// load pattern (not the degrade-and-skip plugin pattern). Kinds whose file is +// not present in the directory are simply not loaded. Split out of +// loadWorkflows; pure extraction, same log messages and error-return order as +// before. func (b *boot) loadModules(cfg config.Config, log *slog.Logger) error { b.modules = module.New() if cfg.ModuleDir == "" { @@ -1066,14 +878,13 @@ func (b *boot) loadModules(cfg config.Config, log *slog.Logger) error { return nil } -// loadEDAPlaybooks loads the EDA playbook documents (t2db.15): trigger + -// workflow-kind actions and module-kind action playbooks with CEL when -// conditions and args values. Loaded at startup with the same reject-at-load -// rule -- any malformed playbook, mixed/unsupported action shape, unknown -// module kind, when compile failure, or args key failure aborts startup, -// matching the routing-file load pattern (not degrade-and-skip). A nonexistent -// dir is an empty store. Action playbooks run through the daemon once -// buildDaemon wires the dispatch ledger (docs/prds/action-playbook-run.md). +// loadEDAPlaybooks loads the EDA playbook documents: trigger + workflow-kind +// actions and module-kind action playbooks with CEL when conditions and args +// values. Loaded at startup with the same reject-at-load rule -- any malformed +// playbook, mixed/unsupported action shape, unknown module kind, when compile +// failure, or args key failure aborts startup, matching the routing-file load +// pattern (not degrade-and-skip). A nonexistent dir is an empty store. Action +// playbooks run through the daemon once buildDaemon wires the dispatch ledger. func (b *boot) loadEDAPlaybooks(cfg config.Config, log *slog.Logger) error { var err error b.playbooks, err = playbook.Load(cfg.EDAPlaybookDir, b.modules) @@ -1115,16 +926,6 @@ func (b *boot) loadPlugins() error { return nil } -// buildWorktreeManager composes the process-wide worktree manager from the -// resolved primary forge credential and the loaded config. Both process roots -// own one: the daemon works tasks in it, and the Gateway used it to -// materialise a pull request head for the now-removed synchronous -// operator-review path (archie-core-afbk.7). It reads only, so it has -// nothing to report. -// -// Identity managers are not built here: buildTreesAndIdentities builds one per -// identity, each in its own WorkDir, because the Gateway must not own daemon -// identity runners. func (b *boot) buildWorktreeManager() { cfg := b.cfg b.trees = &worktree.Manager{ @@ -1136,21 +937,11 @@ func (b *boot) buildWorktreeManager() { } } -// buildTreesAndIdentities composes the worktree manager and the -// multi-identity runners. Each configured identity gets its own forge -// client (its own token, possibly its own forge type/host) and its own -// worktree manager (a distinct WorkDir so concurrent identities never -// collide on the same clone). When cfg.Identities is empty, -// Daemon.Identities stays nil and Run() takes the single-identity path -// unchanged. func (b *boot) buildTreesAndIdentities(ctx context.Context) error { cfg, log := b.cfg, b.log b.buildWorktreeManager() for _, idCfg := range cfg.Identities { - // Same reasoning as the primary forge: one identity whose credential is - // missing must not deny every other identity, and every other - // subsystem, the ability to run. idForge, idToken := resolveForge(idCfg.Forge, b.secrets, log.With("identity", idCfg.Name)) idTrees := &worktree.Manager{ WorkDir: filepath.Join(cfg.WorkDir, "identity-"+idCfg.Name), @@ -1170,9 +961,6 @@ func (b *boot) buildTreesAndIdentities(ctx context.Context) error { return nil } -// registerNATSRPC lets archie-agent containers (which hold no DB -// connection, forge token, or push credential) proxy Store/Forge/ -// worktree operations back to archied over NATS. func (b *boot) registerNATSRPC() error { log := b.log if b.natsClient == nil { @@ -1205,10 +993,6 @@ func (b *boot) registerNATSRPC() error { } b.addCleanup(unsubscribeAgentEvents) - // The standalone Gateway forwards operator task actions to the daemon - // over NATS. The daemon owns execution cancellation, retry policy, - // forge closure and event persistence; the responder applies the same - // taskactions.Service the dashboard uses. unsubscribeTaskActions, err := taskactions.Register(coreConn, b.taskActions(), log) if err != nil { log.Error("gateway task action register failed", "err", err) @@ -1218,18 +1002,8 @@ func (b *boot) registerNATSRPC() error { return nil } -// setupMemoryEngine wires the domain/memory engine family -// (archie-core-1786637499161-356-e424e40d), the only memory engine per -// docs/prds/memory-engine-unification.md. cfg.Memory.Engine is validated at -// config load (configuration.validateMemory) against the same set this -// switch covers, so an unrecognised value cannot reach here -- this only -// guards against the two lists drifting apart. -// -// Rooted at workDir/memory-engine. func (b *boot) setupMemoryEngine() error { cfg, log := b.cfg, b.log - // The logger is what carries an engine's scanner warning: warn allows - // the write, so the log line is the whole audit trail for it. registry := domainmemory.NewRegistry(domainmemory.Registrar{Log: log}) switch cfg.Memory.Engine { @@ -1242,10 +1016,6 @@ func (b *boot) setupMemoryEngine() error { return fmt.Errorf("memory.engine %q has no registered implementation", cfg.Memory.Engine) } - // Not b's own ctx: matches setupMemory's identical choice just above, - // and Start here is a synchronous startup step, not a subscription - // that needs to live and later be cancelled with the daemon's context - // the way setupCurators' WakeOnPrimaryInput does. if err := registry.Start(context.Background()); err != nil { return fmt.Errorf("start memory engine registry: %w", err) } @@ -1261,10 +1031,6 @@ func (b *boot) setupMemoryEngine() error { return nil } -// activeMemoryEngine resolves the engine setupMemoryEngine registered under -// cfg.Memory.Engine. Both memoryStore and memoryWriter narrow this same -// engine to the read or write surface their caller needs; ok is false when -// the registry was never set up or the configured engine is not registered. func (b *boot) activeMemoryEngine() (domainmemory.MemoryEngine, bool) { if b.memEngines == nil { return nil, false @@ -1276,10 +1042,6 @@ func (b *boot) activeMemoryEngine() (domainmemory.MemoryEngine, bool) { return b.memEngines.Get(name) } -// memoryStore resolves the active memory engine as the narrow read surface -// a chat turn runner needs. Nil when activeMemoryEngine has none -- the -// turn runner already treats that as "no memory block" -// (gateway.renderMemory), so a chat turn degrades instead of failing. func (b *boot) memoryStore() gateway.MemoryStore { engine, ok := b.activeMemoryEngine() if !ok { @@ -1288,11 +1050,6 @@ func (b *boot) memoryStore() gateway.MemoryStore { return engine } -// memoryWriter resolves the active memory engine as the narrow write -// surface the per-turn memory tool needs (docs/prds/ -// memory-engine-unification.md §5). Nil when activeMemoryEngine has none -- -// MemoryTools already treats that as "no memory tools", so a chat turn -// simply has no memory_create/update/delete/list tools rather than failing. func (b *boot) memoryWriter() gateway.MemoryWriteStore { engine, ok := b.activeMemoryEngine() if !ok { @@ -1301,63 +1058,31 @@ func (b *boot) memoryWriter() gateway.MemoryWriteStore { return engine } -// setupCurators wires the curator engine family. The registry owns -// curator registration, lifecycle and shutdown ordering. The runtime -// loop (archie-core-89x) and the reference curators (archie-core-i7i, -// gs8) are wired by their issues; until then the registry is empty and -// Stop is a no-op. The event sink rides the in-process bus, whose -// bounded dropping per-subscriber buffers guarantee curator activity can -// never backpressure the daemon or a chat turn. func (b *boot) setupCurators(ctx context.Context) { log := b.log.With("component", "curator") - // Skills root matches loadWorkflows' own resolution of skillsBase -- - // the skill curator maintains the same local skills this daemon - // already treats as authoritative, not the full multi-root catalog a - // chat turn reads. See docs/prds/skill-curator.md. skillsRoot := b.cfg.SkillsDir if skillsRoot == "" { skillsRoot = b.cfg.WorkDir } b.curatorRegistry = curator.NewRegistry(curator.Registrar{ - Log: log.With("component", "curator"), - Events: curatorEventSink{b.bus}, - // Tools resolves declared curator tool names from the same - // process-wide registry a chat turn is given (b.toolReg): one - // catalogue, resolved down to the declared set by the builder. - Tools: toolbuilder.New(b.toolReg), - // b.memEngines (*domainmemory.Registry) satisfies - // curator.MemoryEngineSource's Get(name) signature directly, no - // adapter needed. Set by setupMemoryEngine, which Run() calls before - // setupCurators. + Log: log.With("component", "curator"), + Events: curatorEventSink{b.bus}, + Tools: toolbuilder.New(b.toolReg), MemoryEngines: b.memEngines, - // Skills is a shared host service like Events/MemoryEngines -- - // registry.filter narrows it out of the view for any curator that - // doesn't declare Manifest.Skills, per curator not per instance. - Skills: skillcurator.NewStore(skillsRoot), - // Conversations backs the session-memory curator; b.chatSessionStore - // is opened by openChatSessions before setupCurators. The agent every - // curator write is addressed to is the deployment's bot user: the same - // value the turn runner reads agent-scope memory with - // (TurnRunnerConfig.BotUser), so a fact written here is a fact a later - // turn reaches. + Skills: skillcurator.NewStore(skillsRoot), Conversations: sessioncurator.NewAdapter(b.chatSessionStore, b.cfg.BotUser), LLM: curatorLLMRunner{llm: b.chatLLM, outcomes: b.providerOutcomes}, - // b.chatModels.ActiveModel() is the same source sendChatTurn uses - // for a real chat turn (telegram_setup.go) -- not - // b.defaultChatIdentity, which names a task-routing identity, not - // a model reference. - Model: b.chatModels.ActiveModel(), + Model: b.chatModels.ActiveModel(), }) + if err := b.curatorRegistry.Register(skillcurator.New(skillcurator.DefaultInterval)); err != nil { log.Error("skill curator registration failed", "err", err) } + if err := b.curatorRegistry.Register(sessioncurator.New(sessioncurator.DefaultInterval, infraMemory.EngineName)); err != nil { log.Error("session-memory curator registration failed", "err", err) } - // Config definitions are seed data: each enabled [[curators]] entry is - // registered through the one generic definition-driven engine. Code - // registrations above win for their own name (a duplicate is refused - // and logged, not silently replaced). + for _, def := range b.cfg.Curators { if !def.Enabled { continue @@ -1381,17 +1106,8 @@ func (b *boot) setupCurators(ctx context.Context) { log.Error("config curator registration failed", "curator", def.Name, "err", err) } } - // The runtime owns the per-curator loops (archie-core-89x): one - // goroutine per curator, wake nudges, per-pass budgets, panic - // recovery, bounded shutdown. Stop order at shutdown: runtime first - // (cancels in-flight passes, then stops curator lifecycle), then the - // registry's own Stop below, which is a no-op by then. + b.curatorRuntime = curator.NewRuntime(b.curatorRegistry, curator.RuntimeConfig{}) - // Primary chat turns wake input-driven curators (archie-core-035): - // the forwarder consumes only primary-input kinds, and curator - // output never produces them, so derived work cannot feed its own - // trigger. The subscriber buffer is bounded and dropping — a slow - // curator can never backpressure the chat publisher. curator.WakeOnPrimaryInput(ctx, b.bus, b.curatorRuntime, events.KindTurnCompleted) rt := b.curatorRuntime b.addCleanup(shutdownCuratorRuntime(rt, log)) @@ -1399,32 +1115,19 @@ func (b *boot) setupCurators(ctx context.Context) { b.addCleanup(shutdownCuratorRegistry(reg, log)) } -// registerTools registers the tool providers with a lifecycle: workspace -// file/shell tools and optional MCP servers. Memory tools -// (memory_create/update/delete/list) are not registered here -- they are -// built per turn onto the resolved Subject's scopes -// (internal/gateway/turn_memory_tool.go), not once at boot. -func (b *boot) registerTools(ctx context.Context) error { - // The running config, not b.cfg: boot is where the first stored version of - // every kind was already layered in, and a watch that applied a later one - // before this point published through the holder. +func (b *boot) registerTools() error { cfg, log := b.cfgHolder.Get(), b.log b.providerRegistry = toolprovider.NewRegistry(b.toolReg) b.mcpMu.Lock() b.mcpApplied = make(map[string]appliedMCPServer, len(cfg.Tools.MCPServers)) b.mcpMu.Unlock() - // Workspace file and shell tools. Registered only when a workspace is - // configured: these read, write and execute, so the directory is a - // deliberate choice rather than a default. if workspace := cfg.Chat.Workspace; workspace != "" { unrestricted := cfg.Chat.UnrestrictedFilesystem if err := b.providerRegistry.Register(builtintoolprovider.New(workspace, unrestricted)); err != nil { log.Error("workspace tool provider registration failed", "err", err) return err } - // Logged at the same level either way: which of the two postures is - // running is the first thing worth knowing when a file tool refuses a - // path, or reaches one it should not have. + log.Info("workspace tools enabled", "workspace", workspace, "unrestricted_filesystem", unrestricted) } else { @@ -1436,12 +1139,7 @@ func (b *boot) registerTools(ctx context.Context) error { log.Warn("mcp tool provider skipped", "name", srv.Name, "err", err) continue } - // Optional: an MCP server is a third-party process pulled in at - // runtime, and it is exactly the category that is allowed to be - // absent. Registering it as required meant one failing npm package - // unregistered every builtin tool and exited the daemon, which under - // Restart=on-failure is a crash loop that takes chat and the gateway - // with it. + if err := b.providerRegistry.RegisterOptional(provider); err != nil { log.Warn("mcp tool provider skipped", "name", srv.Name, "err", err) continue @@ -1457,14 +1155,9 @@ func (b *boot) registerTools(ctx context.Context) error { return nil } -// registerStandaloneTools registers the tools with no provider -// lifecycle: the skill catalog activator, the spill directory check and -// web_fetch. func (b *boot) registerStandaloneTools() { cfg, log := b.cfg, b.log - // Skill catalog → skill_activate tool (progressive disclosure: the - // catalog's name+description is always in the tool schema; the full - // SKILL.md body loads only when the model activates one). + if catalog, err := skill.CatalogRoots(skill.DefaultRoots(cfg.WorkDir, cfg.SkillsDir)...); err != nil { log.Warn("skill catalog load failed", "err", err) } else if entry := skill.ActivateTool(cfg.WorkDir, catalog); entry != nil { @@ -1475,35 +1168,17 @@ func (b *boot) registerStandaloneTools() { } } - // Tool results too large to inline are written here. Created once, at - // startup: the write failure inside a turn is silent, so without this - // every oversized result would quietly fall back to truncation and - // spilling would look configured while doing nothing. if spillDir := cfg.Tools.Policy.SpillDir; spillDir != "" { if err := toolLimits(cfg).EnsureSpillDir(); err != nil { log.Warn("tool spill directory unavailable; large results will be truncated instead", "err", err) } else if ws := cfg.Chat.Workspace; ws != "" && !cfg.Chat.UnrestrictedFilesystem && !isWithin(ws, spillDir) { - // A spill hands the model a path to read back, and a confined read - // tool refuses anything outside the workspace. Outside it, the - // spill reference is a dead end and the result is lost rather than - // displaced -- worse than truncating in the first place. - // - // Not a concern when the filesystem is unrestricted: the read tool - // can reach the spill wherever it lives. log.Warn("tool spill directory is outside chat.workspace; the model cannot read back what is spilled there", "spill_dir", spillDir, "workspace", ws) } } - // web_fetch. Registered directly rather than as a tool provider: it has - // no process to start or stop, so the provider lifecycle would buy - // nothing. Disabled by configuration returns nil and advertises nothing. b.registerWebFetchTool(cfg) - // send_file. Rooted at the same workspace as the file tools and gated - // by the same confinement, because it hands a host file to an outbound - // message: a send that could reach paths the read tool refuses would - // be a way around whatever confinement is configured. if entry := sendfile.Tool(cfg.Chat.Workspace); entry != nil { if err := b.toolReg.Register(*entry); err != nil { log.Warn("send_file registration failed", "err", err) @@ -1517,10 +1192,6 @@ func (b *boot) registerStandaloneTools() { b.registerMinimaxTool(cfg, log) } -// registerWebFetchTool registers web_fetch from cfg. Split out of -// registerStandaloneTools because a live tool-settings change rebuilds the -// entry: the one a boot built captured its config at construction, so it -// cannot read a changed value per call. func (b *boot) registerWebFetchTool(cfg config.Config) { log := b.log entry := webfetch.Tool(webfetch.Config{ @@ -1541,14 +1212,6 @@ func (b *boot) registerWebFetchTool(cfg config.Config) { "allow_private_networks", cfg.Tools.WebFetch.AllowPrivateNetworks) } -// registerMinimaxTool registers generate_video. Off by default -- see -// MinimaxConfig's doc comment, it spends real API credits per call -- and, -// unlike web_fetch, needs a resolved credential before it can be -// registered at all: a tool advertised with no working key would fail -// every call, the same "don't advertise a broken capability" reasoning as -// disabled-by-config. Split out of registerStandaloneTools to keep that -// function's branching flat rather than nesting this tool's three failure -// modes (resolve error, empty key, registration error) inside it. func (b *boot) registerMinimaxTool(cfg config.Config, log *slog.Logger) { if !cfg.Tools.Minimax.IsEnabled() { log.Info("minimax video generation disabled") @@ -1576,8 +1239,6 @@ func (b *boot) registerMinimaxTool(cfg config.Config, log *slog.Logger) { log.Info("minimax video generation enabled") } -// buildDaemon constructs the daemon and hands the dashboard the handles -// it shares with it. func (b *boot) buildDaemon() { log := b.log b.d = &daemon.Daemon{ @@ -1606,30 +1267,31 @@ func (b *boot) buildDaemon() { WorkflowEnablement: b.controlPlane, Playbooks: b.playbooks, } + if identities, ok := b.stateStore.(identity.Repository); ok { b.d.IdentityRepository = identities } - // Consumer mapping/binding surfaces resolve from b.stateStore (the State - // Store contract adapter): local by default, remote *staterpc.Client when - // [services.state].target is set. See docs/prds/state-store-contract.md §10. + if ms, ok := b.stateStore.(storecontract.MappingStore); ok { b.d.Mappings = ms } + if bs, ok := b.stateStore.(storecontract.BindingStore); ok { b.d.Bindings = bs } + if bd, ok := b.stateStore.(storecontract.BindingDispatcher); ok { b.d.BindingDispatcher = bd } + if mm, ok := b.stateStore.(storecontract.MappingMatchRecorder); ok { b.d.MappingMatches = mm } + if btc, ok := b.stateStore.(storecontract.BindingTaskCreator); ok { b.d.BindingTaskCreator = btc } - // Dispatch is the second Authorizer call site: the chain built by - // openAccessChain, the principal assembly over the wire, and the denial - // record -- wired together or not at all (docs/prds/orgs-and-access.md). + b.d.Access = b.accessChain if b.accessChain != nil { if principals, ok := b.stateStore.(access.PrincipalSource); ok { @@ -1643,9 +1305,6 @@ func (b *boot) buildDaemon() { b.setupForgeWebhook() } -// playbookLedger returns source's dispatch ledger, or nil with a warning -// naming each action playbook that therefore will not run: an action playbook -// never fires without its at-most-once gate. func playbookLedger(source any, playbooks *playbook.Store, log *slog.Logger) storecontract.PlaybookDispatcher { if pd, ok := source.(storecontract.PlaybookDispatcher); ok { return pd @@ -1658,29 +1317,6 @@ func playbookLedger(source any, playbooks *playbook.Store, log *slog.Logger) sto return nil } -// setupForgeWebhook starts the forge webhook receiver when intake is "webhook" -// or "both". It decodes GitHub issue events into task envelopes and publishes -// them through the same path the poller uses, so a labelled or assigned issue -// becomes work immediately instead of on the next poll. Called from -// buildDaemon, since it needs the freshly built (*daemon.Daemon).PublishTask. -// -// A secret that fails to resolve degrades rather than aborts boot, same -// reasoning as resolveForge: under intake="both" the poll is the deployment's -// explicit backstop for exactly this kind of misconfiguration (CLAUDE.md's -// "polling has to remain a first-class option, not a legacy fallback"), so a -// typo'd env var name must not take the whole daemon down and silently stop -// polling too. Config validation already requires webhook_secret to be a -// configured reference before intake="webhook"/"both" is accepted; this -// handles the reference resolving to nothing at runtime. -// -// Single-identity only: the receiver has one dispatch config (root -// Dispatch.Trigger/Label/BotUser), so a multi-identity deployment's -// per-identity trigger/label/bot user cannot be matched correctly. Rather -// than run with the wrong identity's rules and silently misclassify or drop -// events for identity-scoped repos, webhook intake refuses to start when -// [[identities]] is configured; those repos keep working via their own -// per-identity poll loop, unaffected. Extending this to multi-identity is a -// separate feature, not a bug in this one. func (b *boot) setupForgeWebhook() { cfg, log := b.cfg, b.log if cfg.Forge.Intake != config.ForgeIntakeWebhook && cfg.Forge.Intake != config.ForgeIntakeBoth { @@ -1696,11 +1332,7 @@ func (b *boot) setupForgeWebhook() { "engine", cfg.Forge.WebhookSecret.Engine, "key", cfg.Forge.WebhookSecret.Key, "err", err) return } - // The reaction publisher is the consumer's supply side: the same typed - // reaction the poll produces, keyed source-independently, so webhook and - // poll deliveries of one review dedup (pr-review-remediation.md - // decision 2). The daemon's PublishReaction is the single reaction write - // path: it stamps the root org a webhook delivery would otherwise lack. + receiver := forgewebhook.New(secretValue, cfg.Dispatch.Trigger, cfg.Label, cfg.BotUser, b.d.PublishTask, b.d.PublishReaction, log) host, port := parseListenAddr(cfg.Forge.WebhookAddr, "0.0.0.0", 8645) addr := fmt.Sprintf("%s:%d", host, port) @@ -1721,18 +1353,11 @@ func (b *boot) setupForgeWebhook() { }) } -// publishConfig makes a new configuration the running one and republishes -// the dashboard's projection from it. Every path that changes configuration -// goes through here, so the running config and the published page can never -// diverge. The provenance chain it renders is b.currentProvenance, which the -// caller stores before publishing. func (b *boot) publishConfig(ctx context.Context, cfg config.Config) { b.cfgHolder.Set(cfg) b.publishConfigSnapshot(ctx) } -// configOrigins projects the current provenance chain into the dashboard's -// view type. func (b *boot) configOrigins() []webui.ConfigOrigin { provenance := b.currentProvenance.Load() if provenance == nil { @@ -1747,10 +1372,7 @@ func (b *boot) configOrigins() []webui.ConfigOrigin { return origins } -// configViewInput assembles the dashboard's configuration projection from -// the daemon's own configuration state. The daemon is the configuration -// owner, so it is the process that renders this view (archie-core-ml30). -func (b *boot) configViewInput(ctx context.Context) webui.ConfigViewInput { +func (b *boot) configViewInput() webui.ConfigViewInput { catalog, _ := b.catalogState() in := webui.ConfigViewInput{ Config: b.cfgHolder.Get(), @@ -1764,26 +1386,16 @@ func (b *boot) configViewInput(ctx context.Context) webui.ConfigViewInput { return in } -// publishConfigSnapshot sends the dashboard's projection to the State Store, -// where a UI process reads it. This is the only crossing: the configuration -// owner publishes what it already renders, and no other process holds the -// daemon's config.Holder (archie-core-ymut). -// -// A failed publish degrades to a stale configuration page and is logged, not -// propagated: it must never fail the reload or dashboard write that produced -// the new configuration, both of which have already taken effect. func (b *boot) publishConfigSnapshot(ctx context.Context) { snapshots, ok := b.stateStore.(storecontract.ConfigSnapshotStore) if !ok || b.cfgHolder == nil { return } - // Detached from the caller: a dashboard edit's request context is - // cancelled the moment the browser has its answer, and the write it - // describes has already taken effect either way. + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer cancel() - document, err := json.Marshal(webui.BuildConfigView(b.configViewInput(ctx))) + document, err := json.Marshal(webui.BuildConfigView(b.configViewInput())) if err != nil { b.log.Warn("config snapshot not published", "err", err) return @@ -1798,11 +1410,6 @@ func (b *boot) publishConfigSnapshot(ctx context.Context) { } } -// wireConfigPublishing installs SIGHUP reload and the reload status -// surface. The reload log warns about changed fields that require a -// restart, so an operator never has to read the source to find out -// whether their edit took effect. web.LastReload exposes the outcome to -// /api/config. func (b *boot) wireConfigPublishing(ctx context.Context, cfgPath, overlayPath string) { log := b.log reloadController := newReloadController(b.loader, cfgPath, overlayPath, b.reloadConfig) @@ -1816,19 +1423,9 @@ func (b *boot) wireConfigPublishing(ctx context.Context, cfgPath, overlayPath st b.addCleanup(func() { signal.Stop(reloadCh) }) go reloadLoop(ctx, reloadCh, reloadController, log) - // Give /cancel and /stop a handle on work already in flight. The - // controller is built before the daemon exists, so the runtime is - // attached here; gateways start further down, after d.Startup, so no - // command can arrive before this is wired. b.chatController.WithRuntime(b.d) } -// shutdownCapabilityHost returns a cleanup that stops the capability -// host; same Background reasoning as shutdownCuratorRuntime. Defined -// before startServices so the Stop-before-Start ordering stays visible -// in the source layout the contract test reads. -// -//nolint:contextcheck func shutdownCapabilityHost(capabilityHost *plugin.Host, log *slog.Logger) func() { return func() { stopCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) @@ -1839,10 +1436,6 @@ func shutdownCapabilityHost(capabilityHost *plugin.Host, log *slog.Logger) func( } } -// startServices starts the capability host, daemon and curator runtime, -// then launches the gateways. Optional providers that could not start -// are excluded rather than fatal, so the only way an operator learns -// about one is this loop's log line. func (b *boot) startServices(ctx context.Context) error { log := b.log capabilityHost := b.capabilityHost @@ -1874,28 +1467,17 @@ func (b *boot) startServices(ctx context.Context) error { return nil } -// setupBackends wires the autonomous-workflow backends. Container setup may -// degrade, but NATS startup must succeed because there is no other task handoff. func (b *boot) setupBackends(ctx context.Context) error { closeContainers := b.setupContainers(ctx) err := b.connectNATS(ctx) if err == nil { b.setupKitLauncher(ctx) } - // Container discovery must precede embedded NATS so it can bind the - // worker bridge gateway, but cleanup registration comes afterwards. - // cleanups run LIFO: workers stop first, then the daemon client closes, - // then the embedded server shuts down. + b.addCleanup(closeContainers) return err } -// shutdownCuratorRuntime returns a cleanup that stops the curator -// runtime. The stop path derives its own timeout budget from Background -// rather than the boot context, which is already cancelled by the time -// shutdown runs. -// -//nolint:contextcheck func shutdownCuratorRuntime(rt *curator.Runtime, log *slog.Logger) func() { return func() { stopCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) @@ -1906,10 +1488,6 @@ func shutdownCuratorRuntime(rt *curator.Runtime, log *slog.Logger) func() { } } -// shutdownCuratorRegistry returns a cleanup that stops the curator -// registry; same Background reasoning as shutdownCuratorRuntime. -// -//nolint:contextcheck func shutdownCuratorRegistry(reg *curator.Registry, log *slog.Logger) func() { return func() { stopCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) @@ -1920,7 +1498,6 @@ func shutdownCuratorRegistry(reg *curator.Registry, log *slog.Logger) func() { } } -// exitCode maps a bootstrap error to the process exit code. func exitCode(err error) int { if err != nil { return 1 @@ -1929,27 +1506,14 @@ func exitCode(err error) int { } func (b *boot) runLoop(ctx context.Context, once bool) error { - // Boot is done: the liveness surface stops answering 503, which is what - // the update watchdog is waiting to see after a restart. b.health.markServing() - // systemd's READY=1 asserts the same fact this line has just recorded, so - // it is sent here rather than from a second notion of "started". Not - // earlier: the stores, NATS, gateways and tool providers are all up by now. - // Not later, after the first pass: a pass polls every repo and drains the - // queue, and a unit whose TimeoutStartSec expires mid-pass would be - // restarted while the daemon was working. b.announceReady() if once { b.d.Cycle(ctx) return nil } b.log.Info("archied running", "repos", len(b.cfg.Repos), "poll", b.cfg.PollInterval.Std().String(), "label", b.cfg.Label) - // Drain monitoring only matters while the daemon stays up to be drained; - // a --once cycle exits immediately, so a drain that arrives mid-cycle is - // out of scope and the monitor is not started. b.startDrainMonitor(ctx) - // Armed here, not at boot: the loop it reports on starts on the next line, - // and a --once invocation has no loop to watchdog. b.startWatchdog(ctx) if err := b.d.Run(ctx); err != nil && ctx.Err() == nil { b.log.Error("daemon exited", "err", err) diff --git a/internal/app/archied/chat_identity.go b/internal/app/archied/chat_identity.go index ae58682dc..96489b8df 100644 --- a/internal/app/archied/chat_identity.go +++ b/internal/app/archied/chat_identity.go @@ -5,10 +5,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/messaging" ) -// carriesPersonIdentity reports whether a platform's SenderID names a person, -// per docs/prds/memory-engine-unification.md §3: resolution is supplied per -// channel by the composition, never inferred by the engine or guessed from a -// channel-neutral "channel:SenderID" concatenation. +// carriesPersonIdentity reports whether a platform's SenderID names a person. // // Telegram and email carry a native per-person sender id (a Telegram numeric // user id, an SMTP from address). The dashboard ("web") has one bearer token, @@ -37,7 +34,7 @@ func carriesPersonIdentity(platform string) bool { // It was closed over a single channel name, and one Gateway Router serves every // channel, so that name was "web" even for a Telegram turn: the allowlist above // was real code no production call site reached with a real channel name, and -// Subject.UserID was always empty (archie-core-c1qx). Reading the platform off +// Subject.UserID was always empty. Reading the platform off // the inbound is what makes the policy reachable. func userIdentityResolver() func(messaging.Inbound) (memory.IdentityID, bool) { return func(in messaging.Inbound) (memory.IdentityID, bool) { diff --git a/internal/app/archied/chat_setup.go b/internal/app/archied/chat_setup.go index 6036246fd..4b0009364 100644 --- a/internal/app/archied/chat_setup.go +++ b/internal/app/archied/chat_setup.go @@ -48,7 +48,7 @@ type chatSetup struct { ChatTaskLogs gateway.ChatTaskLogReader ChatTaskActor gateway.ChatTaskActor DefaultChatIdentity string - // Bus carries primary-input events (archie-core-035): a completed + // Bus carries primary-input events: a completed // chat turn is published here so input-driven curators can wake. Nil // disables turn events (tests, minimal setups). Bus *events.Bus @@ -61,9 +61,8 @@ type chatSetup struct { // engine, resolved by cfg.Memory.Engine). Nil disables the chat // block for every turn runner built from this setup. MemoryEngine gateway.MemoryStore - // MemoryWriter is the same active engine's write surface, used to build - // the per-turn memory_create/update/delete/list tools (docs/prds/ - // memory-engine-unification.md §5). Nil omits those tools. + // MemoryWriter is the same active engine's write surface, used to build the + // per-turn memory_create/update/delete/list tools. Nil omits those tools. MemoryWriter gateway.MemoryWriteStore // ProviderOutcomes records the outcome of every chat-model call this // process makes, which the /status health source reads back. Nil disables diff --git a/internal/app/archied/control_plane.go b/internal/app/archied/control_plane.go index f55a2e02a..4804c4734 100644 --- a/internal/app/archied/control_plane.go +++ b/internal/app/archied/control_plane.go @@ -18,7 +18,7 @@ import ( // validates the result. Boot and the SIGHUP reload both go through it: the // reload re-resolves the file document alone, so republishing that document // as it stands reverts each of these layers to its file value until the -// process restarts (archie-core-ju85). +// process restarts. func (b *boot) runtimeConfig(ctx context.Context, base config.Config) (config.Config, map[string]int64, error) { cfg, versions, err := b.controlPlane.RuntimeConfig(ctx, base) if err != nil { @@ -178,9 +178,7 @@ type executionSettingsCandidate struct { // be published as and runs this process's own runnability check on it -- the // same configuration.Validate that runtimeConfig applies before publishing a // layered config, and that the readiness probe applies to the published one. A -// snapshot this process cannot run is refused before it becomes the live one -// (docs/prds/runtime-control-plane.md, "API": Archie starts and checks the new -// one before switching). +// snapshot this process cannot run is refused before it becomes the live one. // // The kind's schema is deliberately not re-checked here. The store validates // every document before it is written (Definition.Decode) and @@ -332,7 +330,6 @@ func (b *boot) startRuntimeResourceWatches(ctx context.Context, versions map[str // reported through apply status, which keeps the version still live on the // record. A refused update therefore reaches the settings page the way a // refused workflow-execution-settings update does -// (docs/prds/control-plane-apply-status.md). func (b *boot) applyRuntimeResourceUpdate(ctx context.Context, kind string, update controlplane.AppliedResource) { if update.Err != nil { // A stream failure carries no version at all (versions start at 1, @@ -443,9 +440,7 @@ func (b *boot) reconcileRuntimePlugins(ctx context.Context) { // refuseSkillsDirChange refuses a stored plugin-settings document whose // skills_dir differs from the value in force. skills_dir is the one directory // with no live consumer, so a change to it stays a restart-scoped edit rather -// than a value the daemon reports as applied. The check reads the running -// config, so it cannot live in validatePluginSettings, which is value-agnostic -// by the archie-core-1143 decision. +// than a value the daemon reports as applied. func (b *boot) refuseSkillsDirChange(ctx context.Context) error { var stored struct { SkillsDir string `json:"skills_dir"` diff --git a/internal/app/archied/control_plane_watch.go b/internal/app/archied/control_plane_watch.go index 46118f1d8..3767c0427 100644 --- a/internal/app/archied/control_plane_watch.go +++ b/internal/app/archied/control_plane_watch.go @@ -16,11 +16,7 @@ import ( // ENDS can take: a store that errors at once is charged, and so is one that // stalls for less than the window the attempt is judged against, because that // window is derived from the delay the attempt would otherwise be charged and -// widens with the ladder instead of sitting at its floor (attemptHealthy). The -// reach stops at the window: a stall still going when the window closes is read -// as a store that answered, so an outage whose every attempt takes at least -// that long leaves the ladder at the minimum -- deliberately, and pinned by -// TestKeepWatchTreatsAStallPastTheWindowAsAStoreThatAnswered. +// widens with the ladder instead of sitting at its floor (attemptHealthy). // // This loop charges only attempts that end, and imposes no timeout of its own: // nextUpdate waits on the stream and on the loop's own context, never on a @@ -55,7 +51,7 @@ const controlPlaneWatchHealthyMultiple = 2 // connection drops, or the server closes the stream. keepWatch reopens it in // place; workflow-execution-settings also reports the gap so apply status does // not keep re-stamping the previous successful version as current while no -// live updates can arrive (archie-core-1050). +// live updates can arrive. // // One goroutine per kind, reconnecting in place: a long outage does not stack // watchers. Reopening resumes after the last version an update carried, so a @@ -95,13 +91,12 @@ const controlPlaneWatchHealthyMultiple = 2 // controlPlaneWatchRetry for what ends an attempt against a peer that never // answers), so the reach of the rule stops at the window itself: a stall still // going when the window closes is read as a store that answered, and the delay -// stays at the minimum for as long as every attempt takes that long. That -// is deliberate rather than a gap to close with another rule. The stalled -// attempt lasts the window, so the reopens it leaves behind are bounded by the -// attempt and not by the delay -- about 0.8 a second at the minimum rung, -// against the four a second this rule exists to charge -- and a shape that slow -// is not the request loop it exists for. It is pinned by -// TestKeepWatchTreatsAStallPastTheWindowAsAStoreThatAnswered. +// stays at the minimum for as long as every attempt takes that long. That is +// deliberate rather than a gap to close with another rule. The stalled attempt +// lasts the window, so the reopens it leaves behind are bounded by the attempt +// and not by the delay -- about 0.8 a second at the minimum rung, against the +// four a second this rule exists to charge -- and a shape that slow is not the +// request loop it exists for. // // open, versionOf and deliver are the kind's halves. open re-establishes the // stream -- the caller opens the first one itself, so that a control plane @@ -113,10 +108,10 @@ const controlPlaneWatchHealthyMultiple = 2 // wait is the delay between a stream ending and the reopen that follows it, and // production passes waitFor. It is injected so that the delay the loop hands it // is observable as a value: the retry_in log line states the delay the loop -// charged, and a loop that charged one delay and waited another would leave that -// attribute agreeing with itself. What the injected wait cannot show is a -// multiple taken inside waitFor itself, which is a timer for exactly the d it is -// given (TestKeepWatchWaitsTheDelayItCharged reads the argument, not the wait). +// charged, and a loop that charged one delay and waited another would leave +// that attribute agreeing with itself. What the injected wait cannot show is a +// multiple taken inside waitFor itself, which is a timer for exactly the d it +// is given. func keepWatch[T any]( ctx context.Context, log *slog.Logger, @@ -187,12 +182,7 @@ func attemptHealthy(progressed bool, openFor, backoff time.Duration) bool { // delay the attempt would otherwise be charged, multiplied by // controlPlaneWatchHealthyMultiple. The window moves with the ladder, so the // charge reaches a store that fails slowly at every rung of it, which a window -// fixed at the minimum does not. The multiple is strictly more than one, so the -// window is always wider than that charge -- a store that fails as slowly as -// the charge it would be paid is still charged, which is the shape of -// TestWatchRetryGrowsWhileTheStateStoreIsDown that says so -- and an attempt is -// healthy at the window as well as past it (TestAttemptHealthyAtTheWindowBoundary -// pins that edge). +// fixed at the minimum does not. func controlPlaneWatchHealthyWindow(backoff time.Duration) time.Duration { return controlPlaneWatchHealthyMultiple * retryDelay(backoff, false) } @@ -216,8 +206,7 @@ func retryDelay(current time.Duration, healthy bool) time.Duration { // cancellation that asked it to stop. The coupling that is load-bearing runs // the other way: this watch returns on cancellation without draining what the // producer has left for it, so controlplane.Client's producer must stop on the -// same context instead of parking on a send no reader will ever take (its send -// guard is pinned by TestKeepWatchLeavesNoProducerParkedOnAnUndeliveredUpdate). +// same context instead of parking on a send no reader will ever take. func nextUpdate[T any](ctx context.Context, stream <-chan T) (T, bool) { select { case <-ctx.Done(): diff --git a/internal/app/archied/gateway.go b/internal/app/archied/gateway.go index 045a998de..7297cb9d8 100644 --- a/internal/app/archied/gateway.go +++ b/internal/app/archied/gateway.go @@ -67,7 +67,7 @@ func RunGateway(ctx context.Context, options GatewayOptions) error { } // The Gateway also no longer opens archie.db directly: it consumes the // same remote State Store contract the daemon does via - // [services.state].target (docs/prds/state-store-contract.md §12 step 7). + // [services.state].target. if err := b.openGatewayState(ctx); err != nil { return err } @@ -132,7 +132,7 @@ func (b *boot) serveGatewayListener(ctx context.Context, listener net.Listener, b.log.Info("archie-gateway running", "addr", listener.Addr().String(), "token_required", !loopback) // Boot is over and this listener is about to accept: the same fact // systemd's READY=1 asserts, so the announcement goes out here rather than - // from a second notion of "started" (archie-core-1174). Not later: Serve + // from a second notion of "started". Not later: Serve // begins accepting the moment it is called, and a unit whose // TimeoutStartSec expires first would restart a healthy process. b.announceReady() @@ -159,13 +159,10 @@ func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskAc b.capabilityHost = plugin.NewHost() b.startRateLimiter(ctx, b.cfg.Chat.RateLimit) // The Gateway composes the process-wide worktree manager before - // setupGatewayChat; nothing in this process reads it today (the old - // synchronous operator-review path that did was removed with the - // adversarial self-review system, archie-core-afbk.7 -- see that bead's - // continuation for the operator trigger's replacement). Kept for the + // setupGatewayChat; nothing in this process reads it today. Kept for the // manager's other consumers; it is the only part of the daemon's tree - // composition the Gateway takes -- it must not own identity runners, so - // it does not call buildTreesAndIdentities. + // composition the Gateway takes -- it must not own identity runners, so it + // does not call buildTreesAndIdentities. b.buildWorktreeManager() // setupMemoryEngine must run before setupGatewayChat: setupGatewayChat // constructs the turn runner, which captures b.memEngines at @@ -177,7 +174,7 @@ func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskAc if err != nil { return nil, err } - if err := b.registerTools(ctx); err != nil { + if err := b.registerTools(); err != nil { return nil, err } b.registerStandaloneTools() diff --git a/internal/app/archied/gateway_runtime.go b/internal/app/archied/gateway_runtime.go index ff186c492..bd2e8aa11 100644 --- a/internal/app/archied/gateway_runtime.go +++ b/internal/app/archied/gateway_runtime.go @@ -75,7 +75,6 @@ func (b *boot) setupChatRuntime(ctx context.Context, cfg config.Config) error { // Chat's /approve reaches the daemon's one task-action service rather // than its own requeue, so a chat approval and a dashboard approval // cannot record different decisions for one operator intent - // (docs/prds/pr-review-operator-response.md, Decision 1). approve: func(ctx context.Context, scope *string, actor taskactions.Actor, taskID int64, res taskactions.ActionPayload) error { return b.taskActions().Apply(ctx, scope, actor, taskID, taskstate.ActionApprove, res) }, @@ -90,9 +89,6 @@ func (b *boot) setupChatRuntime(ctx context.Context, cfg config.Config) error { // cannot be watched at all fails the boot that asked for it rather than // leaving the process running personas it can no longer update; after that the // watch reconnects instead of ending (see keepWatch). -// -// Persona updates are not reported through apply status -- the personas kind -// has no apply-status wiring, which is archie-core-aj35, not this watch. func (b *boot) watchPersonas(ctx context.Context, version int64) error { updates, err := b.controlPlane.WatchPersonas(ctx, version) if err != nil { diff --git a/internal/app/archied/health.go b/internal/app/archied/health.go index f9164fdac..82cd846c2 100644 --- a/internal/app/archied/health.go +++ b/internal/app/archied/health.go @@ -15,12 +15,9 @@ import ( // healthSurface is archied's own liveness endpoint, served on // [health].listen for the lifetime of the process. // -// The dashboard also answers /healthz, but on the dashboard's listener: that -// can be switched off, and in Phase 3 it belongs to a separate process -// entirely. Either way it is the wrong thing to ask "did archied come back -// up?" -- which is exactly what the update watchdog asks after restarting -// the daemon, and answers with a rollback when nothing replies -// (archie-core-1r4g, archie-core-exbz). +// Either way it is the wrong thing to ask "did archied come back up?" -- which +// is exactly what the update watchdog asks after restarting the daemon, and +// answers with a rollback when nothing replies // // serving gates the liveness answer: the listener binds early in boot, so // the port is answering before the daemon is, and a 200 before the daemon diff --git a/internal/app/archied/kit_launcher.go b/internal/app/archied/kit_launcher.go index 0ace13d46..3f21677a5 100644 --- a/internal/app/archied/kit_launcher.go +++ b/internal/app/archied/kit_launcher.go @@ -61,7 +61,6 @@ func (b *boot) setupKitLauncher(ctx context.Context) { } // grants is the production Resolver: Launch/Release Grant/RevokeGrant it // per run with exactly the declared-and-granted intersection - // (docs/prds/external-agent-harness.md, Credentials; archie-core-egkf.11). grants := egress.NewGrantResolver() // Without a harness secret store, Register refuses a Kit with a // required OAuth credential. diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 556badf61..62479fca4 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -359,10 +359,6 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence return 1 } - // The state-store adapter, its daemon-side surfaces and the policy chain - // dispatch evaluates: one ordered stage of the composition sequence - // (openStateStage; docs/prds/state-store-contract.md §12 step 7 and - // docs/prds/orgs-and-access.md). if err := b.openStateStage(ctx); err != nil { return 1 } @@ -406,7 +402,7 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence return 1 } - if err := b.loadWorkflows(ctx); err != nil { + if err := b.loadWorkflows(); err != nil { return 1 } if err := b.loadPlugins(); err != nil { @@ -425,7 +421,7 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence return 1 } - if err := b.registerTools(ctx); err != nil { + if err := b.registerTools(); err != nil { return 1 } b.registerStandaloneTools() @@ -441,7 +437,7 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence // wireConfigSurfaces attaches the dashboard's configuration read path and // the reload plumbing behind it. The write handlers (PATCH /api/config, the // per-repository field update, per-row reset) are descoped for the UI -// process (archie-core-ymut): the daemon still owns the validate-persist- +// process: the daemon still owns the validate-persist- // publish policy, but no HTTP route reaches it -- editing is config.toml // plus reload -- so only the snapshot publication and the override list the // renderer needs stay wired. @@ -453,11 +449,10 @@ func (b *boot) wireConfigSurfaces(ctx context.Context, cfgPath, overlayPath stri b.publishConfigSnapshot(ctx) } -// persistEvents drains the bus until it closes, giving each event an ID -// from the store. The store is the only fan-out point (docs/architecture/ -// migration-decisions.md, "Dashboard live event delivery"): the UI process -// reads the same table through its event pump, so the daemon's job is -// persistence, not delivery. +// persistEvents drains the bus until it closes, giving each event an ID from +// the store. The store is the only fan-out point: the UI process reads the same +// table through its event pump, so the daemon's job is persistence, not +// delivery. // // The insert deliberately outlives ctx: this loop ends when the bus closes, // which is part of shutdown, and the last events of a run are exactly the @@ -614,7 +609,7 @@ func (a chatTaskControllerAdapter) CancelChatTask(ctx context.Context, taskID in // An operator declining work lands in the same state whichever surface // they used, through the one cancel path: the store records the // cancellation -- every non-terminal step of the current attempt plus the - // execution's own move (docs/prds/execution-tree-state-machine.md) -- and + // execution's own move -- and // this write is what a late worker's next step write fails against. This // used to record StatusRejected while the dashboard recorded // StatusClosedWontDo, so the same decision showed up as two different @@ -653,7 +648,7 @@ func (a chatTaskLogReaderAdapter) ReadChatTaskLogs( // tasks, and tasks with no identity (forge-sourced) are not // readable through a chat tool at all — they belong to the daemon, // not a particular identity. "The empty string MUST NOT retain - // special meaning" (docs/architecture/identity.md). + // special meaning". if task.Identity != identity { return gateway.ChatTaskLogResult{}, fmt.Errorf("task %d belongs to %q, not %q", taskID, task.Identity, identity) } @@ -856,12 +851,11 @@ func subscribeAgentEvents(nc *natsio.Conn, bus *events.Bus, log *slog.Logger) (u }, nil } -// registerTaskRPCServers subscribes the forgerpc/worktreerpc handlers on nc -// so an archie-agent container (which holds no forge token, or push -// credential) can proxy those operations back to archied. The returned func -// unsubscribes all of them. The agent's store calls are NOT proxied here: they -// go over gRPC to the State Store (docs/prds/state-store-contract.md §12 step -// 4), so the legacy NATS storerpc registration is deleted. +// registerTaskRPCServers subscribes the forgerpc/worktreerpc handlers on nc so +// an archie-agent container (which holds no forge token, or push credential) +// can proxy those operations back to archied. The returned func unsubscribes +// all of them. The agent's store calls are NOT proxied here: they go over gRPC +// to the State Store, so the legacy NATS storerpc registration is deleted. // // Forge and worktree are identity-scoped: the root servers answer the root // (identity-less) subjects for single-identity deployments and root-owned @@ -941,10 +935,9 @@ func configuredNATSToken(cfg config.NATSConfig, getenv func(string) string) (str return token, nil } -// updateReportPath is where the update watchdog leaves the phase-2 outcome -// of an update for this identity to relay on its next launch. The identity is -// hashed so multiple identities sharing one daemon (see -// docs/architecture/identity.md) never collide. +// updateReportPath is where the update watchdog leaves the phase-2 outcome of +// an update for this identity to relay on its next launch. The identity is +// hashed so multiple identities sharing one daemon never collide. func updateReportPath(workDir, identity string) string { identityHash := sha256.Sum256([]byte(identity)) return filepath.Join( diff --git a/internal/app/archied/mcp_reconcile.go b/internal/app/archied/mcp_reconcile.go index 26d4f8d49..e8bea5330 100644 --- a/internal/app/archied/mcp_reconcile.go +++ b/internal/app/archied/mcp_reconcile.go @@ -18,7 +18,6 @@ import ( // from: the configuration it was built with and the manifest id it registered // under. A live tool-settings change diffs the stored server set against this // record, so a server that did not change is left running and untouched -// (archie-core-zfb0.3). type appliedMCPServer struct { server config.MCPServer id string diff --git a/internal/app/archied/plugin_reconcile.go b/internal/app/archied/plugin_reconcile.go index cef081dd1..99574d0f7 100644 --- a/internal/app/archied/plugin_reconcile.go +++ b/internal/app/archied/plugin_reconcile.go @@ -35,7 +35,7 @@ const ( // drop a file beside a running daemon and have it take effect without a // restart. Yaegi cannot unload an interpreter, so a removed file's code keeps // running and the reconciler reports it through apply status until the process -// restarts (docs/prds/plugin-settings-live.md). +// restarts. // // Files are content-hashed, so a tick loads only what appeared or changed: the // boot load's files are seeded as already loaded. A file whose load fails is @@ -170,7 +170,6 @@ func (r *pluginReconciler) reconcile(ctx context.Context) error { // it re-resolves provider credentials, so a provider disabled at boot for // an unresolvable engine is re-resolved on the first tick that finds it, // and a changed directory retargets the next tick without a restart - // (docs/prds/plugin-settings-live.md, "Triggers"). if r.relayer != nil { if err := r.relayer(ctx); err != nil { problems = append(problems, fmt.Errorf("re-resolve provider credentials: %w", err)) diff --git a/internal/app/archied/readiness.go b/internal/app/archied/readiness.go index b23381e5d..45ae597e1 100644 --- a/internal/app/archied/readiness.go +++ b/internal/app/archied/readiness.go @@ -27,7 +27,7 @@ import ( // // The probes read the daemon's state directly rather than through a // webui.Server: the daemon serves /health/detailed on its own listener and -// has served no dashboard since the UI process cutover (archie-core-ml30). +// has served no dashboard since the UI process cutover. func (b *boot) setupReadinessProbes() { cfg := b.cfg probes := []health.Probe{ @@ -38,8 +38,7 @@ func (b *boot) setupReadinessProbes() { // The daemon no longer runs a chat channel, so it cannot observe one's // lifecycle; channel health is the Messaging Service's own probe. What // this process depends on is the Gateway answering, so that is what it - // reports (docs/prds/ui-service-boundary.md, "Listen, authentication, - // and readiness"). + // reports. readiness.NewContractProbe("gateway", time.Duration(cfg.Health.DependencyTimeout), func(ctx context.Context) error { return pingChat(ctx, b.chat) }), diff --git a/internal/app/archied/reload.go b/internal/app/archied/reload.go index 93a8dc7c5..35bc0a91d 100644 --- a/internal/app/archied/reload.go +++ b/internal/app/archied/reload.go @@ -109,8 +109,7 @@ var reloadableFields = map[string]bool{ "Repos": true, // Per-task snapshot: ForTask carries these into every dispatched // TaskContext (config.go ForTask), built fresh from d.Cfg.Get() at - // dispatch. Pinned by TestReloadableFieldsCoverForTaskSnapshot so a - // field added to ForTask cannot silently drift out of this list. + // dispatch. "DiffCapLines": true, "Budgets": true, "Dispatch": true, @@ -131,17 +130,12 @@ var reloadableFields = map[string]bool{ "BotEmail": true, // cfg.Label additionally feeds IssuesWithLabel per poll cycle // (daemon.go:359,390) and cfg.BotUser feeds AssignedIssues (:364,377). - // Label is not carried by ForTask, so it is pinned by hand in - // TestReloadableFieldsCoverForTaskSnapshot. "Label": true, "BotUser": true, - // MaxRetries has two consumers, both re-reading it: the webui - // maxRetriesFor handler (api_tasks.go:380,383) reads it per request, and - // ForTask carries it into every dispatched TaskConfig, where the - // container's remediation round cap reads it (StageRemediationRoundCap). - // The per-task half of this list is pinned mechanically by - // TestReloadableFieldsCoverForTaskSnapshot; the webui-only entry is pinned - // by TestChangedNonReloadableFields. + // MaxRetries has two consumers, both re-reading it: the webui maxRetriesFor + // handler (api_tasks.go:380,383) reads it per request, and ForTask carries + // it into every dispatched TaskConfig, where the container's remediation + // round cap reads it (StageRemediationRoundCap). "MaxRetries": true, // Tools.Policy (MaxResultChars/SpillDir) is carried into TaskConfig by // ForTask (config.go) and applied fresh per dispatch via @@ -149,24 +143,6 @@ var reloadableFields = map[string]bool{ "ToolPolicy": true, } -// reloadableSubFields are sub-fields of structs that are otherwise -// startup-built. VolumeTTL is re-read per cycle in cleanupExpiredStorage; -// Profiles is resolved fresh per dispatch (daemon.configFor -> -// Containers.Profile, called from pinTaskProfile) and is also its own -// live-applying control-plane resource (AgentProfileKind), never captured at -// container-pool construction -- docs/prds/external-agent-harness.md -// "Selection": a Kit profile applies without a restart. Credentials is the -// same shape one layer down: kitrun.Launcher reads Config.Get().Containers. -// Credentials fresh on every Launch (CredentialBindingsKind), never a slice -// captured once when the launcher was built. Image, MaxConcurrency, MaxUptime, -// PullPolicy and Network are re-read per acquire by the container pool and -// MaxConcurrency also resizes the running dispatcher on publish -// (archie-core-zfb0.2), so a reload applies them without a restart. -// RegistryAuth stays frozen in the startup-built pool: it is file-owned and -// never part of the container-runtime-policies document, so a changed value -// must warn requires-restart. Forge.Host is carried into TaskContext by ForTask -// (display/link building only); the forge client itself is startup-built, so -// Type/Token/TokenEnv stay requires-restart. var reloadableSubFields = map[string]map[string]bool{ "Containers": { "VolumeTTL": true, "Profiles": true, "Credentials": true, diff --git a/internal/app/archied/sd_notify.go b/internal/app/archied/sd_notify.go index 6e2c2b409..130ccb452 100644 --- a/internal/app/archied/sd_notify.go +++ b/internal/app/archied/sd_notify.go @@ -5,8 +5,8 @@ // // The protocol client and the heartbeat sampler live in internal/sdnotify // because archie-messaging, a separate process that cannot import this -// package, is the next process that must be able to announce itself -// (archie-core-g5g8). What stays here is what is the daemon's own: which +// package, is the next process that must be able to announce itself. +// What stays here is what is the daemon's own: which // marker counts as progress (daemon.LastPollAt) and how long the loop may go // without beginning a poll pass. // @@ -30,7 +30,7 @@ import ( // announceReady tells systemd the daemon has finished starting. It is called at // the moment a process declares itself serving: the daemon's run loop (next to // healthSurface.markServing), and the serve steps of archie-gateway and -// archie-state-store (archie-core-1174), which have health surfaces of their +// archie-state-store, which have health surfaces of their // own and would otherwise hang a Type=notify unit until TimeoutStartSec while // perfectly healthy. func (b *boot) announceReady() { diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index 677a22480..c4a5ccfe1 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -3,10 +3,6 @@ // process inputs into RunStateStore, which serves the task and event-capture // stores from Postgres, registers every StateStore gRPC handler (the same service .4.2 serves // in-process on the daemon), and shuts down cleanly on ctx cancellation. -// -// See docs/prds/state-store-contract.md (rev. 2c) -- the single authoritative -// design surface -- and in particular §5 (binary layout), §9 (transport -// security boundary) and §11 (the store service owns its own DB lifecycle). package archied import ( @@ -57,7 +53,6 @@ type StateStoreOptions struct { // Listen is the gRPC listen address. Loopback binds (127.0.0.1, ::1, // localhost) serve insecure with no token; any non-loopback address // requires a non-empty token (or TLS), else the process fails closed - // (state-store-contract.md §9). Listen string // Token is the bearer token the State Store server validates for a // non-loopback listener. Empty falls back to [services.state].target_token. @@ -99,8 +94,8 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error { //nol } // The resumable default org/workspace upgrade runs before this process // serves anything: the State Store refuses scoped calls until its upgrade - // has finished, rather than serving records with no org - // (docs/prds/orgs-and-access.md, "Upgrading existing installs"). A store + // has finished, rather than serving records with no org. + // A store // without the upgrader is one that owns no tenant boundary yet, so the // absence degrades to "no upgrade" rather than aborting boot. if upgrader, ok := b.st.(org.Upgrader); ok { @@ -150,8 +145,8 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error { //nol // Boot is over and every listener this process serves is bound: the gRPC // contract below and, when -ready-addr asked for one, the readiness HTTP // surface. systemd's READY=1 asserts the same fact, so the announcement - // goes out here rather than from a second notion of "started" - // (archie-core-1174). Not earlier: a readiness surface that fails to bind + // goes out here rather than from a second notion of "started". + // Not earlier: a readiness surface that fails to bind // fails the boot, and READY must not precede it. Not later: Serve begins // accepting the moment it is called. b.announceReady() @@ -161,14 +156,13 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error { //nol return serveStateStore(ctx, listener, deps, opts) } -// seedAndValidatePolicies seeds the shipped role policies for every org -// that lacks them, grants the agent identities their org's shipped developer -// role, and re-validates every stored policy this process serves -// (docs/prds/orgs-and-access.md, "Storing and changing policies" and -// "Roles"). An invalid org, workspace or object policy is logged here and -// named as a problem by the engines the consumers build; an invalid instance -// policy fails this boot -- the store stops serving until it is fixed. A -// store without the access surfaces degrades: there is no chain to seed. +// seedAndValidatePolicies seeds the shipped role policies for every org that +// lacks them, grants the agent identities their org's shipped developer role, +// and re-validates every stored policy this process serves. An invalid org, +// workspace or object policy is logged here and named as a problem by the +// engines the consumers build; an invalid instance policy fails this boot -- +// the store stops serving until it is fixed. A store without the access +// surfaces degrades: there is no chain to seed. func (b *boot) seedAndValidatePolicies(ctx context.Context) error { policies, ok := b.st.(access.PolicyStore) if !ok { @@ -210,8 +204,7 @@ func (b *boot) seedAndValidatePolicies(ctx context.Context) error { // reportUnseededResources logs every kind ImportConfig could not seed. // // Reported, not fatal: a stale TOML value in a setting the database owns must -// not stop this process from starting (docs/prds/runtime-control-plane.md, -// "Bootstrap, migration, and recovery"). The kind stays ABSENT rather than +// not stop this process from starting. The kind stays ABSENT rather than // half-written, so the file document's value is the one in effect for every // reader -- the layering leaves a kind with no stored value alone // (controlplane.resourceReader) -- and the operator's fix is still the file. @@ -237,10 +230,6 @@ func (b *boot) reportUnseededResources(skipped []controlplane.SeedSkip) { // registers before it compiles one, so within one build a definition this // server admits is compilable there; a skewed deploy is only fixed by a // matching deploy. -// -// It is separate from RunStateStore so that function stays within its -// complexity budget, and step_vocabulary_test.go pins both the call to -// stepVocabulary below and RunStateStore's call to this function. func openStateStoreControlPlane(resources controlplane.ResourceStore) (*controlplane.Server, error) { steps, err := stepVocabulary() if err != nil { @@ -317,7 +306,7 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps { } // Task logs live in the state directory, which this process owns, and the // dashboard process owns no such directory -- so this is where a task-log - // read is served from (docs/prds/ui-service-boundary.md). The reader is + // read is served from. The reader is // the daemon's own registry over the configured state_dir. // // The nil check is on the registry, not on the interface it is assigned @@ -342,7 +331,7 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps { deps.Sources = b.eda deps.MappingMatches = b.eda // HarnessSecrets rides the same encrypted-at-rest store as source - // webhook secrets (docs/prds/binding-secret-encryption.md), under its + // webhook secrets, under its // own domain separator (bindingcipher.HarnessSecretDomain). deps.HarnessSecrets = b.eda } @@ -391,7 +380,7 @@ func (b *boot) executionDeps(deps *staterpc.Deps) { } // accessDeps wires the policy chain and its denial records from the same -// store (docs/prds/orgs-and-access.md). A store without them -- one that owns +// store. A store without them -- one that owns // no tenant boundary yet -- degrades the access RPCs rather than failing the // boot, the same pattern the other optional surfaces use. func (b *boot) accessDeps(deps *staterpc.Deps) { @@ -468,7 +457,7 @@ func (b *boot) startOptionalSurfaces(ctx context.Context, options StateStoreOpti return nil } -// stateStoreServerOpts applies the transport security boundary (§9): a +// stateStoreServerOpts applies the transport security boundary: a // loopback listener is served insecure with no token; any non-loopback // address requires a bearer token, else the process fails closed. It cannot // enforce TLS/mTLS (an operator decision), so it narrows the non-loopback diff --git a/internal/app/archied/state_store_client.go b/internal/app/archied/state_store_client.go index d8e8e4a96..173a3f8aa 100644 --- a/internal/app/archied/state_store_client.go +++ b/internal/app/archied/state_store_client.go @@ -9,7 +9,7 @@ import ( // composeStateStoreClient dials the State Store gRPC service the daemon's own // capture/mapping/binding consumers call. Token resolution is the daemon's // (it owns the config keys and the secret registry); the dial itself and the -// fail-closed non-loopback rule (§9) belong to the transport, so they come +// fail-closed non-loopback rule belong to the transport, so they come // from staterpc.Dial. func composeStateStoreClient(services config.Services, secrets *secret.Registry) (*staterpc.Client, func(), error) { target, err := services.RequireTarget(config.ServiceNameState) diff --git a/internal/app/archied/state_store_recovery.go b/internal/app/archied/state_store_recovery.go index f13393b6b..dbd6f2ea4 100644 --- a/internal/app/archied/state_store_recovery.go +++ b/internal/app/archied/state_store_recovery.go @@ -3,7 +3,6 @@ // fails closed: a stored setting that will not validate stops archied // starting, and the in-band remedy -- replaying an earlier revision while the // State Store is up -- is unavailable in exactly the case that needs it -// (docs/architecture/safe-change-and-recovery.md). // // Every operation but import works on the PostgreSQL database database_url // names (state_store_recovery_postgres.go). The ones that write refuse while a diff --git a/internal/app/archied/state_store_toolcalls.go b/internal/app/archied/state_store_toolcalls.go index 05d3f0981..96d23049d 100644 --- a/internal/app/archied/state_store_toolcalls.go +++ b/internal/app/archied/state_store_toolcalls.go @@ -40,14 +40,6 @@ func newToolCallProjectingTaskStore(inner storecontract.TaskStore, toolCalls too return &toolCallProjectingTaskStore{TaskStore: inner, toolCalls: toolCalls, log: log} } -// toolCallProjectionFailures reports how many tool_call projections have been -// dropped since this process started. Named and exported to the test surface -// rather than buried in a log field alone: a silent swallow is the bug this -// decorator exists not to have. -func (s *toolCallProjectingTaskStore) toolCallProjectionFailures() int64 { - return s.projectionFailures.Load() -} - func (s *toolCallProjectingTaskStore) InsertEvent(ctx context.Context, e events.Event) (int64, error) { id, err := s.TaskStore.InsertEvent(ctx, e) if err != nil || e.Kind != events.KindToolCall { diff --git a/internal/app/archied/step_vocabulary.go b/internal/app/archied/step_vocabulary.go index 68600f9ae..45303f7a5 100644 --- a/internal/app/archied/step_vocabulary.go +++ b/internal/app/archied/step_vocabulary.go @@ -19,11 +19,6 @@ import ( // definition registers no vocabulary and cannot be failed by one, which is why // the gateway root and internal/app/archiemessaging are not here. // -// It is a named function so that step_vocabulary_test.go can fail if a root -// stops resolving the shipped stages, or hands a constructor a manager other -// than the one this returns; the roots themselves open a database and dial -// gRPC, so the test asserts their wiring by parsing their bodies. -// // Agreement is within one build: the State Store and archie-agent are // separately deployed binaries, so a State Store built from newer source than // the agent it dispatches to can still disagree, and only a matching deploy @@ -66,7 +61,7 @@ func (b *boot) openDaemonWorkflowDefinitions() error { // two calls owe each other is a property of the pair, not of that sequence: the // definitions client wraps the control-plane transport the adapter dials, so it // cannot be built first, and buildDaemon captures the client, so it cannot be -// built later. step_vocabulary_test.go pins exactly that order here. +// built later. // // The gateway root calls openStateStoreAdapter directly and stops there; the // daemon-only half stays out of that function for the reason above it. diff --git a/internal/app/archied/update_relay.go b/internal/app/archied/update_relay.go index 9d26ed348..c0b21ce80 100644 --- a/internal/app/archied/update_relay.go +++ b/internal/app/archied/update_relay.go @@ -19,7 +19,7 @@ const updateReportPollInterval = 2 * time.Second // restarts archied and leaves its verdict in a file on archied's host, so // only archied can read it. It previously ran inside the dashboard's own // Run, which put a host-local file read in the process that is moving off -// the host (archie-core-8cda.5.4). The report reaches an operator the same +// the host. The report reaches an operator the same // way it always did, as an event -- persisted with every other event and // delivered to whichever dashboard is watching. // diff --git a/internal/app/archiemessaging/channel_status.go b/internal/app/archiemessaging/channel_status.go index 52fb93012..65e62aec3 100644 --- a/internal/app/archiemessaging/channel_status.go +++ b/internal/app/archiemessaging/channel_status.go @@ -33,7 +33,7 @@ func channelDescriptors(instances []*channelInstance) []status.Descriptor { // reloadable reports whether this channel can re-read its configuration. It is // the single source for both the capability a descriptor declares and the action // a reload performs; deriving them separately is how a dashboard ends up offering -// a button that reports success and changes nothing (archie-core-np7l). +// a button that reports success and changes nothing. func reloadable(instance *channelInstance) bool { gateway, ok := instance.current().(*telegram.Gateway) return ok && gateway.Reload != nil @@ -72,8 +72,8 @@ func (s *Service) ReloadChannel(_ context.Context, id string) error { // // Before this, Start handed every channel an empty channels.Lifecycle{}, so // nothing recorded starting, running or failed anywhere and -// internal/channels/status.Manager had no production writer at all -// (archie-core-8cda.6.8). The channels have always reported: all three call +// internal/channels/status.Manager had no production writer at all. +// The channels have always reported: all three call // ReportStarting and ReportRunning on whichever lifecycle they are handed. func (s *Service) lifecycleFor(id string) channels.Lifecycle { return channels.Lifecycle{ diff --git a/internal/app/archiemessaging/compose.go b/internal/app/archiemessaging/compose.go index 4d9b863a0..bef98b99f 100644 --- a/internal/app/archiemessaging/compose.go +++ b/internal/app/archiemessaging/compose.go @@ -310,11 +310,7 @@ func (s *Service) Start(ctx context.Context) error { } // Every configured channel has been handed its lifetime and the service - // blocks here serving them. systemd's READY=1 asserts the same fact this - // line has just established, so the announcement goes out here rather than - // from a second notion of "started" (the convention archie-core-1174 set - // for the daemon, the Gateway and the State Store; archie-core-g5g8 is this - // process joining them). Not earlier: a channel whose configuration is + // blocks here serving them. Not earlier: a channel whose configuration is // invalid fails composition, above, and READY must not precede it. Not // later: a unit whose TimeoutStartSec expires first would restart a healthy // process. Nothing is consumed until the unit says Type=notify, so this is diff --git a/internal/app/archiemessaging/config.go b/internal/app/archiemessaging/config.go index 1d1883e9e..d2c61880f 100644 --- a/internal/app/archiemessaging/config.go +++ b/internal/app/archiemessaging/config.go @@ -24,8 +24,7 @@ type ResolvedConfig struct { // WorkDir, BotUser and HealthURL are not channel transport settings. They // locate this identity's release-announcement and update-report state // files, and give the update installer the daemon health endpoint to poll - // after it applies one (docs/architecture/migration-decisions.md, "Telegram - // operator surface after extraction"). + // after it applies one. WorkDir string BotUser string HealthURL string diff --git a/internal/app/archiemessaging/options.go b/internal/app/archiemessaging/options.go index b808eb504..d8800ca86 100644 --- a/internal/app/archiemessaging/options.go +++ b/internal/app/archiemessaging/options.go @@ -2,9 +2,8 @@ // channel connections (Telegram, email, webhook) served against a Gateway running // over its gRPC contract. // -// docs/prds/messaging-service-boundary.md is the authority. The Messaging Service -// owns channel persistent connections and dispatches turns directly to Gateway's -// ChatContract over gRPC. +// The Messaging Service owns channel persistent connections and dispatches +// turns directly to Gateway's ChatContract over gRPC. package archiemessaging import ( diff --git a/internal/app/archiemessaging/reconcile.go b/internal/app/archiemessaging/reconcile.go index 59386c459..b9dd4fc3e 100644 --- a/internal/app/archiemessaging/reconcile.go +++ b/internal/app/archiemessaging/reconcile.go @@ -25,7 +25,7 @@ type chatSettingsSource interface { // interval is the cadence every process already reports at, the messaging // process has no other control-plane watch to share a reconnect ladder with, // and a stored document that cannot be read must leave the running channels -// alone (docs/prds/plugin-settings-live.md). +// alone. func (s *Service) reconcileLoop(ctx context.Context) { ticker := time.NewTicker(s.reconcileInterval) defer ticker.Stop() @@ -117,8 +117,7 @@ func resolveChatSecrets(base ResolvedConfig, layered config.ChatConfig) (Resolve // The composed set and the listen addresses are fixed for the life of the // process. Enabling or disabling a channel and rebinding a listen address are // process bindings; the change is refused and reported for a restart instead of -// applied (docs/prds/runtime-control-plane.md, "Some changes require a -// restart"). +// applied. func (s *Service) applyChannelSettings(next ResolvedConfig) (bool, error) { current := s.currentConfig() effective, outstanding := pinProcessBindings(current, next) diff --git a/internal/app/archiemessaging/supervise.go b/internal/app/archiemessaging/supervise.go index b940b1348..e7871b7f2 100644 --- a/internal/app/archiemessaging/supervise.go +++ b/internal/app/archiemessaging/supervise.go @@ -16,7 +16,7 @@ import ( // The supervisor is per channel rather than one loop over every channel // because a channel-settings change must restart exactly the channel whose // settings changed: cancelling one run context stops one channel and leaves the -// rest serving (archie-core-zfb0.4). +// rest serving. func (s *Service) runChannel(ctx context.Context, c *channelInstance) { defer s.wg.Done() for { @@ -77,7 +77,6 @@ func (s *Service) runChannel(ctx context.Context, c *channelInstance) { // restartChannel stops the running channel id and starts a replacement built // from next. The replacement is built before the running channel is touched, so // a configuration this build cannot run leaves the running channel serving -// (the validate-before-switch rule in docs/prds/runtime-control-plane.md). // // A channel that is not currently supervised is not restarted: it already // stopped on its own, and resurrecting it here would race that exit. The caller diff --git a/internal/app/archiemessaging/telegram_features.go b/internal/app/archiemessaging/telegram_features.go index 2de0a72c7..5c2408370 100644 --- a/internal/app/archiemessaging/telegram_features.go +++ b/internal/app/archiemessaging/telegram_features.go @@ -16,12 +16,8 @@ import ( ) // configureTelegram wires the operator seams telegram.Gateway leaves to its -// composition root. Which process may satisfy each one is settled in -// docs/architecture/migration-decisions.md ("Telegram operator surface after -// extraction"); notably ReleaseAnnouncements and Dangerous stay nil, because -// nothing this process can observe would make them true. RunningVersions is -// supplied here from this process's own build stamp; see -// messagingRunningVersions. +// composition root. RunningVersions is supplied here from this process's own +// build stamp; see messagingRunningVersions. func configureTelegram(ctx context.Context, g *telegram.Gateway, cfg ResolvedConfig, chat messaging.ChatContract, log *slog.Logger) { g.Version = gatewayVersionReporter(ctx, chat, cfg.Options.DependencyTimeout) g.SetShowToolCalls(cfg.ShowToolCalls) @@ -49,7 +45,6 @@ func configureTelegram(ctx context.Context, g *telegram.Gateway, cfg ResolvedCon // from, which Verify reads as drift rather than false success. Reading the // version from the Gateway instead would report a different process's stamp, // which is the failure mode the check exists to catch (see -// docs/architecture/migration-decisions.md). // // The agent is deliberately absent: every archie-agent process is task-scoped // and observed only through daemon.AgentStatus, which this process does not @@ -131,10 +126,9 @@ func telegramReloader(o Options, log *slog.Logger) func(*telegram.Gateway) error } // identityStatePath names a per-identity state file under workDir. The identity -// is hashed so several identities sharing one work directory (see -// docs/architecture/identity.md) never collide. The scheme is the daemon's, -// unchanged: a different path would replay every release announcement the -// operator has already been shown. +// is hashed so several identities sharing one work directory never collide. The +// scheme is the daemon's, unchanged: a different path would replay every +// release announcement the operator has already been shown. func identityStatePath(workDir, kind, identity string) string { identityHash := sha256.Sum256([]byte(identity)) return filepath.Join(workDir, fmt.Sprintf("%s-%x.json", kind, identityHash[:8])) diff --git a/internal/app/archieplaybooks/lint.go b/internal/app/archieplaybooks/lint.go index 1511c23e4..d2327f99d 100644 --- a/internal/app/archieplaybooks/lint.go +++ b/internal/app/archieplaybooks/lint.go @@ -5,7 +5,7 @@ // internal/domain/workflow (routing binding files) and // internal/domain/eda/playbook (EDA playbooks) -- this package only calls the // loaders the daemon runs and formats results; there is deliberately no -// second validation path here (per docs/prds/eda-playbook-engine.md). +// second validation path here. package archieplaybooks import ( diff --git a/internal/app/archieui/compose.go b/internal/app/archieui/compose.go index 050d0ac43..6ce9c696c 100644 --- a/internal/app/archieui/compose.go +++ b/internal/app/archieui/compose.go @@ -35,46 +35,18 @@ type deps struct { // configured for it. Login identity.LoginFlow // Access evaluates the policy chain; Principals assembles the request - // principal; Denials records refusals - // (docs/prds/orgs-and-access.md). Wired together or not at all. + // principal; Denials records refusals. + // Wired together or not at all. Access access.Authorizer Principals access.PrincipalSource Denials access.DenialStore } -// compose builds the dashboard server for the UI process. It sets exactly the -// fields a contract already carries plus this process's own settings, and -// leaves every remaining field at its zero value on purpose: each one is a -// daemon-local runtime handle with no contract behind it, and the handlers -// already degrade to a documented 501/503/empty response rather than panicking -// (docs/prds/ui-service-boundary.md:130-131). -// -// What is deliberately absent, and which bead fills it: -// -// - Cfg, LastReload, UpdateConfig, ConfigOverrides, ResetConfig, -// UpdateRepoField: the configuration owner stays the daemon. The read -// crosses as the snapshot ConfigSource renders; the write routes answer -// 503 and the page hides their controls (archie-core-ymut). -// - LogFeed, Events, Channels, ReloadChannel, Curators, Memory, -// Workflows, WorkRequests, RunningVersions, Chat.Updates, -// UpdateReportPath: no contract exists for these yet. -// Defining one amends the owning service's contract first -// (docs/prds/ui-service-boundary.md:205-207); the route migration is -// archie-core-8cda.5.3. -// - TaskLogs: wired below from the store client's TaskLogStore contract. -// Task log files live in the state directory the State Store owns, so this -// process reads one attempt's log over that contract rather than opening -// the file itself -- which would only work on a single host and is exactly -// what the boundary forbids (archie-core-iaqx). -// - Captures, CaptureIntake, CaptureMaxEvents: wired below. From the -// cutover change (archie-core-8cda.5.4) this process is the only -// listener serving POST /webhooks/capture/{source}: the receiver is a -// persistence shim over the State Store contract, and the daemon's -// binding-dispatch loop keeps consuming captures from the same store, -// so the HTTP front door moved here without moving the owner of work -// intake. Mounting it before the daemon's listener was gone would have -// given two listeners the same intake authority, which the PRD forbids -// (docs/prds/ui-service-boundary.md:30-33). +// compose builds the dashboard server for the UI process from contract-backed +// dependencies only. Fields left at zero are daemon-local handles; their +// handlers answer 501/503 or empty. Config writes stay with the daemon. Task +// logs are read through the State Store, and this process is the only listener +// for POST /webhooks/capture/{source}. func compose(d deps) *webui.Server { srv := &webui.Server{ Store: d.Store, @@ -96,7 +68,6 @@ func compose(d deps) *webui.Server { // Channel lifecycle follows the same split as the config view: the process // hosting the channels publishes, this one reads. Withholding it left // /api/channels answering with nothing while channels were running - // (archie-core-8cda.6.8). if channels, ok := d.Store.(storecontract.ChannelStatusStore); ok { srv.Channels = webui.RemoteChannelStatus(channels) } @@ -115,8 +86,8 @@ func compose(d deps) *webui.Server { } // Harness OAuth token sets are a ratified State Store contract, and the // same client already carries them. Withholding it would leave the - // harness page answering 503 on a deployment that has the store - // (archie-core-egkf.7). The setup terminal itself is not wired here: its + // harness page answering 503 on a deployment that has the store. + // The setup terminal itself is not wired here: its // implementation owns a container, which this process must not link, so // the route stays a documented 503 until a daemon-side contract exists. if secrets, ok := d.Store.(storecontract.HarnessSecretStore); ok { @@ -130,11 +101,10 @@ func compose(d deps) *webui.Server { } // The task-log read crosses the State Store contract: the files live in // the state directory that process owns, so this one asks for the log - // rather than opening a path (docs/prds/ui-service-boundary.md). Withholding + // rather than opening a path. Withholding // it would degrade a page that has an owner, and would leave the dashboard // claiming task logging was not enabled -- see wireTaskLogs. // The policy chain: wired together or not at all - // (docs/prds/orgs-and-access.md, "Where it lives"). srv.Access = d.Access srv.Principals = d.Principals srv.Denials = d.Denials diff --git a/internal/app/archieui/config.go b/internal/app/archieui/config.go index bd4776755..a8dde99d9 100644 --- a/internal/app/archieui/config.go +++ b/internal/app/archieui/config.go @@ -19,13 +19,11 @@ import ( // // The projection is an allowlist of the values this process needs -- // [services.gateway].{target,target_token}, [services.state].{target, -// target_token}, [web].{listen,trust_forwarded_headers} and [capture] (the -// receiver this process mounts; archie-core-8cda.5.4). The UI reads the -// same file the daemon does because operators already keep the service -// endpoints there, but Options has no field for anything else in it: the -// daemon's forge credentials, model catalog, workflow routing, NATS settings, -// filesystem jail and agent/container settings have nowhere to land -// (docs/prds/ui-service-boundary.md:87-89). +// target_token}, [web].{listen,trust_forwarded_headers} and [capture]. The UI +// reads the same file the daemon does because operators already keep the +// service endpoints there, but Options has no field for anything else in it: +// the daemon's forge credentials, model catalog, workflow routing, NATS +// settings, filesystem jail and agent/container settings have nowhere to land func Resolve(o Options, log *slog.Logger) (Options, error) { if o.Config != "" { cfg, found, err := readProjection(o.Config, o.Overlay, log) @@ -194,11 +192,9 @@ func resolveToken(o Options) (string, error) { return webui.LoadOrCreateToken(o.TokenFile) } -// validate holds the PRD's security posture (lines 116-118): a loopback -// listener may omit the dashboard token, a non-loopback listener requires one -// and fails closed without it. Unlike the daemon, which mints a token -// silently, this process refuses to start -- an operator who exposed the -// dashboard by accident learns about it here rather than from the log. +// Unlike the daemon, which mints a token silently, this process refuses to +// start -- an operator who exposed the dashboard by accident learns about it +// here rather than from the log. func (o Options) validate() error { if o.Gateway.Target == "" { return fmt.Errorf("gateway target is required (-gateway-target or [services.gateway].target)") diff --git a/internal/app/archieui/options.go b/internal/app/archieui/options.go index 5384ec73b..c811326fa 100644 --- a/internal/app/archieui/options.go +++ b/internal/app/archieui/options.go @@ -2,17 +2,13 @@ // HTTP surface and the compiled SPA, served against a Gateway and a State // Store running in other processes. // -// docs/prds/ui-service-boundary.md is the authority. The two rules that shape -// this package are that the UI owns only process-local settings ("HTTP listen -// address and read/header/shutdown timeouts; UI asset source or build mode; -// UI authentication mode and token reference; Gateway endpoint and credential -// reference; State Store endpoint and credential reference; readiness -// endpoint and dependency timeout policy"), and that it "must never implement -// [configuration] policy by holding or mutating a shared config.Holder". -// -// It deliberately lives outside internal/app/archied: that package's -// dependency graph carries the daemon, forge, container and workflow runtimes -// that the PRD's deletion gate forbids the UI process from linking. +// The two rules that shape this package are that the UI owns only process-local +// settings ("HTTP listen address and read/header/shutdown timeouts; UI asset +// source or build mode; UI authentication mode and token reference; Gateway +// endpoint and credential reference; State Store endpoint and credential +// reference; readiness endpoint and dependency timeout policy"), and that it +// "must never implement [configuration] policy by holding or mutating a shared +// config.Holder". package archieui import ( @@ -82,8 +78,8 @@ type Options struct { TrustForwardedHeaders *bool // Capture configures the unbound webhook capture receiver this process - // mounts on its bypass mux (docs/prds/event-capture-storage.md). At the - // cutover (archie-core-8cda.5.4) this process is the only listener + // mounts on its bypass mux. At the + // cutover this process is the only listener // serving POST /webhooks/capture/{source}: the receiver persists what // arrives through the State Store contract, and the daemon's // binding-dispatch loop consumes captures from the same store, so the @@ -98,11 +94,8 @@ type Options struct { // DependencyTimeout bounds each readiness probe's call to a dependency. DependencyTimeout time.Duration - // EventPollInterval bounds how stale the dashboard's activity feed can - // be. This process owns no event bus, so live activity is a poll of the - // State Store's event cursor; see webui.DefaultEventPollInterval and - // docs/architecture/migration-decisions.md, "Dashboard live event - // delivery". + // EventPollInterval bounds how stale the dashboard's activity feed can be. + // Live activity is a poll of the State Store's event cursor. EventPollInterval time.Duration // ReadHeaderTimeout and ShutdownTimeout bound the HTTP lifecycle. ReadHeaderTimeout time.Duration diff --git a/internal/app/archieui/readiness.go b/internal/app/archieui/readiness.go index 77c0f272d..fc82b3f78 100644 --- a/internal/app/archieui/readiness.go +++ b/internal/app/archieui/readiness.go @@ -14,7 +14,6 @@ import ( // UI is ready when both of its mandatory remote contracts answer within the // dependency timeout; each probe consumes the dependency's own result over // the wire and never inspects its manager, registry or database -// (docs/prds/ui-service-boundary.md:126-132). // // The component names match the daemon dashboard's, so the readiness view // reads the same whichever process serves it. diff --git a/internal/app/archieui/run.go b/internal/app/archieui/run.go index ab9e9ed80..9f4fa6785 100644 --- a/internal/app/archieui/run.go +++ b/internal/app/archieui/run.go @@ -111,9 +111,8 @@ func Run(ctx context.Context, options Options) error { // Live activity has no in-process bus in this process: the pump reads // events back out of the State Store over the same cursor SSE catch-up - // uses. Backgrounded so priming past a large events table cannot delay - // the listener (docs/architecture/migration-decisions.md, "Dashboard - // live event delivery"). + // uses. Backgrounded so priming past a large events table cannot delay the + // listener. go func() { if err := srv.PumpEvents(ctx, opts.EventPollInterval); err != nil { log.Error("event pump stopped; the activity feed will only show history", "err", err) @@ -156,7 +155,7 @@ func serve(ctx context.Context, listener net.Listener, handler http.Handler, opt // Shutdown returned once the drain deadline elapsed with a request // still in flight. Force-close what is left so shutdown finishes // and the process exits cleanly rather than carrying a deadline - // error to the operator as a fatal exit (archie-core-u4xu). + // error to the operator as a fatal exit. _ = server.Close() } return nil diff --git a/internal/app/controlplane/agent_profiles.go b/internal/app/controlplane/agent_profiles.go index 2593acca7..9ff138b24 100644 --- a/internal/app/controlplane/agent_profiles.go +++ b/internal/app/controlplane/agent_profiles.go @@ -2,18 +2,9 @@ package controlplane import "github.com/samcharles93/archie-core/internal/config" -// AgentProfileKind is the control-plane resource for Kit and image agent -// profiles. It exists so a Kit profile applies without a restart -// (docs/prds/external-agent-harness.md, "Selection"): [containers].profiles -// in config.toml is only its seed, ContainerRuntimePoliciesKind carries every -// other container setting and none of this one (config.ContainerConfig. -// Profiles is json:"-"), and this resource's own ApplyMode is "live". -// -// Its document is agentProfile (container_settings.go's snake_case wire -// type), not config.AgentProfile directly: that internal type carries no -// json tags, so encoding/json would fall back to its Go field names -- -// "Tools", "Image" -- exactly the defect archie-core-1171 fixed for the rest -// of this document family. +// AgentProfileKind is the control-plane resource holding agent profiles. Its +// document is the snake_case agentProfile wire type, not config.AgentProfile, +// which has no json tags. const AgentProfileKind = "agent-profiles" func agentProfileDefinition() Definition { diff --git a/internal/app/controlplane/channel_settings.go b/internal/app/controlplane/channel_settings.go index 3489821b7..903b021d7 100644 --- a/internal/app/controlplane/channel_settings.go +++ b/internal/app/controlplane/channel_settings.go @@ -10,8 +10,8 @@ import ( // The channel-settings DOCUMENT lives in internal/infrastructure/controlplanerpc, // beside the client that projects it, so a process that only reads stored -// settings does not link this package's store-backed server and workflow engine -// (archie-core-1ng1). These aliases keep the store-backed side reading the same +// settings does not link this package's store-backed server and workflow engine. +// These aliases keep the store-backed side reading the same // types by the same names it always used, so there is one definition of the // document rather than a copy on each side of the boundary. type ( diff --git a/internal/app/controlplane/client.go b/internal/app/controlplane/client.go index 8547fe245..a2a312e31 100644 --- a/internal/app/controlplane/client.go +++ b/internal/app/controlplane/client.go @@ -26,7 +26,7 @@ import ( // embeds the Messaging Service's client -- the generic resource read path and // the channel-settings projection -- and adds the resource-specific reads and // watches, which need the workflow and scheduling engines that such a process -// already links (archie-core-1ng1). +// already links. type Client struct { *controlplanerpc.Client rpc pb.ControlPlaneServiceClient @@ -146,8 +146,8 @@ type AppliedResource struct { } // WatchResource streams version updates for any resource kind without -// decoding the document. It is the shape the runtime-resource watches read -// (archie-core-zfb0.1): keepWatch reconnects on it exactly as it does on a +// decoding the document. It is the shape the runtime-resource watches read: +// keepWatch reconnects on it exactly as it does on a // typed stream, and the resume point still moves past a document the client // refused to decode -- the store answered with that version, and resuming // before it would re-offer it on every reconnect. diff --git a/internal/app/controlplane/container_settings.go b/internal/app/controlplane/container_settings.go index 0d3b9b3f1..d7856488c 100644 --- a/internal/app/controlplane/container_settings.go +++ b/internal/app/controlplane/container_settings.go @@ -15,13 +15,11 @@ import ( // directly: that struct's tags belong to the TOML file format, and when it was // the document, encoding/json fell back to its Go field names -- "Image", // "MaxConcurrency", "LegacyEnabled" -- the only Go-cased resource left in the -// registry (archie-core-1171). The two durations are config.Duration, which +// registry. The two durations are config.Duration, which // already writes the string the file accepts; the leak was the keys only. // -// Profiles is deliberately not a field here: config.ContainerConfig.Profiles -// is json:"-" (its own resource, AgentProfileKind, applies live where the -// rest of this one is restart-required -- docs/prds/external-agent-harness.md -// "Selection"), so this document never carries it either. +// Profiles is deliberately not a field here: config.ContainerConfig.Profiles is +// json:"-", so this document never carries it either. type containerRuntimePolicies struct { Image string `json:"image"` MaxConcurrency int `json:"max_concurrency"` diff --git a/internal/app/controlplane/credential_bindings.go b/internal/app/controlplane/credential_bindings.go index 4c9031519..85c1e2064 100644 --- a/internal/app/controlplane/credential_bindings.go +++ b/internal/app/controlplane/credential_bindings.go @@ -4,7 +4,6 @@ import "github.com/samcharles93/archie-core/internal/config" // CredentialBindingsKind is the control-plane resource mapping a Kit // credential@1 service name to an org secret -// (docs/prds/external-agent-harness.md, Credentials; docs/prds/orgs-and-access.md). // It exists so a binding applies without a restart, the same reason // AgentProfileKind is its own resource: [containers].credentials in // config.toml is only its seed, and kitrun.Launcher reads the live diff --git a/internal/app/controlplane/operational_settings.go b/internal/app/controlplane/operational_settings.go index eaa306021..a42ef45e0 100644 --- a/internal/app/controlplane/operational_settings.go +++ b/internal/app/controlplane/operational_settings.go @@ -48,8 +48,8 @@ func operationalDefinitions() []Definition { // ApplyMode is live: the daemon diffs the stored MCP server set against // the running providers -- connecting added servers, disconnecting // removed ones and reconnecting changed ones while leaving unchanged - // servers untouched -- and rebuilds the web_fetch and minimax entries - // (archie-core-zfb0.3). A changed server whose new engine fails to start + // servers untouched -- and rebuilds the web_fetch and minimax entries. + // A changed server whose new engine fails to start // is rolled back to the old one, so the refusal is reported rather than // leaving the server down. {Kind: ToolSettingsKind, Title: "Tool and MCP settings", ApplyMode: "live", Document: toolSettings{}, Seed: seedTools, Validate: validateTools}, @@ -57,23 +57,20 @@ func operationalDefinitions() []Definition { // and the daemon's reconciliation loads new and changed files without a // restart. A removal cannot unload Yaegi's interpreter, so it stays an // outstanding apply-status problem rather than a restart of the whole kind - // (docs/prds/plugin-settings-live.md). {Kind: PluginSettingsKind, Title: "Plugin settings", ApplyMode: "live", Document: pluginSettings{}, Seed: func(cfg config.Config) any { return pluginSettings{cfg.PluginDir, cfg.ModuleDir, cfg.SecretEngineDir, cfg.SkillsDir} }, Validate: validatePluginSettings}, // ApplyMode is live: the container pool reads the published config on // every acquire (image, pull policy, network, max uptime, concurrency // cap) and the daemon resizes its running dispatcher after the publish, - // so neither a deferred container nor a queued task needs a restart - // (archie-core-zfb0.2). RegistryAuth is file-owned and never part of + // so neither a deferred container nor a queued task needs a restart. + // RegistryAuth is file-owned and never part of // this document, so it stays a boot-resolved value. {Kind: ContainerRuntimePoliciesKind, Title: "Container runtime policies", ApplyMode: "live", Document: containerRuntimePolicies{}, Seed: seedContainerPolicies, Validate: validateContainers, Normalize: normalizeContainerPolicies}, } } -// validatePluginSettings accepts every value, deliberately. The four directories -// are free-form operator paths, and that is the decision recorded for -// archie-core #1143 rather than a validator nobody has written yet. +// validatePluginSettings accepts every value, deliberately. // // Two candidate rules were considered and are refused: // @@ -134,7 +131,7 @@ func validateScheduling(input []byte) error { // leaves the file's label in force, which is what legacy policies // decode with), so a stored label-requiring trigger with no label was // a value the store blessed and boot refused -- the two-layer - // disagreement the parity test refuses to allow (archie-core-7pyj). + // disagreement the parity test refuses to allow. if workintake.RequiresLabel(policy.Dispatch.Trigger) && (policy.Label == nil || *policy.Label == "") { return fmt.Errorf("label is required when dispatch.trigger is %q (an empty label matches every open issue)", policy.Dispatch.Trigger) } diff --git a/internal/app/controlplane/registry.go b/internal/app/controlplane/registry.go index 6f428911a..7b09a92c6 100644 --- a/internal/app/controlplane/registry.go +++ b/internal/app/controlplane/registry.go @@ -115,13 +115,10 @@ const ( // the file document's value stays the one in effect (Client.RuntimeConfig // leaves an absent kind alone), with the fix still in the file. The seed is // retried on the next start of this process, so correcting config.toml re-seeds -// it. -// docs/prds/runtime-control-plane.md, "Bootstrap, migration, and recovery": -// after migration, settings in TOML are ignored and cannot block State Store -// startup -- and this import runs on the State Store's startup path. Fail closed -// belongs to the process that uses the value: boot.runtimeConfig validates the -// effective document and refuses to start archied with a value it cannot run -// with, which is what keeps an invalid value from taking effect silently. +// it. Fail closed belongs to the process that uses the value: +// boot.runtimeConfig validates the effective document and refuses to start +// archied with a value it cannot run with, which is what keeps an invalid value +// from taking effect silently. func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[string]int64, []SeedSkip, error) { versions := make(map[string]int64, len(s.ordered)) var skipped []SeedSkip diff --git a/internal/app/controlplane/review_settings.go b/internal/app/controlplane/review_settings.go index 75cb79744..14917efc4 100644 --- a/internal/app/controlplane/review_settings.go +++ b/internal/app/controlplane/review_settings.go @@ -8,7 +8,6 @@ import ( // workflow's two dials: whether a post-worthiness pass runs before findings are // posted, and whether a human approves the draft before it posts. The file's // [review] section seeds it; the stored document outranks the file from then on -// (docs/prds/review-settings-resource.md). const ReviewSettingsKind = "review-settings" type reviewSettings struct { diff --git a/internal/app/controlplane/runtime_config.go b/internal/app/controlplane/runtime_config.go index fd6308910..ae8be4baf 100644 --- a/internal/app/controlplane/runtime_config.go +++ b/internal/app/controlplane/runtime_config.go @@ -34,7 +34,6 @@ import ( // // It also returns the version of each kind it read, so the process that // layers them in can report which version it is running -// (docs/prds/control-plane-apply-status.md). func (c *Client) RuntimeConfig(ctx context.Context, base config.Config) (config.Config, map[string]int64, error) { return runtimeConfigFrom(ctx, c, base) } @@ -116,8 +115,8 @@ func runtimeConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReade // The stored role assignments own cfg.Models once the store carries a // value, the way the provider layer above owns cfg.Providers: a role // removed from the store is gone from the layered document too. The - // runtime-resource watches re-layer over an already-layered base - // (archie-core-zfb0.1), so json.Unmarshal's map merge here would + // runtime-resource watches re-layer over an already-layered base, + // so json.Unmarshal's map merge here would // resurrect a role the store deleted every time any watched kind changed. if err := layerResource(ctx, reader, versions, ModelRoleAssignmentsKind, func(value []byte) error { var roles map[string]string @@ -163,7 +162,7 @@ func runtimeConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReade // review-settings owns the pr-review dials once the store carries a value. // The two fields are assigned individually, not `out.Review = ...`: a field // added to config.Review later keeps the file's value until the stored - // document carries it (docs/prds/review-settings-resource.md). + // document carries it. if err := layerResource(ctx, reader, versions, ReviewSettingsKind, func(value []byte) error { var settings reviewSettings if err := json.Unmarshal(value, &settings); err != nil { diff --git a/internal/app/controlplane/schema.go b/internal/app/controlplane/schema.go index ca28599d2..58d2bf30c 100644 --- a/internal/app/controlplane/schema.go +++ b/internal/app/controlplane/schema.go @@ -11,7 +11,6 @@ import ( // bareObjectSchema is what a descriptor advertises when its definition names no // document. It is the fallback, not the norm: a descriptor with no properties is // what left the Web UI with nothing to label, describe or format a field with -// (archie-core-2xs6). const bareObjectSchema = `{"type":"object"}` var timeType = reflect.TypeFor[time.Time]() diff --git a/internal/app/controlplane/workflow_projector.go b/internal/app/controlplane/workflow_projector.go index 314ab379e..8b41356f6 100644 --- a/internal/app/controlplane/workflow_projector.go +++ b/internal/app/controlplane/workflow_projector.go @@ -24,7 +24,7 @@ const projectWriteAttempts = 3 // WorkflowProjector carries an installed package's workflow contributions // into the org's workflow-definitions resource, the same document an operator -// edits on the dashboard (docs/prds/store.md, "Packages"). The readers the +// edits on the dashboard. The readers the // daemon holds read that resource per dispatch, so a projected workflow is // usable at the next dispatch and a withdrawn one stops dispatching, without // restarting processes. diff --git a/internal/buildinfo/buildinfo.go b/internal/buildinfo/buildinfo.go index beff9a338..0b90773e2 100644 --- a/internal/buildinfo/buildinfo.go +++ b/internal/buildinfo/buildinfo.go @@ -1,7 +1,7 @@ // Package buildinfo carries the release version stamped into every host // binary. The updater asks each installed binary what it is, rather than // trusting one component's word for a whole install whose binaries may have -// been replaced by hand (archie-core-k94o). +// been replaced by hand. package buildinfo import ( diff --git a/internal/channels/email/email.go b/internal/channels/email/email.go index d1437e99a..1ff75c853 100644 --- a/internal/channels/email/email.go +++ b/internal/channels/email/email.go @@ -142,7 +142,6 @@ func (g *Gateway) handleSMTP(ctx context.Context, conn net.Conn) { write(250, "OK: message accepted") return } - // Un-dot-stuff: RFC 5321 §4.5.2 if strings.HasPrefix(line, "..") { line = line[1:] } diff --git a/internal/channels/status/status.go b/internal/channels/status/status.go index 5518951c1..2b97466a1 100644 --- a/internal/channels/status/status.go +++ b/internal/channels/status/status.go @@ -3,7 +3,7 @@ // facts for the dashboard and readiness surfaces. It lives beside the // channels package rather than inside it so UI-process code can hold the // types without linking the plugin contract there -- which references the -// gateway runtime (archie-core-8cda.5.6). +// gateway runtime. package status import "sync" diff --git a/internal/channels/telegram/commands.go b/internal/channels/telegram/commands.go index 3359023af..4bb5d1099 100644 --- a/internal/channels/telegram/commands.go +++ b/internal/channels/telegram/commands.go @@ -29,11 +29,10 @@ var gatewayCommandSpecs = []commandSpec{ {Command: "settings", Description: "Inspect or change runtime settings", Usage: "/settings [list|get |set = ...]"}, {Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] "}, // /approve and /deny are Telegram's own dangerous-command approval surface: - // dangerous.go lists the pending commands and the inline buttons decide. The - // shared command specs use /approve for task approval instead, and Telegram's - // exact-match handler shadows that path, so /help must describe the Telegram - // meaning. Reconciling the split is archie-core-ho86; do not copy the shared - // task-approval copy here. + // dangerous.go lists the pending commands and the inline buttons decide. + // The shared command specs use /approve for task approval instead, and + // Telegram's exact-match handler shadows that path, so /help must describe + // the Telegram meaning. {Command: "approve", Description: "Show pending dangerous commands to approve", Usage: "/approve"}, {Command: "deny", Description: "Show pending dangerous commands to deny", Usage: "/deny"}, {Command: "start", Description: "Confirm that Archie is running", Usage: "/start"}, diff --git a/internal/channels/telegram/live.go b/internal/channels/telegram/live.go index 7eb912406..304d84183 100644 --- a/internal/channels/telegram/live.go +++ b/internal/channels/telegram/live.go @@ -84,12 +84,6 @@ type liveReply struct { // interval throttles updates; zero renders every change. interval time.Duration - // mediaWg lets tests (and a future bounded drain, mirroring - // abandonAllLive) wait for in-flight Media deliveries. Callers other - // than tests must not block on it: Media is fire-and-forget by - // contract, same as Delta and ToolCall. - mediaWg sync.WaitGroup - // newMediaSender builds the MediaSender Media delivers through. // Defaults to g.NewMediaSender; tests override it to inject a sender // with fixed Capabilities(), which the real Telegram one can't @@ -414,7 +408,7 @@ func (l *liveReply) Media(ctx context.Context, event messaging.MediaEvent) { return } - l.mediaWg.Go(func() { + go func() { sender := l.newMediaSender(l.b, l.chatID, l.messageThreadID) // Checked before attempting delivery, not just on failure: that is @@ -441,7 +435,7 @@ func (l *liveReply) Media(ctx context.Context, event messaging.MediaEvent) { l.g.log.Warn("media delivery failed, falling back to a link", "tool", event.ToolName, "type", event.Attachment.Type, "error", err) l.appendFallbackLine(ctx, event.Attachment) - }) + }() } // appendFallbackLine renders att as a visible link in the reply, for a @@ -478,13 +472,6 @@ func (l *liveReply) appendFallbackLine(ctx context.Context, att messaging.MediaA l.requestRender() } -// waitMedia blocks until every Media delivery started so far has finished. -// Tests only: production callers never wait on Media's fire-and-forget -// goroutines. -func (l *liveReply) waitMedia() { - l.mediaWg.Wait() -} - // render writes the current buffer, cursor and all, to the live message. func (l *liveReply) render(ctx context.Context) { l.mu.Lock() diff --git a/internal/channels/telegram/richblocks.go b/internal/channels/telegram/richblocks.go index e91713f6c..bea711566 100644 --- a/internal/channels/telegram/richblocks.go +++ b/internal/channels/telegram/richblocks.go @@ -115,12 +115,10 @@ func stripInlineMarkdown(s string) string { } // stripEmphasis removes paired emphasis delimiters and keeps their content. -// Pairing follows CommonMark's flanking rules, so a delimiter that cannot -// open or close is ordinary text and stays put. That is what keeps this -// project's own vocabulary intact over the wire: snake_case config keys, -// dotted paths like config_schema_test.go, and Go pointer types such as +// Pairing follows CommonMark's flanking rules, so a delimiter that cannot open +// or close is ordinary text and stays put. // *sql.Tx all used to lose characters to a non-greedy `_(.+?)_` that paired -// any two markers on a line (archie-core-8x1r). +// any two markers on a line. func stripEmphasis(s, marker string) string { var b strings.Builder for i := 0; i < len(s); { @@ -277,7 +275,7 @@ func (p *markdownBlockParser) handleLine(line string) { case p.startsIndentedCode(line): // CommonMark's other code form. Models emit it constantly, and // without this it fell to the paragraph case below, which - // space-joins its lines into one run-on line (archie-core-cvu6). + // space-joins its lines into one run-on line. p.flush() p.inCode, p.indented, p.codeLang = true, true, "" p.codeLines = []string{stripCodeIndent(line)} @@ -300,7 +298,7 @@ func (p *markdownBlockParser) handleLine(line string) { // said it is a line, so it closes its own block and the next one // hugs it. Line-oriented reports (/status, /tasks) depend on this; // without it every one of their lines soft-joined into one run-on - // paragraph (archie-core-8cda.6.10). + // paragraph. p.flushList() p.flushQuote() switch { @@ -488,7 +486,7 @@ func (p *markdownBlockParser) flushQuote() { // closeCode emits the open code block. The text is passed through verbatim: // code is not prose, and running the emphasis stripper over it turned -// *sql.Tx into sql.Tx and ate same-line snake_case pairs (archie-core-8x1r). +// *sql.Tx into sql.Tx and ate same-line snake_case pairs. func (p *markdownBlockParser) closeCode() { lines := p.codeLines if p.indented { diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index 3cad3a89c..f1206fa2b 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -281,11 +281,7 @@ type telegramTextHandler struct { } // telegramTextHandlers is the single source for the commands Telegram answers -// locally. Registration reads it, and so does -// TestPublishedCommandsMatchExecutableSurface, which proves the published menu -// covers the executable surface: a handler added here without a spec in -// gatewayCommandSpecs fails that test, so a command cannot become typeable -// without becoming discoverable. +// locally. var telegramTextHandlers = []telegramTextHandler{ {"/status", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.statusHandler(c) }}, {"/whoami", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.whoamiHandler(c) }}, diff --git a/internal/channels/webhook/webhook.go b/internal/channels/webhook/webhook.go index 002c1df83..ff6415fbf 100644 --- a/internal/channels/webhook/webhook.go +++ b/internal/channels/webhook/webhook.go @@ -178,7 +178,6 @@ func (g *Gateway) handleWebhook(route *RouteConfig) http.HandlerFunc { // empty: consumers read it as a person // (internal/app/archied/chat_identity.go, sessioncurator), // and a route path must never become a user identity - // (docs/prds/memory-engine-unification.md criterion 7). Role: messaging.RoleUser, Text: text, }, @@ -200,7 +199,7 @@ func (g *Gateway) handleWebhook(route *RouteConfig) http.HandlerFunc { // (chat prose, meant for a human) or 202'd as accepted (indistinguishable // from a delivered event, so the source would never retry it). 429 lets // the source back off and retry, the way internal/webhookguard.RateLimiter's - // other callers already respond (archie-core-1173). + // other callers already respond. if reply.RateLimited { http.Error(w, "rate limited", http.StatusTooManyRequests) return diff --git a/internal/config/chat_frontends.go b/internal/config/chat_frontends.go index 846ab4d87..04bddec1a 100644 --- a/internal/config/chat_frontends.go +++ b/internal/config/chat_frontends.go @@ -23,8 +23,8 @@ type ChatFrontEnd struct { // two answers drifted: the daemon's channel status manager counted the inbound // mail gateway, and the dashboard projection published for the extracted UI // process did not, so an email-only deployment read as configured on -// /api/channels and unconfigured on the setup checklist at the same time -// (GitHub #821). Front-ends are enumerated once here so a front-end added to +// /api/channels and unconfigured on the setup checklist at the same time. +// Front-ends are enumerated once here so a front-end added to // [chat] cannot be counted by one surface and missed by the other. // // A whitespace-only value is not configured on any front-end: an env var name diff --git a/internal/config/config.go b/internal/config/config.go index 49788524a..aa4c43c24 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -8,10 +8,7 @@ // The forge API token is deliberately not part of the file: it comes from a // configurable env var. // -// Per docs/architecture/configuration.md this package is scheduled for -// dissolution: its types and methods are to be reassigned to the domains -// whose behaviour they describe. Do not add new fields here that a single -// domain could own. +// Do not add new fields here that a single domain could own. package config import ( @@ -130,8 +127,6 @@ func (r Repo) ResolvedPreflight() [][]string { } // ResolvedTestGlob returns the test-file glob pattern for this repo. -// Explicit TestGlob wins; otherwise the ecosystem default; empty -// for unknown ecosystems and "custom" (protection no-ops). func (r Repo) ResolvedTestGlob() string { if r.TestGlob != "" { return r.TestGlob @@ -203,15 +198,12 @@ type Forge struct { WebhookAddr string `toml:"webhook_addr" yaml:"webhook_addr"` } -// Review configures the pr-review workflow (docs/prds/pr-review-agent.md). +// Review configures the pr-review workflow. // Both fields are off by default: the pipeline is recall-first, and posts // automatically, unless an operator opts into either dial. type Review struct { - // PrecisionGate runs a post-worthiness pass after phase 4 (review) and - // before phase 5 (verification): it keeps every concrete, evidenced - // defect, drops nitpicks, style and unverifiable claims, and keeps a - // finding when unsure. It trades recall for precision and cuts - // verification cost by filtering early. + // It trades recall for precision and cuts verification cost by filtering + // early. PrecisionGate bool `toml:"precision_gate" yaml:"precision_gate"` // ApproveBeforePost ends the pipeline in waiting_human right after // synthesis, before the merge gate runs, so an operator can choose which @@ -395,36 +387,29 @@ type Config struct { Services Services `toml:"services" yaml:"services"` WorkDir string `toml:"work_dir" yaml:"work_dir"` // SkillsDir is an optional path to a shared skills directory - // containing .agents/skills/*/SKILL.md files. When set, the + // containing */SKILL.md files. When set, the // daemon builds its workflow registry from the skill catalog // (plugin-defined workflows override built-ins). When empty, // only built-in workflows are available. Its skills are also the // store a Kit's agent-skills@1 mounts, read-only, into the harness. SkillsDir string `toml:"skills_dir" yaml:"skills_dir"` - // WorkflowRoutingFile is an optional path to a YAML file rebinding - // which registered workflow an intake Kind (bug/feature/bootstrap) - // prefers -- see docs/prds/eda-playbook-engine.md. When empty, the - // built-in bindings (bug->tdd, feature->feasibility, - // bootstrap->bootstrap) are used unchanged. + // WorkflowRoutingFile is an optional path to a YAML file rebinding which + // registered workflow an intake Kind (bug/feature/bootstrap) prefers. WorkflowRoutingFile string `toml:"workflow_routing_file" yaml:"workflow_routing_file"` - // WorkflowLabelsFile is an optional path to a YAML file binding forge - // issue labels outside the closed bug/feature/bootstrap kind set to - // registered workflows (e.g. "security" -> "security-review") -- the - // second slice of docs/prds/eda-playbook-engine.md. When empty, only - // the kind layer routes by label. A label already owned by the kind - // set, or a duplicate binding, is a load failure per the design doc's - // collision rule. + // WorkflowLabelsFile is an optional path to a YAML file binding forge issue + // labels outside the closed bug/feature/bootstrap kind set to registered + // workflows (e.g. A label already owned by the kind 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 is an optional list of directories of *.yaml/*.yml binding + // files loaded at startup. 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"` // EDAPlaybookDir is an optional path to a directory of rich EDA playbook // documents (*.yaml/*.yml: trigger + ordered actions with CEL `when` @@ -469,19 +454,17 @@ type Config struct { // Label marks issues archie should pick up. Label string `toml:"label" yaml:"label"` BotUser string `toml:"bot_user" yaml:"bot_user"` - // Org is this identity's org (docs/prds/orgs-and-access.md). Empty means + // Org is this identity's org. Empty means // "default": the org a single-operator install's one identity belongs to. // A credential binding whose Org does not match a run's identity never // resolves for it, regardless of what the identity is granted. Org string `toml:"org" yaml:"org"` - // GrantedCredentials names the credential@1 services this identity may - // use, by CredentialBinding.Service (docs/prds/external-agent-harness.md, - // Organisations: "a harness run ... acts as the workflow's identity"). - // Empty grants none -- a binding existing is not a grant, the same - // fail-closed default the proxy itself already applies to an unbound - // required credential. Declared (what a Kit's descriptor asks for) and - // granted (this list) are two separate facts; only their intersection - // resolves, and neither widens the other. + // GrantedCredentials names the credential@1 services this identity may use, + // by CredentialBinding.Service. Empty grants none -- a binding existing is + // not a grant, the same fail-closed default the proxy itself already + // applies to an unbound required credential. Declared (what a Kit's + // descriptor asks for) and granted (this list) are two separate facts; only + // their intersection resolves, and neither widens the other. GrantedCredentials []string `toml:"granted_credentials" yaml:"granted_credentials"` // BotEmail is the git author email; defaults to the GitHub noreply // address for BotUser. @@ -816,7 +799,7 @@ const ( // // An empty Mode resolves from URL: URL set means "external", URL empty means // "embedded". Autonomous workflow handoff always uses NATS; there is no -// broker-off execution mode (docs/prds/embedded-nats.md). +// broker-off execution mode. type NATSConfig struct { // Mode selects embedded or external. Empty resolves from URL. Mode string `toml:"mode" yaml:"mode"` @@ -828,8 +811,8 @@ type NATSConfig struct { TokenEnv string `toml:"token_env" yaml:"token_env"` } -// CaptureConfig configures the unbound webhook capture endpoint -// (docs/prds/event-capture-storage.md). All fields have defaults; an empty +// CaptureConfig configures the unbound webhook capture endpoint. +// All fields have defaults; an empty // [capture] section is valid and produces them -- capture is on by default. type CaptureConfig struct { // Retention is how long a captured event is kept before prune-on-write @@ -844,12 +827,11 @@ type CaptureConfig struct { // MaxBodyBytes rejects (413) any single POST body larger than this // before it is read into memory. Zero means the 256 KiB default. MaxBodyBytes int `toml:"max_body_bytes" yaml:"max_body_bytes"` - // RatePerSecond and RateBurst configure the per-remote-address token - // bucket (webhookguard.RateLimiter) applied before a request's body is - // read. Keyed by remote address, not the source path segment, since - // that segment is unregistered and attacker-chosen by design -- see - // docs/prds/event-capture-storage.md's disk-bound mechanics. Zero means - // the defaults (1 req/s, burst 5). + // RatePerSecond and RateBurst configure the per-remote-address token bucket + // (webhookguard.RateLimiter) applied before a request's body is read. Keyed + // by remote address, not the source path segment, since that segment is + // unregistered and attacker-chosen by design. Zero means the defaults (1 + // req/s, burst 5). RatePerSecond float64 `toml:"rate_per_second" yaml:"rate_per_second"` RateBurst int `toml:"rate_burst" yaml:"rate_burst"` } @@ -857,7 +839,6 @@ type CaptureConfig struct { // BindingsConfig configures the playbook-binding store (t2db). When // EncryptionKey is unset, binding secrets are persisted as plaintext // (legacy behaviour); when set, they are AES-256-GCM encrypted at rest -// (see docs/prds/binding-secret-encryption.md). type BindingsConfig struct { // EncryptionKey is the active key that seals new binding secrets. // Resolved through the secret registry (engine + key) at startup; the @@ -899,8 +880,8 @@ type ContainerConfig struct { // AgentProfileKind, seeded from this field but validated and stored // (and reloaded live) separately -- see internal/app/controlplane. Profiles map[string]AgentProfile `toml:"profiles" yaml:"profiles" json:"-"` - // Credentials binds a Kit's credential@1 service names to org secrets - // (docs/prds/external-agent-harness.md, Credentials). A binding names + // Credentials binds a Kit's credential@1 service names to org secrets. + // A binding names // where the value comes from; it is not itself a grant -- an identity // resolves a bound service only when its own Org matches and the service // is in its GrantedCredentials. @@ -926,18 +907,13 @@ type ContainerConfig struct { } // CredentialBinding maps one Kit credential@1 service name to an org secret. -// It carries no secret value itself, only where to resolve one from: the -// existing secret registry (env/file), not yet the encrypted org-secret -// store docs/prds/binding-secret-encryption.md describes -- that store is -// separate, still-open work this does not attempt. type CredentialBinding struct { // Service names the credential@1 service a Kit's descriptor declares // (docker/sandbox-kit-spec spec.CredentialCapability.Service). Service string `toml:"service" yaml:"service"` - // Org is the org this binding belongs to. Empty means the default org. - // A run whose identity's Org does not match never resolves this binding, - // however it is granted (docs/prds/orgs-and-access.md: "No record is - // shared between orgs"). + // Org is the org this binding belongs to. Empty means the default org. A + // run whose identity's Org does not match never resolves this binding, + // however it is granted. Org string `toml:"org" yaml:"org"` // Secret is where an API key's real value is resolved from. A service // the Kit declares OAuth-managed leaves it empty: its tokens are the @@ -991,8 +967,8 @@ func (c ContainerConfig) ValidateCredentialBindings() error { } // AgentProfile is a named execution environment for an agent. Secrets and -// forge or network access are granted to identities, not profiles -// (docs/prds/orgs-and-access.md). A workflow's profile name is not checked +// forge or network access are granted to identities, not profiles. +// A workflow's profile name is not checked // when the workflow is saved: a name with no profile here parks the task for // an operator when it is dispatched (daemon pinTaskProfile). type AgentProfile struct { @@ -1089,9 +1065,8 @@ type Log struct { Quiet bool `toml:"quiet" yaml:"quiet"` } -// ChatConfig configures conversational front-ends (multi-agent -// collaboration PRD, phase C -- docs/prds/multi-agent-collaboration.md). -// Empty (Telegram.Token.Key == "") disables chat entirely. +// ChatConfig configures conversational front-ends. Empty (Telegram.Token.Key == +// "") disables chat entirely. type ChatConfig struct { // Operator is the display name of the person this deployment assists, // shown to the chat agent as runtime metadata. Empty tells it nothing. @@ -1184,9 +1159,8 @@ type ChatConfig struct { // A sender is identified per channel: Telegram by numeric user ID, email by the // SMTP from address, webhook by the configured route path -- which is a source, // not a person, so it reaches the limiter through the transport-only -// Inbound.BudgetKey rather than through SenderID (see -// docs/prds/memory-engine-unification.md §3). Disabled unless both fields are -// set to a positive value. +// Inbound.BudgetKey rather than through SenderID. Disabled unless both fields +// are set to a positive value. type RateLimitConfig struct { // Window is the rolling interval MaxRequests is budgeted over. Window time.Duration `toml:"window" yaml:"window"` @@ -1254,17 +1228,12 @@ type WebhookRoute struct { // Notify configures outbound notifications (n8n webhook → email etc.). type Notify struct { - // Webhook receives JSON POSTs for events that need a human (e.g. - // feasibility PRDs awaiting go/no-go). Empty disables. + // Webhook receives JSON POSTs for events that need a human. Empty disables. Webhook string `toml:"webhook" json:"webhook" yaml:"webhook"` } -// Web configures the observability dashboard. -// Health is archied's own liveness surface, always on. It is separate from -// the dashboard's /healthz because the process whose restart is being -// verified has to be the one answering: the dashboard can be switched off, -// and it becomes its own process in Phase 3, at which point probing it would -// report health for something the update watchdog never restarted. +// Web configures the observability dashboard. Health is archied's own liveness +// surface, always on. type Health struct { // Listen is the address the daemon serves /healthz, /health and // /health/detailed on. Defaulted, never empty in a loaded config. diff --git a/internal/config/secret_ref.go b/internal/config/secret_ref.go index cb9368cc0..b9893b305 100644 --- a/internal/config/secret_ref.go +++ b/internal/config/secret_ref.go @@ -17,7 +17,6 @@ package config // // It lives here rather than in internal/secret so the archie-ui process can // render config projections without linking the secret runtime -// (archie-core-8cda.5.6). type SecretRef struct { Engine string `toml:"engine" yaml:"engine" json:"engine"` Key string `toml:"key" yaml:"key" json:"key"` diff --git a/internal/config/services.go b/internal/config/services.go index eda25ffb2..afca6ed23 100644 --- a/internal/config/services.go +++ b/internal/config/services.go @@ -74,6 +74,6 @@ type ServiceConnection struct { // when dialing a non-loopback service target, and the standalone // archie-state-store server validates. Empty means no token, which is // the loopback-only, daemon-only listener topology permitted without - // auth (docs/prds/state-store-contract.md §9). + // auth. TargetToken string `toml:"target_token" yaml:"target_token"` } diff --git a/internal/container/pool.go b/internal/container/pool.go index 6e3650864..7a0c4deae 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -37,7 +37,7 @@ type Container struct { func (c *Container) Exited() <-chan struct{} { return c.exited } // TaskPayload is the boot-time brief written to /data/worktree/.git/task.json -// before the container starts, per PRD section 3. +// before the container starts. type TaskPayload struct { ID int64 `json:"id"` Owner string `json:"owner"` @@ -138,11 +138,11 @@ type Config struct { Image string MaxConcurrency int // MaxUptime is the total container lifetime cap from creation. When - // exceeded, the container is killed regardless of task state. PRD §4. + // exceeded, the container is killed regardless of task state. MaxUptime time.Duration - // GracePeriod is the idle time after task completion before the - // container is killed. The agent stays alive to handle follow-ups - // (gate re-runs, human replies) during this window. PRD §1. + // GracePeriod is the idle time after task completion before the container + // is killed. The agent stays alive to handle follow-ups (gate re-runs, + // human replies) during this window. GracePeriod time.Duration PullPolicy string // RegistryAuth is the resolved value of [containers].registry_auth: either @@ -516,10 +516,10 @@ func releaseDecision(ctx context.Context, grace time.Duration) (honorGrace bool, return grace > 0, nil } -// Release stops and removes a container after a task completes. If -// GracePeriod is configured, the container stays alive for that duration -// before being killed -- the agent can handle follow-ups (gate re-runs, -// human replies) during this window. PRD section 1. +// Release stops and removes a container after a task completes. If GracePeriod +// is configured, the container stays alive for that duration before being +// killed -- the agent can handle follow-ups (gate re-runs, human replies) +// during this window. func (p *Pool) Release(ctx context.Context, c *Container) { if c == nil { return diff --git a/internal/daemon/agent_status.go b/internal/daemon/agent_status.go index 6db4c8363..72d6c6334 100644 --- a/internal/daemon/agent_status.go +++ b/internal/daemon/agent_status.go @@ -2,12 +2,11 @@ package daemon import "sync" -// AgentStatus tracks the most recent version and install type an -// archie-agent worker reported about itself. It is observed passively, off -// ordinary taskrun.Response traffic in runViaAgent -- there is no dedicated -// poll, since every archie-agent process is task-scoped and ephemeral (see -// docs/architecture and internal/app/agentworker), not a long-lived process -// the daemon could query on demand the way it can Telegram's gateway. +// AgentStatus tracks the most recent version and install type an archie-agent +// worker reported about itself. It is observed passively, off ordinary +// taskrun.Response traffic in runViaAgent -- there is no dedicated poll, since +// every archie-agent process is task-scoped and ephemeral, not a long-lived +// process the daemon could query on demand the way it can Telegram's gateway. // // Before the first task completes, nothing is known: Snapshot's ok return // reports that honestly rather than a caller guessing a value. diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index e4fa1f714..fff4e1447 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -80,9 +80,9 @@ type NATSEndpoint struct { // StateStoreEndpoint is the State Store gRPC target (and the bearer token the // daemon presents, when one is configured) that containerEnv injects as // STATE_STORE_URL / STATE_STORE_TOKEN so archie-agent authenticates to the -// same remote archie-state-store service the daemon dials -// (docs/prds/state-store-contract.md §6, §9, §10). After the in-process -// serving path is deleted (docs/prds/state-store-contract.md §12 step 7) this +// same remote archie-state-store service the daemon dials. +// After the in-process +// serving path is deleted this // is always the configured [services.state].target, never a daemon-owned // listener. type StateStoreEndpoint struct { @@ -107,12 +107,12 @@ type Daemon struct { // [services.state].target after the in-process serving path is deleted. ConnectedStateStore StateStoreEndpoint Store storecontract.TaskStore - // Mappings persists payload field mappings (docs/prds/payload-field-mapping.md). + // Mappings persists payload field mappings. // Used by the binding dispatch loop to resolve capture bodies against // the mapping a binding names. Optional: nil disables the binding // dispatch loop (legacy behaviour). Mappings storecontract.MappingStore - // Bindings persists playbook bindings (docs/prds/playbook-binding.md). + // Bindings persists playbook bindings. // Optional: nil disables the binding dispatch loop (legacy behaviour). Bindings storecontract.BindingStore // BindingDispatcher is the dispatch-time helper surface for bindings: @@ -130,9 +130,8 @@ type Daemon struct { // Optional: nil disables the dispatch loop. BindingTaskCreator storecontract.BindingTaskCreator // Access evaluates the policy chain at dispatch, the second of the two - // Authorizer call sites (docs/prds/orgs-and-access.md, "Where it - // lives"): the workflow's identity may `run` the workflow in its - // workspace. Optional: nil dispatches without the chain, which is the + // Authorizer call sites: the workflow's identity may `run` the workflow in + // its workspace. Optional: nil dispatches without the chain, which is the // behaviour of an install that has not built it. Access access.Authorizer // Principals assembles the dispatch principal for the workflow's @@ -156,8 +155,8 @@ type Daemon struct { // reactionPublisher is built lazily by scanPRReviews; an indirection // only so tests can swap the delivery without the bus. reactionPublisher ReactionPublisher - // Reactions pulls the review-reaction fan-out stream - // (docs/prds/pr-review-remediation.md). Each cycle it is drained into + // Reactions pulls the review-reaction fan-out stream. + // Each cycle it is drained into // queued remediate runs before the task drain, so a reaction can be // claimed in the same pass that carried it. Optional: nil disables the // reaction consumer (tests, or a deployment without the reaction @@ -743,9 +742,8 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st return } // The chain decides dispatch: the workflow's identity may `run` this - // workflow in its workspace, and the event's signature result and - // address travel with the request (docs/prds/orgs-and-access.md, - // "Access decisions"). A denial is recorded and the dispatch is not + // workflow in its workspace, and the event's signature result and address + // travel with the request. A denial is recorded and the dispatch is not // claimed: the capture stays listed for the next cycle. if !d.authorizeDispatch(ctx, b, c, target) { return @@ -755,7 +753,7 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st // claimAndEnqueue claims the dispatch in the at-most-once ledger and enqueues // the task. A failed enqueue after the claim loses that dispatch, which is -// the at-most-once side of the trade (docs/prds/playbook-binding.md). +// the at-most-once side of the trade. func (d *Daemon) claimAndEnqueue(ctx context.Context, b binding.Binding, c storecontract.CapturedEvent, target bindingTarget, values map[string]any) { if err := d.BindingDispatcher.RecordDispatch(ctx, b.ID, int64(b.Version), c.ID, 0); err != nil { if !errors.Is(err, storecontract.ErrAlreadyDispatched) { @@ -1171,8 +1169,7 @@ func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, cfg config.Config // issue on a later poll does not enqueue the work twice. It is the single // enqueue path shared by the poller and the forge webhook intake, so neither // can drift in how a discovered issue becomes a task -- including the org the -// key is built from (docs/prds/orgs-and-access.md, "Events and task -// identity"). +// key is built from. func (d *Daemon) PublishTask(ctx context.Context, task workintake.TaskEnvelope) error { if d.Tasks == nil { return fmt.Errorf("publish task %s: no task bus configured", task.Ref()) @@ -1675,11 +1672,10 @@ func (d *Daemon) acquireTaskContainer( } // pr-review needs an external pull request's metadata, diff and head - // snapshot inside the container, but the container must never hold a - // forge credential (docs/development/agent.md, "Giving the agent - // something new"). The daemon fetches it here, before the container - // exists, using its own credentialed forge client, and writes the result - // into workDir -- the same host directory Docker bind-mounts at + // snapshot inside the container, but the container must never hold a forge + // credential. The daemon fetches it here, before the container exists, + // using its own credentialed forge client, and writes the result into + // workDir -- the same host directory Docker bind-mounts at // storage.WorktreeMountDir -- so the sandboxed pipeline can read it back // with prsource.MountSource and no network call of its own. if task.Workflow == "pr-review" { @@ -1943,12 +1939,12 @@ func (d *Daemon) pinTaskProfile(ctx context.Context, task *workflow.Task) (confi } // validateProfileMeetsNeeds rejects a Kit profile whose harness cannot meet -// what the workflow declares it needs (docs/prds/external-agent-harness.md, -// "Contract"): a workflow needing captures but naming a profile whose Kit CLI -// serves none (no adapter, or one with no MCP config to register archie-agent -// mcp against -- e.g. Codex, Pi, OMP per agentexec.harnessAdapters). An image -// profile is never checked: the built-in agent loop always supports both -// captures and gate retries, so Needs constrains only the harness path. +// what the workflow declares it needs: a workflow needing captures but naming a +// profile whose Kit CLI serves none (no adapter, or one with no MCP config to +// register archie-agent mcp against -- e.g. Codex, Pi, OMP per +// agentexec.harnessAdapters). An image profile is never checked: the built-in +// agent loop always supports both captures and gate retries, so Needs +// constrains only the harness path. func validateProfileMeetsNeeds(profile config.AgentProfile, needs workflowtask.WorkflowNeeds) error { if !profile.IsKit() || !needs.Captures { return nil @@ -2067,7 +2063,7 @@ func pinnedDefinitionID(task *workflow.Task) (string, bool, error) { } // runActionPlaybooks runs the action playbooks matching a task that is about -// to be pinned, which happens once per task (docs/prds/action-playbook-run.md). +// to be pinned, which happens once per task. // A run never affects routing and its failure never fails the task. A task // that already names a workflow is the approval requeue and is skipped, as // it is for workflow playbooks. @@ -2223,7 +2219,7 @@ func (d *Daemon) containerEnv(task *workflow.Task, stateStoreToken string) []str env = append(env, "NATS_TOKEN="+token) } // The State Store gRPC target follows the same seam as NATS_URL/ - // NATS_TOKEN above (docs/prds/state-store-contract.md §6). It is always + // NATS_TOKEN above. It is always // the configured [services.state].target after the in-process serving // path is deleted. stateStoreToken is this task's own scoped credential // (see stateStoreGrantToken) -- never d.ConnectedStateStore.Token, which @@ -2235,13 +2231,9 @@ func (d *Daemon) containerEnv(task *workflow.Task, stateStoreToken string) []str env = append(env, "STATE_STORE_TOKEN="+stateStoreToken) } } - // The agent process runs as root inside the container (no USER in the - // Dockerfile, no userns-remap), so a commit it writes to the bind-mounted - // worktree lands owned by UID 0 on the host. The daemon then reads those - // same loose objects to push, running as its own non-root host user -- - // archie-core#520's "permission denied" on .git/objects. Passing the - // daemon's own UID/GID lets the agent chown the worktree back to it - // before pushing. + // The agent runs as root in the container, so its commits land owned by + // UID 0 on the host. The daemon's UID/GID let the agent hand the worktree + // back before the daemon reads it to push. env = append(env, fmt.Sprintf("WORKTREE_UID=%d", os.Getuid())) env = append(env, fmt.Sprintf("WORKTREE_GID=%d", os.Getgid())) for _, p := range d.configFor(task).Providers { diff --git a/internal/daemon/pr_review_prefetch.go b/internal/daemon/pr_review_prefetch.go index e4b306d6e..1b943f500 100644 --- a/internal/daemon/pr_review_prefetch.go +++ b/internal/daemon/pr_review_prefetch.go @@ -14,14 +14,12 @@ import ( ) // prefetchPRReview fetches a pull request's metadata, diff and head snapshot -// over f (the daemon's own forge client, which holds the real credential) -// and writes them under workDir/prReviewPrefetchDir, before the task's -// container is acquired. This is how pr-review gets its data into the -// sandbox with no forge credential ever entering the container: the daemon -// does the real HTTP fetch here, unsandboxed, and the container-side -// prsource.MountSource only ever reads the result off the bind-mounted disk -// (docs/development/agent.md, "Giving the agent something new": "the -// daemon's own administrative token never enters a container"). +// over f (the daemon's own forge client, which holds the real credential) and +// writes them under workDir/prReviewPrefetchDir, before the task's container is +// acquired. This is how pr-review gets its data into the sandbox with no forge +// credential ever entering the container: the daemon does the real HTTP fetch +// here, unsandboxed, and the container-side prsource.MountSource only ever +// reads the result off the bind-mounted disk. func prefetchPRReview(ctx context.Context, f any, owner, repo string, number int, workDir string) error { prReader, ok := f.(forge.PullRequestReader) if !ok { diff --git a/internal/daemon/reactions.go b/internal/daemon/reactions.go index f2e9500b6..00f5b3d90 100644 --- a/internal/daemon/reactions.go +++ b/internal/daemon/reactions.go @@ -34,12 +34,8 @@ var remediableReviewStates = map[string]bool{ "commented": true, } -// reactionConsumer turns forge review reactions on Archie-owned PRs into -// queued remediate runs. It implements the consumer half of -// docs/prds/pr-review-remediation.md decisions 3 and 5: resolve the PR to -// the task that owns it (the authorization boundary), never react to -// Archie's own comments, collect a review's comments into one unit while it -// is pending, and rely on the guarded store transition for dedup. +// reactionConsumer turns forge review reactions on Archie-owned PRs into queued +// remediate runs. type reactionConsumer struct { lookup workintake.ReviewTaskLookup remediations storecontract.RemediationStarter diff --git a/internal/domain/access/access.go b/internal/domain/access/access.go index 73f22c6a1..050c46f1e 100644 --- a/internal/domain/access/access.go +++ b/internal/domain/access/access.go @@ -1,6 +1,6 @@ // Package access owns the policy schema, the action vocabulary, how // principals and resources are turned into policy entities, and the -// Authorizer contract (docs/prds/orgs-and-access.md). +// Authorizer contract. // // The policy chain is // diff --git a/internal/domain/access/authorizer.go b/internal/domain/access/authorizer.go index 708696369..2fedaac13 100644 --- a/internal/domain/access/authorizer.go +++ b/internal/domain/access/authorizer.go @@ -6,7 +6,7 @@ package access import "context" // Authorizer evaluates the policy chain for one request. Exactly two places -// call it (docs/prds/orgs-and-access.md, "Where it lives"): the dashboard and +// call it: the dashboard and // API request path, and dispatch. The implementation is the Cedar engine in // internal/infrastructure/access. // diff --git a/internal/domain/access/request.go b/internal/domain/access/request.go index a5f2ee23f..a2ea1ff13 100644 --- a/internal/domain/access/request.go +++ b/internal/domain/access/request.go @@ -141,7 +141,7 @@ type PrincipalSource interface { } // Denial is one recorded refusal: who was refused, doing what, to what, by -// which level and which policies (docs/prds/orgs-and-access.md, "Denials"). +// which level and which policies. type Denial struct { Principal identity.IdentityID `json:"principal"` Org org.OrgID `json:"org"` diff --git a/internal/domain/access/roles.go b/internal/domain/access/roles.go index 2b5497de1..1543affd1 100644 --- a/internal/domain/access/roles.go +++ b/internal/domain/access/roles.go @@ -1,6 +1,5 @@ // The shipped policies: the four org roles every org carries, and the // cross-org forbid the engine always enforces -// (docs/prds/orgs-and-access.md, "The policy chain" and "Roles"). // // The role policies are Cedar policy text because that is what the engine // evaluates. They live in the domain so the store seeds them, the reset diff --git a/internal/domain/access/store.go b/internal/domain/access/store.go index a4fb9c844..82816fbd5 100644 --- a/internal/domain/access/store.go +++ b/internal/domain/access/store.go @@ -28,8 +28,8 @@ type PolicyStore interface { EnsureShippedOrgPolicies(ctx context.Context, orgID org.OrgID) error } -// Resetter restores access for a locked-out org or a broken instance policy -// (docs/prds/orgs-and-access.md, "Recovering from a locked-out org"). It +// Resetter restores access for a locked-out org or a broken instance policy. +// It // runs only on the State Store host, never over the network, and the reset // command records it as an audit event. type Resetter interface { diff --git a/internal/domain/applystatus/applystatus.go b/internal/domain/applystatus/applystatus.go index aa30cf604..1b0cb5c30 100644 --- a/internal/domain/applystatus/applystatus.go +++ b/internal/domain/applystatus/applystatus.go @@ -1,5 +1,5 @@ // Package applystatus reports which version of a control-plane resource each -// process is running. See docs/prds/control-plane-apply-status.md. +// process is running. package applystatus import ( diff --git a/internal/domain/binding/binding.go b/internal/domain/binding/binding.go index 1bc902614..379180423 100644 --- a/internal/domain/binding/binding.go +++ b/internal/domain/binding/binding.go @@ -1,7 +1,6 @@ -// Package binding owns the playbook binding vocabulary: the matcher + -// mapping + workflow + state-machine entity that turns a captured webhook -// into an archie task. See docs/prds/webhook-intake-security.md and -// docs/prds/payload-field-mapping.md. +// Package binding owns the playbook binding vocabulary: the matcher + mapping + +// workflow + state-machine entity that turns a captured webhook into an archie +// task. package binding import ( diff --git a/internal/domain/curator/activity.go b/internal/domain/curator/activity.go index 17f63cf31..c105e76b4 100644 --- a/internal/domain/curator/activity.go +++ b/internal/domain/curator/activity.go @@ -8,7 +8,7 @@ import ( // maxRecentActions bounds how much per-curator history activityTracker // keeps in memory. Curator activity is inspectable, not archival -- there is -// deliberately no persistence layer here (archie-core-1786637489932-6), +// deliberately no persistence layer here, // so this is a ring buffer, not a log. const maxRecentActions = 20 diff --git a/internal/domain/curator/contract.go b/internal/domain/curator/contract.go index 0668a12f1..e8c364518 100644 --- a/internal/domain/curator/contract.go +++ b/internal/domain/curator/contract.go @@ -1,6 +1,6 @@ // Package curator is the curator engine family: long-running agent loops // that reason over memory and perform small maintenance tasks, rather than -// one hardcoded background job. See epic archie-core-yp9. +// one hardcoded background job.. // // A curator is defined by a declared shape (check-in interval, tool set, // attached memory engine), runs persistently while there is input, and backs @@ -46,23 +46,22 @@ type Manifest struct { // OnInput marks the curator as input-driven: primary input (e.g. a // completed chat turn) wakes it before the next interval. Wake events // are best-effort nudges; the trigger decision is a deterministic - // state read at pass time (archie-core-035). + // state read at pass time. OnInput bool // Tools is the declared tool set: the only tools a pass may reach. // Enforcement is mechanical — the pass's tool set is built from this // list, never from a broader registry. Tools []string - // Skills declares the skill-maintenance capability (skill curator, - // archie-core-i7i). The registrar must carry a SkillStore for a - // curator that declares it. + // Skills declares the skill-maintenance capability. The registrar must + // carry a SkillStore for a curator that declares it. Skills bool // MemoryEngine names the attached memory engine once the memory engine - // family exists (archie-core-pek). Empty means the curator does not + // family exists. Empty means the curator does not // use memory; a memory operation without a declared engine is // rejected. MemoryEngine string - // Conversations declares the conversation-history capability - // (session-memory curator, archie-core-1786637499114). The registrar + // Conversations declares the conversation-history capability. + // The registrar // must carry a ConversationSource for a curator that declares it. Conversations bool // Model is the model reference ("provider/model") passes use. Empty @@ -132,7 +131,6 @@ type PassInput struct { // PassResult reports what a pass did. Every action is attributable: the // registry emits them as events and they are inspectable at runtime -// (archie-core-114). type PassResult struct { // Actions records what this pass changed and why. Actions []Action diff --git a/internal/domain/curator/definition_engine.go b/internal/domain/curator/definition_engine.go index 3aeda3fa0..9eedcc5e2 100644 --- a/internal/domain/curator/definition_engine.go +++ b/internal/domain/curator/definition_engine.go @@ -13,10 +13,7 @@ import ( // registry's activity surface and events. const ActionToolCalled = "tool.called" -// defaultDefinitionMaxSteps bounds the model/tool loop of one definition -// pass. It is not a definition value and is deliberately not configurable -// yet: the PRD's no-live-path-constants rule covers interval, cooldown, -// tools, model, and memory engine, not loop length. +// defaultDefinitionMaxSteps bounds the model/tool loop of one definition pass. const defaultDefinitionMaxSteps = 10 // DefinitionEngine interprets a Definition: one generic engine serving diff --git a/internal/domain/curator/registrar.go b/internal/domain/curator/registrar.go index 14e09ccaf..442d7bfe7 100644 --- a/internal/domain/curator/registrar.go +++ b/internal/domain/curator/registrar.go @@ -29,11 +29,11 @@ type Registrar struct { // declared set, never a broader registry. Bound when tools are // declared. Tools ToolBuilder - // Skills is the skill-maintenance capability (skill curator, - // archie-core-i7i). Bound when the curator declares Skills. + // Skills is the skill-maintenance capability. Bound when the curator + // declares Skills. Skills SkillStore // MemoryEngines resolves a named memory engine, for a curator that - // declared Manifest.MemoryEngine (archie-core-1786637499636). Bound + // declared Manifest.MemoryEngine. Bound // only when declared. Like Tools, resolution is by name at call time, // not a value pre-fetched at Bind: a curator calls // MemoryEngines.Get(its own Manifest().MemoryEngine), the same trust @@ -41,9 +41,8 @@ type Registrar struct { // trusted to pass its own declared identifier, not handed a // pre-scoped instance. MemoryEngines MemoryEngineSource - // Conversations is read-only recent conversation history, for a - // curator that declared Manifest.Conversations (session-memory - // curator, archie-core-1786637499114). Bound only when declared. + // Conversations is read-only recent conversation history, for a curator + // that declared Manifest.Conversations. Bound only when declared. Conversations ConversationSource // Events publishes curator activity. Implementations must be // non-blocking and bounded (drop on overflow), so a curator can never @@ -99,7 +98,7 @@ type ToolBuilder interface { } // SkillStore is the skill-maintenance capability. The implementation owns -// the on-disk format and catalog reload rules (archie-core-i7i). +// the on-disk format and catalog reload rules. type SkillStore interface { List(ctx context.Context) ([]SkillRef, error) Read(ctx context.Context, name string) (Skill, error) diff --git a/internal/domain/curator/registry.go b/internal/domain/curator/registry.go index 9736fc56a..5d25ca087 100644 --- a/internal/domain/curator/registry.go +++ b/internal/domain/curator/registry.go @@ -45,8 +45,8 @@ type Registry struct { order []string state registryState - // activity tracks recent per-curator run history for observability - // (archie-core-1786637489932-6). It has its own mutex and is safe to + // activity tracks recent per-curator run history for observability. + // It has its own mutex and is safe to // use independently of r.mu. activity *activityTracker } diff --git a/internal/domain/curator/runtime.go b/internal/domain/curator/runtime.go index e50e1da44..1f3bc8c69 100644 --- a/internal/domain/curator/runtime.go +++ b/internal/domain/curator/runtime.go @@ -40,7 +40,7 @@ type RuntimeConfig struct { // Curators are peers, never dependencies: nothing a curator does — a // blocking pass, a panic, a burst of nudges — can block a chat turn, an // agent run, or the daemon. Wake events are accelerations; the trigger is a -// deterministic state read at pass time (archie-core-035), so a dropped +// deterministic state read at pass time, so a dropped // nudge only delays a run to the next check-in. type Runtime struct { registry *Registry @@ -312,7 +312,7 @@ func (rt *Runtime) fail(name, phase string, err error) { } // emitRun publishes one run summary plus one event per action, so what ran, -// when, what it changed, and why all stay attributable (archie-core-114). +// when, what it changed, and why all stay attributable. func (rt *Runtime) emitRun(name string, at time.Time, result PassResult) { rt.registry.RecordActivity(name, at, result.Actions) diff --git a/internal/domain/curator/wake.go b/internal/domain/curator/wake.go index e65e347dd..1638fcfbd 100644 --- a/internal/domain/curator/wake.go +++ b/internal/domain/curator/wake.go @@ -8,7 +8,7 @@ import ( ) // WakeOnPrimaryInput forwards primary-input events from the in-process bus -// to the runtime as best-effort nudges (archie-core-035). Only the kinds in +// to the runtime as best-effort nudges. Only the kinds in // inputKinds wake curators — the trigger-accounting invariant: curator- // produced activity (curator_run, curator_action, curator_error, and any // future derived-write kind) never appears on this path, so a curator's own diff --git a/internal/domain/eda/expr/expr.go b/internal/domain/eda/expr/expr.go index b8d2d2522..efa1e7334 100644 --- a/internal/domain/eda/expr/expr.go +++ b/internal/domain/eda/expr/expr.go @@ -13,10 +13,9 @@ // evaluation cannot disagree; the standalone lint command covers the flat // kind/label binding files, not rich EDA playbook documents. // -// CEL is non-Turing-complete, side-effect-free, and panic-free by design (no -// recover() wrapper is needed; verified in the t2db.14 acceptance tests -// against hostile data). Anything the schema does not accept is a returned -// error here -- the reject-at-load philosophy of the parent design doc. +// CEL is non-Turing-complete, side-effect-free, and panic-free by design. +// Anything the schema does not accept is a returned error here -- the +// reject-at-load philosophy of the parent design doc. package expr import ( diff --git a/internal/domain/eda/module/log/log.go b/internal/domain/eda/module/log/log.go index 3ab1471a5..38c4dff57 100644 --- a/internal/domain/eda/module/log/log.go +++ b/internal/domain/eda/module/log/log.go @@ -1,8 +1,8 @@ // Package log is the schema source for the "log" Module action kind -- the -// side-effect-free proof-of-concept kind for the Module position (t2db.13, -// docs/prds/module-position.md). A Yaegi module implementing this kind -// exports a fixed function name against these generated types; the operator's -// file is the implementation, this package is the contract. +// side-effect-free proof-of-concept kind for the Module position. A Yaegi +// module implementing this kind exports a fixed function name against these +// generated types; the operator's file is the implementation, this package is +// the contract. // // This is the hand-written schema. logextract (generated by `go generate`) // turns it into the Yaegi symbol table the interpreter uses. diff --git a/internal/domain/eda/module/module.go b/internal/domain/eda/module/module.go index e2efd131d..2257a3d55 100644 --- a/internal/domain/eda/module/module.go +++ b/internal/domain/eda/module/module.go @@ -7,10 +7,9 @@ // installed source, resolve its typed entrypoint, then call it through the // panic-safe interpreter boundary. // -// Per docs/prds/module-position.md, there is deliberately no generic Module -// interface with an any payload. Each action kind is its own tiny package -// with its own generated contract (internal/domain/eda/module/), and -// the registry's internal storage is the only place type erasure appears. +// Each action kind is its own tiny package with its own generated contract +// (internal/domain/eda/module/), and the registry's internal storage is +// the only place type erasure appears. package module import ( @@ -74,9 +73,9 @@ func New() *ModuleRegistry { return &ModuleRegistry{kinds: make(map[string]invoker)} } -// Kinds returns the known action-kind names, sorted for determinism. Only -// kinds with a registered contract can be loaded; the log kind is the -// shipped proof-of-concept (t2db.13). +// Kinds returns the known action-kind names, sorted for determinism. Only kinds +// with a registered contract can be loaded; the log kind is the shipped +// proof-of-concept. func Kinds() []string { names := make([]string, 0, len(registry)) for name := range registry { diff --git a/internal/domain/eda/playbook/coordinator.go b/internal/domain/eda/playbook/coordinator.go index 8d1ed78e9..c09692df1 100644 --- a/internal/domain/eda/playbook/coordinator.go +++ b/internal/domain/eda/playbook/coordinator.go @@ -13,8 +13,8 @@ import ( // InvokeOnce runs one playbook action at most once per // (playbook, version, event, action) tuple, record-before-invoke: the ledger // row is committed before fn runs, so a redelivered action (the same -// structural key) skips without repeating a non-revocable side effect -// (docs/prds/eda-playbook-engine.md gap 2). The structural key is computed +// structural key) skips without repeating a non-revocable side effect. +// The structural key is computed // from Decision.PlaybookID, Decision.Version, input.TaskID (the event_id) and // Decision.ActionID; when the action declares no id the 1-based // Decision.ActionPosition is used instead -- it is never a CEL expression. A diff --git a/internal/domain/eda/playbook/playbook.go b/internal/domain/eda/playbook/playbook.go index 1f5409747..0bd718fcc 100644 --- a/internal/domain/eda/playbook/playbook.go +++ b/internal/domain/eda/playbook/playbook.go @@ -1,20 +1,18 @@ -// Package playbook is the EDA playbook document type and its event -// coordinator: the rich trigger+actions YAML shape (docs/prds/ -// eda-playbook-engine.md) with CEL `when` conditions and `args` values -// (open question 1, resolved to CEL). A playbook is one of two shapes +// Package playbook is the EDA playbook document type and its event coordinator: +// the rich trigger+actions YAML shape with CEL `when` conditions and `args` +// values (open question 1, resolved to CEL). A playbook is one of two shapes // (multi-action-playbooks.md, D2): // // - a workflow playbook is exactly one `workflow` action, unchanged from // the original boundary, and is routed by the daemon's definition pin; // - an action playbook is one or more `module` actions in order, each with // a registered `kind`, `args`, and an optional `when`/`id`. Store.Run -// executes it (docs/prds/action-playbook-run.md). +// executes it. // // The two shapes never mix in one playbook. This is an ADDITIONAL routing -// source alongside the flat kind/label binding files (t2db.9/.10/.11): the -// daemon consults a matching workflow playbook before those bindings when it -// pins a task's workflow definition (t2db.23). The binding loaders themselves -// are untouched. +// source alongside the flat kind/label binding files: the daemon consults a +// matching workflow playbook before those bindings when it pins a task's +// workflow definition. The binding loaders themselves are untouched. package playbook import ( @@ -661,7 +659,6 @@ func (pb *Playbook) Match(input DispatchInput) bool { // that chose it. Version pins the decision to the exact file content active // when it fired, and both fields are the first two components of the // per-action idempotency key the resolved gap-2 scheme derives -// (docs/prds/eda-playbook-engine.md, "Idempotency at execution time"). type Decision struct { PlaybookID string Version string @@ -671,9 +668,8 @@ type Decision struct { // dispatch ledger) read this action under. ActionID string // ActionPosition is the 1-based index of the dispatched action in the - // playbook's actions list. It is the idempotency-key fallback when - // ActionID is empty (docs/prds/eda-playbook-engine.md, "Idempotency at - // execution time"). + // playbook's actions list. It is the idempotency-key fallback when ActionID + // is empty. ActionPosition int } @@ -736,7 +732,6 @@ func evalContext(input DispatchInput) expr.Context { // Asymmetry with `when`: `when` is a predicate, so an evaluation error is // false (J3: skip + log); `args` is data, so an evaluation error has no // meaningful substitute and is returned to the caller to abort the playbook run -// (J6, docs/prds/playbook-expression-syntax.md). func (s *Store) EvalArgs(a Action, input DispatchInput) (map[string]any, error) { if s == nil { return map[string]any{}, nil diff --git a/internal/domain/eda/playbook/run.go b/internal/domain/eda/playbook/run.go index 7fe2dcf7e..0c90ed03f 100644 --- a/internal/domain/eda/playbook/run.go +++ b/internal/domain/eda/playbook/run.go @@ -12,7 +12,7 @@ import ( ) // Run executes every action playbook whose trigger matches input, in load -// order (docs/prds/action-playbook-run.md). Each action goes through +// order. Each action goes through // InvokeOnce, so it fires at most once per (playbook, version, event, // action). A failure stops only its own playbook; the rest still run, and // the failures are returned joined, each naming its playbook and action. diff --git a/internal/domain/embedding/contract.go b/internal/domain/embedding/contract.go index 35e145c42..66adc5920 100644 --- a/internal/domain/embedding/contract.go +++ b/internal/domain/embedding/contract.go @@ -1,7 +1,6 @@ -// Package embedding is the embedding capability: a narrow typed boundary -// for turning text into vectors, so consumers (curators first, per bead -// archie-core-1786637500752-415-434e5bb9 / GitHub #436) never depend on a -// specific provider SDK. +// Package embedding is the embedding capability: a narrow typed boundary for +// turning text into vectors, so consumers never depend on a specific provider +// SDK. // // Unlike curator and memory (internal/domain/curator, internal/domain/ // memory), a Client has no Lifecycle: it is call-scoped, not long-running, diff --git a/internal/domain/eventtype/eventtype.go b/internal/domain/eventtype/eventtype.go index 8d8c500e3..9d6a81cb2 100644 --- a/internal/domain/eventtype/eventtype.go +++ b/internal/domain/eventtype/eventtype.go @@ -1,9 +1,9 @@ // Package eventtype owns event types: named kinds of event from one source, -// each defined by a match rule over headers and payload. It infers a -// structural signature per capture, groups a source's captures into proposed -// types, evaluates rules, and refuses two types on one source whose rules can -// match the same event. An event that matches no type is unidentified and is -// never dispatched. See docs/prds/event-automation.md, "Event types". +// each defined by a match rule over headers and payload. It infers a structural +// signature per capture, groups a source's captures into proposed types, +// evaluates rules, and refuses two types on one source whose rules can match +// the same event. An event that matches no type is unidentified and is never +// dispatched. package eventtype import ( diff --git a/internal/domain/harnesssecret/harnesssecret.go b/internal/domain/harnesssecret/harnesssecret.go index 96f73ca91..f3166f41b 100644 --- a/internal/domain/harnesssecret/harnesssecret.go +++ b/internal/domain/harnesssecret/harnesssecret.go @@ -1,10 +1,8 @@ -// Package harnesssecret is the OAuth token set a credential binding's -// service holds for one org (docs/prds/external-agent-harness.md, -// Credentials). The setup terminal writes the first capture; the egress -// proxy overwrites it on every token refresh. It is never a Kit-declared -// value and never resolved through the config secret registry the way an -// API-key binding's SecretRef is -- it is state archie itself captures and -// mutates. +// Package harnesssecret is the OAuth token set a credential binding's service +// holds for one org. The setup terminal writes the first capture; the egress +// proxy overwrites it on every token refresh. It is never a Kit-declared value +// and never resolved through the config secret registry the way an API-key +// binding's SecretRef is -- it is state archie itself captures and mutates. package harnesssecret import ( diff --git a/internal/domain/image/contract.go b/internal/domain/image/contract.go index f8f0df2eb..69e9a8499 100644 --- a/internal/domain/image/contract.go +++ b/internal/domain/image/contract.go @@ -1,8 +1,6 @@ -// Package image is the image generation capability family: a -// provider-neutral boundary for hosted (gpt-image-2-class) and local GPU -// backends, so /image routing can target either without depending on -// provider-specific types. See docs/prds/image-capability-contract.md for -// the design and epic archie-core-1786748942120-1-6636e629. +// Package image is the image generation capability family: a provider-neutral +// boundary for hosted (gpt-image-2-class) and local GPU backends, so /image +// routing can target either without depending on provider-specific types. // // Unlike curator and memory (internal/domain/curator, // internal/domain/memory), a Provider has no Lifecycle: it is call-scoped, diff --git a/internal/domain/mapping/mapping.go b/internal/domain/mapping/mapping.go index f99c2e590..e108ee4c7 100644 --- a/internal/domain/mapping/mapping.go +++ b/internal/domain/mapping/mapping.go @@ -2,7 +2,6 @@ // resolve/preview rule: binding named fields to JSON paths inside a // captured webhook payload, and deciding -- loudly -- when a path a mapping // depends on has drifted out from under it. See -// docs/prds/payload-field-mapping.md. package mapping import ( @@ -104,9 +103,8 @@ func (m Mapping) Validate() error { return nil } -// Failure describes one field that did not resolve cleanly against a -// payload -- named by field and path so the operator (or, once t2db.4 -// lands, the runtime failure it surfaces) knows exactly what drifted. +// Failure describes one field that did not resolve cleanly against a payload -- +// named by field and path so the operator knows exactly what drifted. type Failure struct { FieldName string `json:"field_name"` Path string `json:"path"` diff --git a/internal/domain/memory/contract.go b/internal/domain/memory/contract.go index 447c6b97e..117c6c3d0 100644 --- a/internal/domain/memory/contract.go +++ b/internal/domain/memory/contract.go @@ -1,7 +1,5 @@ // Package memory is the memory engine family: the authoritative store for -// durable observations, addressed by typed scope. See -// docs/prds/memory-engine-unification.md for the decision this contract -// implements. +// durable observations, addressed by typed scope. // // One engine, four scopes. A caller names the scopes it may read or write // (Scope, Subject) and the engine applies no policy of its own: an engine @@ -16,10 +14,8 @@ // start/health/stop and shutdown ordering, and narrow typed host access // (Registrar) — an engine never receives the daemon or an untyped hook map. // -// This package owns the contract and the family's policy that is independent -// of any backend (the content scanner). internal/memory's MemoryProvider and -// Manager predate the domain migration and are the legacy runtime path, -// deleted in slice 5 of the same PRD; nothing here depends on them. +// This package owns the contract and the family's policy that is independent of +// any backend (the content scanner). package memory import ( @@ -68,7 +64,6 @@ type Lifecycle interface { } // ScopeKind names one of the four durable memory scopes -// (docs/architecture/agent-system.md, "Memory scopes"). type ScopeKind string const ( @@ -293,9 +288,6 @@ type NewRecord struct { // Validate checks what every engine needs before writing: an addressable // scope and content. Kind's format belongs to the backend (the builtin // engine maps it to a section name), so it is validated there. -// -// Implementations must also scan Content before persisting it — see -// ScanContent and docs/prds/memory-engine-unification.md §7. func (n NewRecord) Validate() error { if err := n.Scope.Validate(); err != nil { return err diff --git a/internal/domain/messaging/chat_contract.go b/internal/domain/messaging/chat_contract.go index b4c2a1ca1..4fedb5996 100644 --- a/internal/domain/messaging/chat_contract.go +++ b/internal/domain/messaging/chat_contract.go @@ -9,7 +9,7 @@ import ( // ChatContract is the conversational boundary consumed by channel frontends. // Results are snapshots: callers must not rely on shared object identity. -// It moved here from internal/gateway (archie-core-8cda.5.6) so the webui +// It moved here from internal/gateway so the webui // and archie-ui processes can hold the contract without linking the gateway // runtime (and, transitively, its SQLite session store). type ChatContract interface { //nolint:interfacebloat // wire contract intentionally covers the complete Gateway facade diff --git a/internal/domain/messaging/chat_stream.go b/internal/domain/messaging/chat_stream.go index b7eb4745f..9ecc32a30 100644 --- a/internal/domain/messaging/chat_stream.go +++ b/internal/domain/messaging/chat_stream.go @@ -28,7 +28,6 @@ type ChatReply struct { // than a real dispatch outcome. A human-facing channel can ignore it and // send Text as usual; a channel with no human reading replies (a webhook) // must not treat it as a normal reply or a delivered event -- see - // archie-core-1173. RateLimited bool } diff --git a/internal/domain/messaging/inbound.go b/internal/domain/messaging/inbound.go index f40972bcd..882fe1ac3 100644 --- a/internal/domain/messaging/inbound.go +++ b/internal/domain/messaging/inbound.go @@ -41,8 +41,8 @@ type Inbound struct { // one Router serves all of them, so its own name is "web" even for a // Telegram turn, which made SessionSource.Platform -- the first // component of the session natural key -- a constant, and left the - // per-user identity policy unreachable with a real channel name - // (archie-core-c1qx). Transport-only and never persisted: the session + // per-user identity policy unreachable with a real channel name. + // Transport-only and never persisted: the session // record keeps the platform. Empty means the sender did not name its // channel, and the Gateway falls back to its own name. Platform string diff --git a/internal/domain/messaging/message.go b/internal/domain/messaging/message.go index c318b6924..ad7b5206f 100644 --- a/internal/domain/messaging/message.go +++ b/internal/domain/messaging/message.go @@ -2,13 +2,9 @@ // channel and source correlation, and typed tool-call/tool-result message // variants. // -// This package intentionally contains only the vocabulary already settled -// in docs/architecture/migration-decisions.md section 2: the composite -// Conversation identity, immutable MessageIDs, typed tool-call and -// tool-result messages, and branch lineage through ParentConversationID and -// ForkMessageID. Migrating internal/gateway/'s session, compression, -// approval, and branch logic onto these types is deliberately out of scope -// here — see that section for why, and bd for the tracked follow-up work. +// Migrating internal/gateway/'s session, compression, approval, and branch +// logic onto these types is deliberately out of scope here — see that section +// for why, and bd for the tracked follow-up work. package messaging import "time" @@ -96,7 +92,7 @@ type Message struct { // when the channel has no stable per-person identity to offer -- which // includes a webhook, whose configured route path is a source rather // than a person and travels in the transport-only Inbound.BudgetKey - // instead (see docs/prds/memory-engine-unification.md §3). Used to key + // instead. Used to key // per-identity inbound controls and to derive a memory participant, so // a non-person value here becomes a user identity to every consumer // that reads it. diff --git a/internal/domain/messaging/session_store.go b/internal/domain/messaging/session_store.go index 3298d422d..6385cb143 100644 --- a/internal/domain/messaging/session_store.go +++ b/internal/domain/messaging/session_store.go @@ -62,13 +62,13 @@ type SessionContext struct { // SessionStore persists gateway session metadata and conversation history. // Each session tracks one platform, bot, and channel combination. // -// Message history is stored and loaded as canonical Message records -// (archie-core-d9dv). Session lifecycle records stay SessionContext: +// Message history is stored and loaded as canonical Message records. +// Session lifecycle records stay SessionContext: // a session's UUID key, platform/bot/title/branch metadata, and the fact // that several sessions share one channel/thread have no lossless home in // Conversation, whose composite identity is only // {ChannelID, ThreadID} and whose canonical Agent/user/binding ownership is -// still open (see docs/architecture/migration-decisions.md section 2). +// still open. // Conversation-keying the sessions is tracked as follow-up work once that // ownership settles. type SessionStore interface { diff --git a/internal/domain/org/org.go b/internal/domain/org/org.go index 491d29a91..efd5d35d7 100644 --- a/internal/domain/org/org.go +++ b/internal/domain/org/org.go @@ -1,6 +1,5 @@ // Package org owns the tenant boundary: orgs, the workspaces that divide them, // and the memberships that give an identity a role in either -// (docs/prds/orgs-and-access.md). package org import ( @@ -35,9 +34,8 @@ var ( ErrWorkspaceExists = errors.New("org: workspace already exists") ErrMembershipExists = errors.New("org: membership already exists") // ErrUpgradeIncomplete reports that the resumable default org/workspace - // upgrade has not finished (docs/prds/orgs-and-access.md, "Upgrading - // existing installs"): the store refuses scoped calls rather than serving - // records with no org. + // upgrade has not finished: the store refuses scoped calls rather than + // serving records with no org. ErrUpgradeIncomplete = errors.New("org: default org upgrade incomplete") ) diff --git a/internal/domain/org/store.go b/internal/domain/org/store.go index b8638b082..199df9ad3 100644 --- a/internal/domain/org/store.go +++ b/internal/domain/org/store.go @@ -34,8 +34,8 @@ type Repository interface { OrgForIdentity(context.Context, identity.IdentityID) (OrgID, error) } -// Upgrader performs the resumable default org/workspace upgrade -// (docs/prds/orgs-and-access.md, "Upgrading existing installs"). It runs in +// Upgrader performs the resumable default org/workspace upgrade. +// It runs in // the State Store first, then in the event store, each phase resumable from // its recorded ledger row, and it must run before scoped calls are served. type Upgrader interface { diff --git a/internal/domain/sampling/contract.go b/internal/domain/sampling/contract.go index 9a8030f85..99d9e58ee 100644 --- a/internal/domain/sampling/contract.go +++ b/internal/domain/sampling/contract.go @@ -1,9 +1,7 @@ // Package sampling is the curator sampler family: given a bounded set of -// candidates, pick a subset to spend a curator pass's agentic budget on. -// See docs/prds/curator-sampler-wave1.md for the design and the four -// wave-1 strategies (recency, random, all, staleness) this package ships. -// The embedding-backed surprisal strategy (GitHub #437) is a separate, -// deferred consumer of this same interface -- it does not live here. +// candidates, pick a subset to spend a curator pass's agentic budget on. The +// embedding-backed surprisal strategy is a separate, deferred consumer of this +// same interface -- it does not live here. package sampling import ( @@ -33,7 +31,7 @@ type Request struct { // Sampler selects a subset of candidates to spend a curator pass's agentic // budget on. Every implementation -- the four in this package and the -// future embedding-backed surprisal strategy (GitHub #437) -- must be +// future embedding-backed surprisal strategy -- must be // deterministic given the same candidates and Request: same inputs, same // output, every time. That is what makes a pass reproducible and testable. type Sampler interface { diff --git a/internal/domain/sampling/staleness.go b/internal/domain/sampling/staleness.go index 67eb0c18f..5cdffbf60 100644 --- a/internal/domain/sampling/staleness.go +++ b/internal/domain/sampling/staleness.go @@ -6,7 +6,7 @@ import "context" // hasn't been touched/reviewed in the longest time, i.e. the smallest // Candidate.At first. It is a cheap proxy only -- callers decide what // timestamp At holds (created, updated, or last-reviewed); this is never -// the embedding-based surprisal calculation (see GitHub #437). +// the embedding-based surprisal calculation. type stalenessSampler struct{} // NewStaleness builds the "staleness" strategy. diff --git a/internal/domain/scheduling/contract.go b/internal/domain/scheduling/contract.go index fb604c262..da42a8a35 100644 --- a/internal/domain/scheduling/contract.go +++ b/internal/domain/scheduling/contract.go @@ -1,5 +1,5 @@ // Package scheduling is the ticker engine: the timing half of archied's -// cron/scheduling capability (epic archie-core-1786637496320-249-be6d9a20). +// cron/scheduling capability. // It owns one job and one job only — deciding *when* a scheduled job runs, // and with what concurrency — and nothing about where jobs are stored, how // they are authored, or how their output is delivered. diff --git a/internal/domain/source/source.go b/internal/domain/source/source.go index 541c58d15..0462c7ea7 100644 --- a/internal/domain/source/source.go +++ b/internal/domain/source/source.go @@ -1,5 +1,5 @@ -// Package source owns the capture source: the endpoint one sender posts to, -// and its signing setting. See docs/prds/event-automation.md "Sources". +// Package source owns the capture source: the endpoint one sender posts to, and +// its signing setting. package source import ( diff --git a/internal/domain/storecontract/storecontract.go b/internal/domain/storecontract/storecontract.go index 7e5887b4f..777a6d73e 100644 --- a/internal/domain/storecontract/storecontract.go +++ b/internal/domain/storecontract/storecontract.go @@ -1,6 +1,6 @@ // Package storecontract is the ratified State Store contract as its // consumers reference it: the producer-owned daemon/webui/intake store -// surfaces (docs/prds/state-store-contract.md §1, §2). It carries no +// surfaces. It carries no // persistence -- internal/infrastructure/postgres and *staterpc.Client (the // remote adapter) both satisfy these interfaces -- // so a process that only holds the contracts, such as the archie-ui @@ -10,7 +10,7 @@ // It is hand-written and lives in the domain layer (which owns required // contracts), NOT under internal/contracts: that tree is the buf generate // output and is wiped and regenerated by tools/proto.sh, which would -// delete a hand-written file there (archie-core-8cda.5.6). +// delete a hand-written file there. package storecontract import ( @@ -67,8 +67,8 @@ type TaskParker interface { ParkTask(ctx context.Context, taskID int64, from, detail, class string) error } -// StepRecorder records the StepExecutions of one running WorkflowExecution -// (docs/prds/execution-tree-state-machine.md). It is deliberately separate +// StepRecorder records the StepExecutions of one running WorkflowExecution. +// It is deliberately separate // from TaskLifecycle, which is exactly at the interfacebloat cap: the same // two methods also sit on the workflow engine's mid-run facade (task.Store), // which is what a container's run credential calls. @@ -77,8 +77,8 @@ type StepRecorder interface { FinishStep(ctx context.Context, s task.StepFinish) (events.Event, error) } -// ExecutionCanceller is the one cancel path -// (docs/prds/execution-tree-state-machine.md, "Cancellation"): one +// ExecutionCanceller is the one cancel path: +// one // transaction moves every non-terminal StepExecution of the execution's // current attempt to cancelled and the execution itself to the status the // operator action names (parked or closed_wont_do, as the transition table @@ -93,7 +93,7 @@ type ExecutionCanceller interface { } // StepReader lists one execution's recorded steps -- the dashboard run -// detail's read (docs/prds/execution-tree-state-machine.md). Separate from +// detail's read. Separate from // StepRecorder: this is a dashboard/API/dispatch action (Authorizer: read on // the run), never task-scoped-grant callable the way StartStep/FinishStep // are. @@ -101,14 +101,12 @@ type StepReader interface { ListSteps(ctx context.Context, executionID int64, attempt int) ([]task.StepExecution, error) } -// HarnessSecretStore persists one org's OAuth token set per credential -// binding service (docs/prds/external-agent-harness.md, Credentials). The -// setup terminal writes the first capture (an `update` action on the -// secret, Authorizer-gated); the egress proxy's token-endpoint interception -// overwrites it on every refresh with no Authorizer check of its own -- it -// acts as the run, not as an operator. Encrypted at rest under its own -// domain separator (docs/prds/binding-secret-encryption.md, -// bindingcipher.HarnessSecretDomain). +// HarnessSecretStore persists one org's OAuth token set per credential binding +// service. The setup terminal writes the first capture (an `update` action on +// the secret, Authorizer-gated); the egress proxy's token-endpoint interception +// overwrites it on every refresh with no Authorizer check of its own -- it acts +// as the run, not as an operator. Encrypted at rest under its own domain +// separator. type HarnessSecretStore interface { GetHarnessSecret(ctx context.Context, org, service string) (harnesssecret.Secret, error) PutHarnessSecret(ctx context.Context, s harnesssecret.Secret) error @@ -129,8 +127,8 @@ type TaskRetryer interface { RetryTask(ctx context.Context, taskID int64, fromStatus, workflow, retryMode string) error } -// ReviewGateResponder is the operator's answer to the review gate -// (docs/prds/pr-review-operator-response.md, Decision 2): one guarded write +// ReviewGateResponder is the operator's answer to the review gate: +// one guarded write // beside RetryTask/BeginRemediation that fills in the review gate document // the caller computed (the outcome, the selection or the instructions), and // -- for a re-review only -- increments rereview_rounds and requeues, under @@ -144,12 +142,10 @@ type ReviewGateResponder interface { RespondReviewGate(ctx context.Context, taskID int64, fromStatus, gate string, rereview bool, maxRounds int) error } -// RemediationStarter queues a review-triggered remediation for an -// Archie-owned open-PR task: one guarded transition that carries the -// JSON-encoded review unit in the same write, so a claimed remediation -// always has its input. UpdateReviewPayload appends late-arriving comments -// to a still-queued unit. Both guards are the reaction consumer's dedup and -// are documented in docs/prds/pr-review-remediation.md decisions 3 and 5. +// RemediationStarter queues a review-triggered remediation for an Archie-owned +// open-PR task: one guarded transition that carries the JSON-encoded review +// unit in the same write, so a claimed remediation always has its input. +// UpdateReviewPayload appends late-arriving comments to a still-queued unit. type RemediationStarter interface { BeginRemediation(ctx context.Context, taskID int64, payload string) error UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error @@ -186,18 +182,17 @@ type TaskEvents interface { // workflow binding and no task association. Deliberately separate from // TaskStore: a consumer that only needs capture (the intake HTTP handler) // should not acquire the full task-lifecycle surface, mirroring why -// TaskArchiver is split out above. See docs/prds/event-capture-storage.md. +// TaskArchiver is split out above. type CaptureStore interface { InsertCapture(ctx context.Context, c CapturedEvent, retention time.Duration, maxEvents int) (string, error) ListCaptures(ctx context.Context, limit int) ([]CapturedEvent, error) } -// ConfigSnapshotStore holds the running configuration as the dashboard -// renders it: the owner of configuration publishes, the process that displays -// it reads. Separate from every other store surface because it is the only -// one whose writer is the daemon and whose reader is the UI, and because a -// task-scoped credential must never reach the writer. -// See docs/architecture/migration-decisions.md, "Dashboard configuration page". +// ConfigSnapshotStore holds the running configuration as the dashboard renders +// it: the owner of configuration publishes, the process that displays it reads. +// Separate from every other store surface because it is the only one whose +// writer is the daemon and whose reader is the UI, and because a task-scoped +// credential must never reach the writer. type ConfigSnapshotStore interface { PutConfigSnapshot(ctx context.Context, snapshot ConfigSnapshot) error ConfigSnapshot(ctx context.Context) (ConfigSnapshot, bool, error) @@ -211,7 +206,6 @@ type ConfigSnapshotStore interface { // It is runtime state rather than a settings document -- a channel that is // failed is not a document anybody edits -- which is why it is not a // ControlPlaneService resource kind. -// See docs/architecture/migration-decisions.md, "Channel state to the dashboard". type ChannelStatusStore interface { // PutChannelStatus records the reporting process's whole set: a channel it no // longer reports is removed rather than left behind, because a stale "running" @@ -224,17 +218,15 @@ type ChannelStatusStore interface { // process is running. Same split as ConfigSnapshotStore and for the same // reason: the writers are the processes that apply a resource, the reader is // the UI, and a task-scoped credential must reach neither. -// See docs/prds/control-plane-apply-status.md. type ApplyStatusStore interface { PutApplyStatus(ctx context.Context, status ApplyStatus) error ListApplyStatus(ctx context.Context) ([]ApplyStatus, error) } -// MappingStore persists payload field mappings (t2db.3). Deliberately -// separate from TaskStore and CaptureStore for the same reason those are -// split: the dashboard's mapping editor should only acquire the mapping -// surface, not the full task or capture APIs. See -// docs/prds/payload-field-mapping.md. +// MappingStore persists payload field mappings. Deliberately separate from +// TaskStore and CaptureStore for the same reason those are split: the +// dashboard's mapping editor should only acquire the mapping surface, not the +// full task or capture APIs. See type MappingStore interface { InsertMapping(ctx context.Context, m mapping.Mapping) (string, error) GetMapping(ctx context.Context, id string) (*mapping.Mapping, error) @@ -250,11 +242,10 @@ type MappingMatchRecorder interface { RecordMappingMatch(ctx context.Context, mappingID, captureID string) error } -// EventTypeStore persists event types (docs/prds/event-automation.md, "Event -// types"). Insert and Update refuse a type whose rule overlaps another on the -// same source with eventtype.ErrOverlap, and a malformed one with -// eventtype.ErrInvalid. Update rewrites the name and rule; the schema is the -// one the type was created with. +// EventTypeStore persists event types. Insert and Update refuse a type whose +// rule overlaps another on the same source with eventtype.ErrOverlap, and a +// malformed one with eventtype.ErrInvalid. Update rewrites the name and rule; +// the schema is the one the type was created with. type EventTypeStore interface { InsertEventType(ctx context.Context, t eventtype.EventType) (string, error) UpdateEventType(ctx context.Context, t eventtype.EventType) error @@ -262,12 +253,11 @@ type EventTypeStore interface { ListEventTypes(ctx context.Context) ([]eventtype.EventType, error) } -// BindingStore persists playbook bindings (t2db.4 Phase B): CRUD and the -// draft -> pending_approval -> armed state machine. Split off from -// TaskStore and MappingStore so the webui binding editor does not acquire -// the full task or mapping surfaces. Dispatch-time helpers live in -// BindingDispatcher; the daemon depends on both. See -// docs/prds/playbook-binding.md. +// BindingStore persists playbook bindings: CRUD and the draft -> +// pending_approval -> armed state machine. Split off from TaskStore and +// MappingStore so the webui binding editor does not acquire the full task or +// mapping surfaces. Dispatch-time helpers live in BindingDispatcher; the daemon +// depends on both. See type BindingStore interface { InsertBinding(ctx context.Context, b binding.Binding) (string, error) GetBinding(ctx context.Context, id string) (*binding.Binding, error) @@ -277,8 +267,8 @@ type BindingStore interface { ApproveBinding(ctx context.Context, id string) error } -// SourceStore persists capture sources and their signing setting -// (docs/prds/event-automation.md "Sources"). The path is the key and never +// SourceStore persists capture sources and their signing setting. +// The path is the key and never // changes. Secrets cross this surface in plaintext; the store encrypts them // at rest. Signing transitions are decided by the source domain and written // with an expected-from guard, so two operators cannot race an approval. @@ -321,7 +311,7 @@ type BindingTaskCreator interface { } // WorkflowCaller is the consumer surface a workflow.call step crosses to -// start its callee and read it back while waiting (docs/prds/workflow-calls.md). +// start its callee and read it back while waiting. // It is the workflow engine's own task.Caller contract, satisfied by the // PostgreSQL store and *staterpc.Client alike -- the same shape as // workflow.Store. The caller task ID is explicit so both the wire grant and @@ -330,7 +320,7 @@ type BindingTaskCreator interface { type WorkflowCaller = task.Caller // PlaybookDispatcher is the idempotency-ledger surface for side-effecting -// playbook actions (docs/prds/eda-playbook-engine.md gap 2). +// playbook actions. // RecordPlaybookDispatch writes the (playbook, version, event, action) row // BEFORE the action's side effect fires -- the deliberate reverse of // BindingDispatcher.RecordDispatch -- so a duplicate returns @@ -350,7 +340,7 @@ type PlaybookDispatcher interface { // owns the format of, and a process that can read the task board should not // have to acquire a log reader to do it. The dashboard's UI process is the // consumer this exists for -- it holds no daemon-local file handle, so the -// read crosses the State Store contract (docs/prds/ui-service-boundary.md). +// read crosses the State Store contract. // // Found=false with a nil error is the not-found convention every read here // uses, and it is load-bearing: "this attempt has no log" is not "this @@ -368,7 +358,6 @@ type TaskLogStore interface { // CapturedEvent is one unbound inbound webhook capture: no workflow binding, // no forge/task association -- just what arrived, from where, and when. -// See docs/prds/event-capture-storage.md. type CapturedEvent struct { ID string `json:"id"` ReceivedAt time.Time `json:"received_at"` @@ -469,23 +458,21 @@ type DayTokens struct { // Sentinel errors, part of the wire contract: staterpc's // mapError/unmapError match these by (code, canonical message) across the // gRPC boundary, so their message strings are load-bearing and must never -// change (docs/prds/state-store-contract.md §4). +// change. var ( // ErrStaleTransition is returned when a task transition's expected // from status does not match the task's current status. ErrStaleTransition = errors.New("store: stale transition: task status does not match expected from status") // ErrIllegalTransition is returned when a task's current status and the // requested status form a pair the shared taskstate transition table - // does not route (docs/prds/execution-tree-state-machine.md): the move + // does not route: the move // would have executed against a truthful from, but the table forbids // it. Distinct from ErrStaleTransition, which covers a from that does // not match the row's actual status. ErrIllegalTransition = errors.New("store: illegal transition: status pair is not in the transition table") - // ErrInvalidStep is returned when a step-execution request names a kind - // the store does not record (docs/prds/execution-tree-state-machine.md: - // stage, agent or call; a new kind needs a named consumer before it is - // added) or a step whose identifying fields do not resolve. Distinct from - // the transition sentinels, which cover a row's state. + // ErrInvalidStep is returned when a step-execution request names a kind the + // store does not record or a step whose identifying fields do not resolve. + // Distinct from the transition sentinels, which cover a row's state. ErrInvalidStep = errors.New("store: invalid step execution request") // ErrBindingNotFound is returned when a binding ID does not exist. ErrBindingNotFound = errors.New("store: binding not found") @@ -505,7 +492,6 @@ var ( // ErrCallNotYours is returned when a workflow.call status read names a // task that is not a callee of the calling task, or the caller itself // does not exist: a caller reads only the tasks it started - // (docs/prds/workflow-calls.md). ErrCallNotYours = errors.New("store: task is not a callee of the calling task") // ErrCallCallerNotRunning is returned when a workflow.call enqueue names // a caller that is not running: a stale retry, or a bug in the caller. @@ -530,9 +516,9 @@ var ( // captured one yet. ErrHarnessSecretNotFound = errors.New("store: harness secret not found") // ErrRereviewCapReached is returned when a review gate re-review would - // round past prreview.MaxRereviewRounds (docs/prds/pr-review-operator- - // response.md, Decision 2). The task stays waiting and its gate row is - // unchanged. The dashboard answers it 409, like every other conflict. + // round past prreview.MaxRereviewRounds. The task stays waiting and its + // gate row is unchanged. The dashboard answers it 409, like every other + // conflict. ErrRereviewCapReached = errors.New("store: re-review cap reached") // ErrResourceNotFound is returned when a control-plane resource kind has diff --git a/internal/domain/storepkg/authority.go b/internal/domain/storepkg/authority.go index 88dfc5e39..d2ba89a72 100644 --- a/internal/domain/storepkg/authority.go +++ b/internal/domain/storepkg/authority.go @@ -5,11 +5,10 @@ import ( "strings" ) -// Covers reports whether accepted authority is an upper bound of the -// requested authority: every grant the request asks for is one the accepted -// record grants, per field, never across fields. The acceptance record and -// the update-widening check share this predicate (docs/prds/store.md, -// "Authority": an update whose authority is equal or narrower applies). +// Covers reports whether accepted authority is an upper bound of the requested +// authority: every grant the request asks for is one the accepted record +// grants, per field, never across fields. The acceptance record and the +// update-widening check share this predicate. func (a Authority) Covers(b Authority) bool { return listCovers(a.CredentialServices, b.CredentialServices) && listCovers(a.EgressHosts, b.EgressHosts) && diff --git a/internal/domain/storepkg/installed.go b/internal/domain/storepkg/installed.go index 35491b025..ff5ac2a7f 100644 --- a/internal/domain/storepkg/installed.go +++ b/internal/domain/storepkg/installed.go @@ -14,7 +14,7 @@ var ( // ErrAuthorityNotDeclared: the operator asked to accept authority the // package itself does not declare, which is not an acceptance of that // package. Acceptance records the package's own declared grants against - // the pinned digest (docs/prds/store.md, "Authority"). + // the pinned digest. ErrAuthorityNotDeclared = errors.New("store package does not declare this authority") // ErrContributionCollision: the package contributes an entry the org // resource already holds under an id the package never projected. The diff --git a/internal/domain/taskactions/service.go b/internal/domain/taskactions/service.go index e910ff04b..c60f29d8c 100644 --- a/internal/domain/taskactions/service.go +++ b/internal/domain/taskactions/service.go @@ -51,10 +51,9 @@ type Task struct { } // ActionPayload is the per-action data an operator action carries: the -// review-gate answer for approve and rereview (docs/prds/pr-review-operator- -// response.md, Decision 1), and the worktree mode for retry. Every field is -// empty for the actions that do not use it, and for chat's /approve and -// /retry, which carry no instruction, selection or mode syntax. +// review-gate answer for approve and rereview, and the worktree mode for retry. +// Every field is empty for the actions that do not use it, and for chat's +// /approve and /retry, which carry no instruction, selection or mode syntax. type ActionPayload struct { // Instructions are what a re-review must focus on. The response path // requires them for ActionRereview and ignores them otherwise. @@ -184,8 +183,8 @@ type Store interface { RespondReviewGate(context.Context, int64, string, string, bool, int) error ArchiveTask(context.Context, int64, string, events.Event) (int64, error) InsertEvent(context.Context, events.Event) (int64, error) - // CancelExecution is the one cancel path - // (docs/prds/execution-tree-state-machine.md, "Cancellation"): the store + // CancelExecution is the one cancel path: + // the store // records the cancellation -- every non-terminal step of the current // attempt plus the execution's own move to `to` -- in one transaction. // The service then cancels the in-memory context that was delivering the @@ -290,16 +289,15 @@ func (s Service) apply(ctx context.Context, task *Task, actor Actor, action task } // applyApprove is the one approval path, for both the review gate and the -// human-decision waits that predate it (feasibility's PRD handoff). +// human-decision waits that predate it. // // A task carrying a gate offer gets the answer recorded on that offer in the -// guarded response write: the resumed run posts the recorded review filtered -// by the operator's selection, which is the only way "post the findings the -// operator selected" can mean the findings they saw. A task with no gate has -// no review to answer, so the approval is the plain release of waiting work; -// it requeues under the workflow the wait names -- which feasibility sets to -// implement before it waits (docs/prds/pr-review-operator-response.md, -// Decision 1) -- never a name this handler hardcodes. +// guarded response write: the resumed run posts the recorded review filtered by +// the operator's selection, which is the only way "post the findings the +// operator selected" can mean the findings they saw. A task with no gate has no +// review to answer, so the approval is the plain release of waiting work; it +// requeues under the workflow the wait names -- which feasibility sets to +// implement before it waits -- never a name this handler hardcodes. func (s Service) applyApprove(ctx context.Context, task *Task, actor Actor, o outcome, res ActionPayload) (outcome, error) { o.event.Kind, o.event.Detail = approvedKind(actor), actor.describe("approved") gate, ok := workflowtask.DecodeReviewGate(task.ReviewGate) @@ -371,11 +369,8 @@ func selectedFindingKeys(gate workflowtask.ReviewGate, requested []string) ([]st return selection, nil } -// deliver cancels the in-memory context of a run the store has already -// recorded as cancelled. It is the delivery mechanism, never a second store -// write, and it follows the record -- the PRD's order, which the step rows -// make safe: a worker that keeps writing after the record fails -// ErrStaleTransition on its next step write. +// deliver cancels the in-memory context of a run the store has already recorded +// as cancelled. func (s Service) deliver(taskID int64) { if s.CancelTask != nil { s.CancelTask(taskID) diff --git a/internal/domain/workflow/agent.go b/internal/domain/workflow/agent.go index 06c12cea5..9fc1b6b31 100644 --- a/internal/domain/workflow/agent.go +++ b/internal/domain/workflow/agent.go @@ -46,11 +46,10 @@ type AgentStage struct { // OnResult consumes a successful (passed) result. Parked and idle // results park the workflow before OnResult is called. OnResult func(*TaskContext, agentexec.Result) error - // ReviewResult gates agent output before OnResult forwards it to - // human channels. The daemon calls this hook to review stage output - // (issue comments, PR bodies) before human delivery. Return an - // error to block the stage. Nil means pass-through -- no review. - // PRD §1: daemon reviews agent responses before forwarding. + // ReviewResult gates agent output before OnResult forwards it to human + // channels. The daemon calls this hook to review stage output (issue + // comments, PR bodies) before human delivery. Return an error to block the + // stage. Nil means pass-through -- no review. ReviewResult func(*TaskContext, agentexec.Result) error } @@ -315,7 +314,7 @@ func missionWithSkill(tc *TaskContext, mission string) string { } // loadSkillBody loads the SKILL.md body and plugins for the current -// workflow from the worktree's .agents/skills/ directory. Skills declare +// workflow. Skills declare // their workflow in metadata.archie.workflow -- no hardcoded mapping. // When metadata.archie.plugins is non-empty, only the listed plugin files // are loaded in declared order; otherwise all *.go files are globbed. diff --git a/internal/domain/workflow/command_run.go b/internal/domain/workflow/command_run.go index 19bd2f6b0..f8d78013f 100644 --- a/internal/domain/workflow/command_run.go +++ b/internal/domain/workflow/command_run.go @@ -14,14 +14,11 @@ import ( // CommandRunStepName is the step type that runs operator-authored argv in the // task worktree at its position in a stored workflow definition. // -// It is the stage half of the deleted .archie/stages/*.go, and it exists only -// because the maintainer accepted the command-step trust decision -// (archie-core-ndm8): stored control-plane settings already drive argv -// execution -- repository-policies' gate and preflight commands, and -// tool-settings' stdio MCP servers -- so a command step adds no trust tier that -// is not already live. Before that decision the vocabulary PRD said explicitly -// that no command step type would be created to stand in for those files -// (docs/prds/workflow-step-vocabulary.md). +// It is the stage half of the deleted.archie/stages/*.go, and it exists only +// because the maintainer accepted the command-step trust decision: stored +// control-plane settings already drive argv execution -- repository-policies' +// gate and preflight commands, and tool-settings' stdio MCP servers -- so a +// command step adds no trust tier that is not already live. // // It runs where the workflow engine runs, which is the task container: // internal/app/agentworker is the only caller of Run diff --git a/internal/domain/workflow/definition.go b/internal/domain/workflow/definition.go index f280904a1..54308f5ff 100644 --- a/internal/domain/workflow/definition.go +++ b/internal/domain/workflow/definition.go @@ -138,7 +138,7 @@ type ( // ValidateDefinitionCollection rejects malformed, duplicate, or mismatched // definitions, and every workflow.call step a definition carries: the callee // must exist, its inputs must be satisfiable, and the call graph must be -// acyclic (docs/prds/workflow-calls.md). +// acyclic. func ValidateDefinitionCollection(collection WorkflowDefinitionCollection, registry StepRegistry) error { seen := make(map[string]struct{}, len(collection.Definitions)) parsed := make(map[string]YAMLDefinition, len(collection.Definitions)) @@ -198,7 +198,7 @@ func noSettingsFactory(stage Stage) StepFactory { // parses and compiles. var retiredSteps = map[string]Stage{ // The remediate workflow's in-container resume stage moved to daemon - // preparation (archie-core-866m); see retiredResumeStep. + // preparation; see retiredResumeStep. "remediate.resume": retiredResumeStep(), } diff --git a/internal/domain/workflow/feasibility.go b/internal/domain/workflow/feasibility.go index c606485ce..3315d2463 100644 --- a/internal/domain/workflow/feasibility.go +++ b/internal/domain/workflow/feasibility.go @@ -11,14 +11,9 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" ) -// Feasibility is the feature-request workflow: assess the request -// against the project's direction, close it with reasons when it -// doesn't fit, otherwise produce a PRD, post a one-way delivery notice -// on the issue (plus the notify webhook when configured), and hand the -// task to waiting_human. The operator answers in chat or on the -// dashboard -- the decision surfaces -- and the approval requeues the -// feature under the implement workflow or closes it. Routed via the -// "feature" label. +// The operator answers in chat or on the dashboard -- the decision surfaces -- +// and the approval requeues the feature under the implement workflow or closes +// it. Routed via the "feature" label. func Feasibility() Workflow { return Workflow{ Name: "feasibility", @@ -93,20 +88,19 @@ func Feasibility() Workflow { }, }.Stage(), - // Persist the PRD and block on Sam. Messaging and the Web UI are - // the decision surfaces, so the issue gets a one-way delivery - // notice (notify) rather than a reply channel: the wait is - // channel-neutral, and the forge issue is not a chat log. + // Messaging and the Web UI are the decision surfaces, so the issue + // gets a one-way delivery notice (notify) rather than a reply + // channel: the wait is channel-neutral, and the forge issue is not + // a chat log. {Name: "deliver", Run: func(ctx context.Context, tc *TaskContext) error { notify(ctx, tc, "feasibility_prd") - // The approval handoff is a workflow change, not a payload - // the approve handler names: an approval requeues under the + // The approval handoff is a workflow change, not a payload the + // approve handler names: an approval requeues under the // workflow the wait recorded (an empty name keeps the task's), // so the task must name implement before it enters the wait. // Hardcoding "implement" in the handler is how a gate wait on // the standalone pr-review workflow would have re-run the - // implement workflow (docs/prds/pr-review-operator-response.md, - // Decision 1). + // implement workflow. tc.Task.Workflow = "implement" tc.Outcome = Outcome{Status: StatusWaitingHuman, Detail: "PRD delivered, awaiting go/no-go"} return nil @@ -140,12 +134,9 @@ func decideCaptureTools(*TaskContext) []agentexec.CaptureTool { } // notify delivers a human-facing event to the channels a default deployment -// has. A forge-backed task gets a one-way notice on its issue -- the channel -// that always exists when [notify].webhook is unset -- and the webhook is an -// additional push (n8n turns it into an email). Both are best-effort and log -// on failure: the PRD is persisted on the task and rendered by the Web UI, so -// a transport error must not mask the delivery decision or re-run the agent -// stages that produced it. +// has. A forge-backed task gets a one-way notice on its issue -- the channel +// that always exists when [notify].webhook is unset -- and the webhook is an +// additional push (n8n turns it into an email). // // The issue notice is one-way. Messaging and the Web UI are the decision // surfaces; the issue is not a chat log, and notify records no reply cursor @@ -191,9 +182,7 @@ func notify(ctx context.Context, tc *TaskContext, kind string) { } // deliveryNotice is the body of the one-way notice notify posts on a -// forge-backed task's issue. It carries the PRD because the issue is the -// durable record of the request, and points at the decision surfaces so the -// notice is not read as an invitation to reply there. +// forge-backed task's issue. func deliveryNotice(tc *TaskContext, kind string) string { subject := "archie finished a run that needs you" if kind == "feasibility_prd" { diff --git a/internal/domain/workflow/gate_environment.go b/internal/domain/workflow/gate_environment.go index 56dccfe1b..f8e48beaf 100644 --- a/internal/domain/workflow/gate_environment.go +++ b/internal/domain/workflow/gate_environment.go @@ -20,7 +20,7 @@ import ( // - the combined output names host infrastructure the gate needs and does // not have, such as a Docker daemon the test harness spawns containers on. // These are the phrasings the tools themselves emit when their dependency -// is absent (archie-core-71mq), not an inference drawn from the exit +// is absent, not an inference drawn from the exit // status. // // The second signal is deliberately a closed, literal set: a marker is added @@ -80,7 +80,7 @@ func baselineEnvironmentError(argv []string, out, cause string) error { // baselineFixFailedError is the park reason for every failure after the // baseline repair agent was dispatched. A failure that names only the agent -- // a provider 402, say -- and drops the gate output leaves the operator with no -// way to see why the gate was red in the first place (archie-core-rwy6). +// way to see why the gate was red in the first place. func baselineFixFailedError(argv []string, out, cause string) error { return fmt.Errorf("baseline red -- %s fails and the baseline-fix builder did not repair it: %s\n\ngate output:\n%s", strings.Join(argv, " "), cause, clipTail(out, baselineParkOutputBytes)) diff --git a/internal/domain/workflow/implement.go b/internal/domain/workflow/implement.go index 6f73b01dd..f588ff892 100644 --- a/internal/domain/workflow/implement.go +++ b/internal/domain/workflow/implement.go @@ -57,7 +57,6 @@ func stageBaselineGateRun(ctx context.Context, tc *TaskContext) error { // not have -- is not a pre-existing code defect: no repair agent in // the worktree can fix it. Park with the cause and the output rather // than spend a run budget on a builder that cannot succeed - // (archie-core-rwy6). if cause := gateEnvironmentCause(string(out), err); cause != "" { return baselineEnvironmentError(argv, string(out), cause) } @@ -159,8 +158,6 @@ func Implement() Workflow { Mission: func(tc *TaskContext) string { prd := "" if tc.Task.Plan != "" { - // An approved feasibility PRD precedes this run; - // the plan refines it rather than starting cold. prd = "\n\n" + tc.Task.Plan + "\n\n" } return fmt.Sprintf( @@ -224,12 +221,7 @@ func Implement() Workflow { // -- most of it is typically prefix-cache hits billed at a steep discount, // not full price. // -// This used to also append the adversarial self-review's findings section -// (now superseded by docs/prds/pr-review-agent.md). archie-core-afbk.7 -// removed the old review stage; hooking the new pr-review pipeline in as -// this workflow's "archie's own PRs" trigger is tracked separately (see the -// bead's continuation comment) rather than guessed at here, since it needs -// the same stage-loop-around-StageOpenPR investigation that bead flagged. +// This used to also append the adversarial self-review's findings section. func implementPRBody(tc *TaskContext) string { return fmt.Sprintf("%s\n\n---\n*workflow: implement · %d iterations · %s*", tc.BuildSummary, tc.Task.Iterations, formatTokenUsage(tc.Task.TokensUsed, tc.RunUsage)) diff --git a/internal/domain/workflow/outputs.go b/internal/domain/workflow/outputs.go index bd8aed7ce..f0c4f0361 100644 --- a/internal/domain/workflow/outputs.go +++ b/internal/domain/workflow/outputs.go @@ -12,7 +12,7 @@ import ( ) // Declared workflow outputs: how a run writes one and how a wait:true caller -// publishes one (docs/prds/workflow-call-outputs.md). A run's only structured +// publishes one. A run's only structured // results are capture calls, so declared outputs ride the capture path: each // is offered to the run's agent stages as a capture tool named after it, and // the engine applies, validates, publishes and persists the accepted values. diff --git a/internal/domain/workflow/prreview/bench/bench.go b/internal/domain/workflow/prreview/bench/bench.go index 51d0cb3c2..8faddd109 100644 --- a/internal/domain/workflow/prreview/bench/bench.go +++ b/internal/domain/workflow/prreview/bench/bench.go @@ -2,7 +2,6 @@ // real defects are known: each problem's golden comments. A reviewer produces // findings, the deterministic core turns them into the comments a review would // post, and an independent judge decides which golden each comment catches. -// See docs/prds/pr-review-agent.md, Verification. package bench import ( diff --git a/internal/domain/workflow/prreview/budget.go b/internal/domain/workflow/prreview/budget.go index 024b27c04..e49e5d649 100644 --- a/internal/domain/workflow/prreview/budget.go +++ b/internal/domain/workflow/prreview/budget.go @@ -2,11 +2,9 @@ package prreview import "time" -// Budget bounds a pr-review run's total cost (tokens, the only spend the -// agent runtime accounts for) and wall-clock, split evenly across every -// budget-tracked phase (docs/prds/pr-review-agent.md, Budget: "A run has a -// cost cap and a wall-clock cap, split into per-phase shares"). Zero -// disables that dimension. +// Budget bounds a pr-review run's total cost (tokens, the only spend the agent +// runtime accounts for) and wall-clock, split evenly across every +// budget-tracked phase. Zero disables that dimension. type Budget struct { MaxTokens int WallClock time.Duration diff --git a/internal/domain/workflow/prreview/coverage.go b/internal/domain/workflow/prreview/coverage.go index 90f7722ef..3c43fe7d8 100644 --- a/internal/domain/workflow/prreview/coverage.go +++ b/internal/domain/workflow/prreview/coverage.go @@ -1,9 +1,5 @@ package prreview -// CoverageGaps returns the clusters with no finding pointing at any of their -// files, and the high-exposure blast-radius files no finding points at -// either: the two things phase 6's coverage gate checks (docs/prds/ -// pr-review-agent.md, phase 6). func CoverageGaps(clusters []Cluster, highExposure []string, findings []Finding) (uncoveredClusters []Cluster, uncoveredFiles []string) { reviewed := make(map[string]bool, len(findings)) for _, f := range findings { @@ -30,10 +26,8 @@ func CoverageGaps(clusters []Cluster, highExposure []string, findings []Finding) } // ClusterFindings groups findings by the cluster whose files contain them, -// keyed by cluster ID. Phase 5's compound-defect check runs once per cluster -// with more than one confirmed finding, because a compound defect is a -// property of findings that share a place, not of the whole PR. A finding -// whose file belongs to no cluster contributes to none. +// keyed by cluster ID. A finding whose file belongs to no cluster contributes +// to none. func ClusterFindings(clusters []Cluster, findings []Finding) map[string][]Finding { fileToCluster := make(map[string]string, len(findings)) for _, cluster := range clusters { diff --git a/internal/domain/workflow/prreview/diff.go b/internal/domain/workflow/prreview/diff.go index edfee3c71..da6303e17 100644 --- a/internal/domain/workflow/prreview/diff.go +++ b/internal/domain/workflow/prreview/diff.go @@ -103,8 +103,7 @@ type DiffStats struct { FilesRenamed int FilesTypeChanged int TestFilesChanged int - // TestToCodeRatio is changed test files per changed non-test file. A - // change that touches no non-test file reports its own test count rather + // A change that touches no non-test file reports its own test count rather // than dividing by zero. TestToCodeRatio float64 } diff --git a/internal/domain/workflow/prreview/dimension.go b/internal/domain/workflow/prreview/dimension.go index c627b638d..4eee677c9 100644 --- a/internal/domain/workflow/prreview/dimension.go +++ b/internal/domain/workflow/prreview/dimension.go @@ -5,9 +5,6 @@ import ( "slices" ) -// Dimension is one review dimension a lens proposed: a name, a reviewer -// prompt written for this PR, the files the reviewer must read, and a -// priority phase 3 ranks dimensions by when the depth's cap forces a cut. type Dimension struct { Name string Prompt string @@ -50,10 +47,8 @@ func MergeDimensions(lensOutputs [][]Dimension, limit int) []Dimension { return merged } -// HallucinationDimension is the extra review dimension phase 3 adds for a PR -// intake scores as likely machine-written: claims, citations and behaviour -// the diff does not actually implement. Returns nil at or below -// AIGeneratedThreshold -- a coin-flip is not evidence, so it is not added. +// Returns nil at or below AIGeneratedThreshold -- a coin-flip is not evidence, +// so it is not added. func HallucinationDimension(aiGenerated float64) *Dimension { if aiGenerated <= AIGeneratedThreshold { return nil diff --git a/internal/domain/workflow/prreview/intake.go b/internal/domain/workflow/prreview/intake.go index 22b5ddada..ae2d0fc02 100644 --- a/internal/domain/workflow/prreview/intake.go +++ b/internal/domain/workflow/prreview/intake.go @@ -1,7 +1,7 @@ package prreview // Depth is how many review dimensions a run affords, driven by the size of -// the change (docs/prds/pr-review-agent.md, phase 1). +// the change. type Depth string const ( @@ -10,8 +10,6 @@ const ( DepthDeep Depth = "deep" ) -// The line-count boundaries phase 1 classifies depth from: under 100 is -// quick, under 500 is standard, otherwise deep. const ( quickLinesCeiling = 100 standardLinesCeiling = 500 @@ -51,9 +49,7 @@ func MaxDimensionsFor(depth Depth) int { } } -// ResolveDepth applies the PRD's override rule: an operator-set depth wins -// over the line-count classification. An empty explicit depth means no -// override was given. +// An empty explicit depth means no override was given. func ResolveDepth(changedLines int, explicit Depth) Depth { if explicit != "" { return explicit diff --git a/internal/domain/workflow/prreview/scoring.go b/internal/domain/workflow/prreview/scoring.go index 507f9c9af..7f9dd8c4a 100644 --- a/internal/domain/workflow/prreview/scoring.go +++ b/internal/domain/workflow/prreview/scoring.go @@ -82,12 +82,9 @@ type Finding struct { LineStart int LineEnd int Severity Severity - // Category is what the finding is about, and the third of the three things - // two findings have to share to be one claim: the PRD merges exact - // duplicates on (file, overlapping lines, category). No producer sets it - // yet, so an empty category is a category -- two findings that both leave - // it empty are duplicates of each other when they also share a file and a - // line. + // No producer sets it yet, so an empty category is a category -- two + // findings that both leave it empty are duplicates of each other when they + // also share a file and a line. Category string Title string Body string @@ -127,11 +124,7 @@ type ScoredFinding struct { Score float64 Multipliers []string Blocking bool - // Adversary carries phase 5's verdict through synthesis, so a caller - // deciding whether a blocking finding was ever challenged (the pr-review - // PRD's archie's-own-PR trigger rule) does not have to cross-reference - // back into the pre-synthesis Finding slice. - Adversary AdversaryVerdict + Adversary AdversaryVerdict } // ScoreInputs is the run context that moves every finding's score. @@ -185,10 +178,7 @@ func Score(findings []Finding, inputs ScoreInputs) []ScoredFinding { } // mergeDuplicates collapses the findings that are one claim about one place. -// Two findings are one claim when they name the same file and category and -// their line ranges overlap -- the PRD's exact-duplicate rule, with the wording -// and the severity left out of it. Overlap is transitive, so a chain 1-2, 2-3, -// 3-4 is one claim and not two. +// Overlap is transitive, so a chain 1-2, 2-3, 3-4 is one claim and not two. func mergeDuplicates(findings []ScoredFinding) []ScoredFinding { ordered := slices.Clone(findings) slices.SortFunc(ordered, compareIdentity) @@ -427,10 +417,6 @@ func IsAIGenerated(confidence float64) bool { return confidence > AIGeneratedThreshold } -// IsHighPriority reports whether a finding's severity is high enough for -// phase 5's evidence verifier to check it against its evidence package: a -// hallucinated nitpick costs a reader little, a hallucinated critical costs -// them a debugging session chasing a defect that was never there. func IsHighPriority(f Finding) bool { switch normalizeSeverity(f.Severity) { case SeverityCritical, SeverityImportant: diff --git a/internal/domain/workflow/prreview_headless.go b/internal/domain/workflow/prreview_headless.go index eed48f4e4..361b82ec0 100644 --- a/internal/domain/workflow/prreview_headless.go +++ b/internal/domain/workflow/prreview_headless.go @@ -8,9 +8,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/workflow/prreview" ) -// ReviewPullRequest runs the same decision phases as PRReview through its -// merge gate, without phase 9 or any forge writes. The caller supplies a fresh -// context with operator approval disabled. +// The caller supplies a fresh context with operator approval disabled. type PRReviewDecision struct { Comments []prreview.ScoredFinding SkippedPhases []string diff --git a/internal/domain/workflow/prreview_own_pr.go b/internal/domain/workflow/prreview_own_pr.go index 15ad14047..c760fae31 100644 --- a/internal/domain/workflow/prreview_own_pr.go +++ b/internal/domain/workflow/prreview_own_pr.go @@ -8,13 +8,10 @@ import ( "github.com/samcharles93/archie-core/internal/domain/workflow/prreview" ) -// localPRSource implements PRSource against the task's own worktree instead -// of an external forge fetch: archie's own PRs trigger (docs/prds/pr-review- -// agent.md, Triggers: "the implement workflow runs the pipeline before -// opening its PR") reviews a change that has no PR number yet, so there is -// nothing for a forge-backed PRSource to fetch by. Trees already holds -// everything the pipeline's phase 1/2 need: the diff against base, and a -// snapshot of the (as yet unopened) PR's head. +// localPRSource implements PRSource against the task's own worktree instead of +// an external forge fetch: archie's own PRs trigger reviews a change that has +// no PR number yet, so there is nothing for a forge-backed PRSource to fetch +// by. type localPRSource struct { tc *TaskContext } @@ -68,9 +65,8 @@ const parkDetailBytes = 4000 // unchallengedBlockingFindings returns the scored findings the merge gate // marked blocking that the adversary did not challenge -- confirmed or never -// reviewed by the adversary both count, since only an explicit challenge -// argues the finding away (docs/prds/pr-review-agent.md, Triggers: "archie's -// own PRs"). +// reviewed by the adversary both count, since only an explicit challenge argues +// the finding away. func unchallengedBlockingFindings(scored []prreview.ScoredFinding) []prreview.ScoredFinding { var out []prreview.ScoredFinding for _, f := range scored { @@ -97,7 +93,7 @@ func renderBlockingFindingsDetail(findings []prreview.ScoredFinding) string { // StagePRReviewAndOpenPR runs the pr-review pipeline's decision phases (1-8) // against the task's own uncommitted change, then opens the PR body builds // and posts the pipeline's advisory findings against it -- archie's own PRs -// trigger (docs/prds/pr-review-agent.md, Triggers). An unchallenged blocking +// trigger. An unchallenged blocking // finding parks the task with the findings instead of opening a PR; a // pipeline stage failure parks the task the same way any other stage failure // does. Once the PR is open, posting failure is logged and does not revert @@ -108,7 +104,7 @@ func renderBlockingFindingsDetail(findings []prreview.ScoredFinding) string { // to the standalone pr-review workflow, where an operator's response // re-reviews a pull request that already exists to post to. This trigger // reviews a change with no PR and no place to post yet, so a wait here would -// end the implement run before its PR was opened (archie-core-7nst). +// end the implement run before its PR was opened. // // This must run every decision stage from inside one Stage.Run body rather // than as separate Stage entries in the workflow's list: the engine ends a diff --git a/internal/domain/workflow/prreview_stages.go b/internal/domain/workflow/prreview_stages.go index 7bce421f4..1e82181d4 100644 --- a/internal/domain/workflow/prreview_stages.go +++ b/internal/domain/workflow/prreview_stages.go @@ -18,19 +18,16 @@ import ( ) // PRSource fetches a pull request under review: its descriptive content, its -// diff, and a read-only, .git-free snapshot of its head. It is Trees' +// diff, and a read-only,.git-free snapshot of its head. It is Trees' // counterpart for the pr-review workflow -- Trees reaches the task's own -// worktree, which the pipeline must never read (docs/prds/pr-review-agent.md, -// Isolation); PRSource reaches the arbitrary pull request named by -// Task.Owner/Repo/PRNumber instead, and carries no push credential. +// worktree, which the pipeline must never read; PRSource reaches the arbitrary +// pull request named by Task.Owner/Repo/PRNumber instead, and carries no push +// credential. // // The real forge-backed implementation belongs to whichever bead wires -// pr-review's triggers (archie-core-afbk.7); this bead builds and tests the +// pr-review's triggers; this bead builds and tests the // Stage wiring against a fake. type PRSource interface { - // Metadata returns the pull request's title, body and commit messages -- - // phase 1's "PR metadata" and phase 3's hallucination-check dimension's - // "what the PR claims". Metadata(ctx context.Context, owner, repo string, number int) (PRMetadata, error) // Diff returns the pull request's unified diff against its base branch. Diff(ctx context.Context, owner, repo string, number int) (string, error) @@ -58,13 +55,9 @@ type prReviewState struct { depth prreview.Depth aiGenerated float64 - snapshotDir string - headSHA string - blastRadius []string - // clusters and highExposure are phase 6's coverage-gate inputs, computed - // once in anatomy alongside blastRadius: clusters groups changed files by - // directory, highExposure is the blastRadius files more than one changed - // file reaches. + snapshotDir string + headSHA string + blastRadius []string clusters []prreview.Cluster highExposure []string @@ -75,48 +68,33 @@ type prReviewState struct { reviewerFailures atomic.Int64 // operatorInstructions is the re-review's instructions, restored from the - // task's review_gate document at intake. Phase 3's lens missions and phase - // 4's reviewer missions append it as one labelled block - // (docs/prds/pr-review-operator-response.md, Decision 3); nothing else - // reads it, so a first run -- or any run the operator did not instruct -- - // leaves every other mission untouched. + // task's review_gate document at intake. operatorInstructions string // approvedReview is the review the operator approved, restored from the - // task's review_gate document at intake. When set, this run IS the - // approve resume: the gate must not wait a second time, and phase 9 posts - // the recorded review filtered by the operator's selection rather than - // the review the resumed phases recomputed. The resumed pipeline has no + // task's review_gate document at intake. The resumed pipeline has no // partway resume, so the recomputed findings are unavoidable; not posting // them is what makes "the findings the operator selected" true. approvedReview *task.ReviewGate - // findingsMu guards findings during phase 6, where the coverage gate and - // consistency verification append to it from two goroutines running in - // parallel (docs/prds/pr-review-agent.md, phase 6). Every other phase - // touches findings from a single goroutine and does not need it. + // Every other phase touches findings from a single goroutine and does not + // need it. findingsMu sync.Mutex - // runStart is when phase 1 started, the origin every budget-share check - // measures elapsed wall-clock against. runStart time.Time // tokensSpent is the run's cumulative token spend so far, across every // agent call any phase has made. It is an atomic because phases 3, 4 and // 9 add to it from concurrent goroutines. tokensSpent atomic.Int64 - // skippedPhases names every phase a budget check skipped, in the order - // they were skipped, so phase 9's output can report them (docs/prds/ - // pr-review-agent.md, Budget: "The posted review names every skipped - // phase, so an exhausted run never reads as a clean one"). Every phase - // runs sequentially in the workflow engine's stage loop, so appends here - // need no lock. + // Every phase runs sequentially in the workflow engine's stage loop, so + // appends here need no lock. skippedPhases []string } -// prReviewTotalBudget bounds the whole pr-review run's cost (tokens, the -// only spend the agent runtime accounts for) and wall-clock, split evenly -// across prReviewBudgetPhases in pipeline order (docs/prds/pr-review-agent.md, -// Budget section). Sized generously: exhausting it is meant to catch a run -// that is genuinely stuck or unexpectedly expensive, not a typical one. +// prReviewTotalBudget bounds the whole pr-review run's cost (tokens, the only +// spend the agent runtime accounts for) and wall-clock, split evenly across +// prReviewBudgetPhases in pipeline order. Sized generously: exhausting it is +// meant to catch a run that is genuinely stuck or unexpectedly expensive, not a +// typical one. var prReviewTotalBudget = prreview.Budget{MaxTokens: 2_000_000, WallClock: 30 * time.Minute} // prReviewBudgetPhases are the budget-tracked phases, in pipeline order. @@ -152,23 +130,13 @@ func skipPhase(tc *TaskContext, phase string) { } // prReviewConcurrency bounds phases 3 (lenses), 4 (reviewers) and 9 (polish), -// all "in parallel, at most 8 at a time" per the PRD except phase 3, which +// all "in parallel, at most 8 at a time" // never has more than three lenses to begin with. const prReviewConcurrency = 8 -// PRReview is the pull request reviewer: a fixed pipeline, not a single -// agent (docs/prds/pr-review-agent.md). archie-core-afbk.3 wired phases 1, 2, -// 3, 4, 7 and 9; archie-core-afbk.4 added 5 and 6 (verification, -// coverage/consistency); archie-core-afbk.5 added phase 8 (the merge gate) -// and the budget shares/skipped-phase reporting that run throughout; -// archie-core-afbk.8 adds the precision dial (between review and -// verification) and the operator-approval gate (between synthesis and the -// merge gate), both off by default and each gated by its own config flag. -// -// The operator-approval gate is this workflow's OWN stage-list entry, not a -// shared one (docs/prds/pr-review-operator-response.md): the implement -// workflow splices the shared decision stages, and a gate there would end an -// implement run before its PR exists. +// PRReview is the pull request reviewer, a fixed pipeline of stages. The +// precision gate and operator approval are optional, each behind its own +// config flag. func PRReview() Workflow { return Workflow{ Name: "pr-review", @@ -188,25 +156,16 @@ func PRReview() Workflow { } } -// prReviewDecisionStages is phases 1 through 8: everything up to and -// including the merge gate's blocking/advisory verdict, but before phase 9 -// posts anything, and WITHOUT the operator-approval gate. Split out from -// PRReview so the implement workflow can splice it in before StageOpenPR -// (archie-core-afbk.7's "archie's own PRs" trigger) -- and so the operator -// gate can never ride along on that splice -// (docs/prds/pr-review-operator-response.md, "The gate is not reachable from -// archie's own PRs"): there the gate's question (which findings to post) has -// no pull request to post to yet, and a park would end the implement run -// before it opened one (archie-core-7nst). +// Split out from PRReview so the implement workflow can splice it in before +// StageOpenPR +// -- and so the operator +// gate can never ride along on that splice: there the gate's question (which +// findings to post) has no pull request to post to yet, and a park would end +// the implement run before it opened one. func prReviewDecisionStages() []Stage { return append(prReviewPipelineStages(), stagePRMergeGate()) } -// prReviewStandaloneStages is the standalone pr-review workflow's full stage -// list: the shared decision phases with the operator-approval gate inserted -// between synthesis and the merge gate -- the gate runs before the merge -// gate's verdict, so an operator's re-review never has to undo one computed -// on a since-changed finding set -- followed by phase 9's posting. func prReviewStandaloneStages() []Stage { pipeline := prReviewPipelineStages() stages := make([]Stage, 0, len(pipeline)+3) @@ -229,9 +188,6 @@ func prReviewPipelineStages() []Stage { } } -// stagePRIntake is pipeline phase 1: PR metadata and diff statistics, the -// depth they classify, and the machine-written confidence phase 3's -// hallucination-check dimension and phase 7's scoring both read. func stagePRIntake() Stage { return Stage{Name: "intake", Run: func(ctx context.Context, tc *TaskContext) error { if tc.PRSource == nil { @@ -292,13 +248,7 @@ func stagePRIntake() Stage { }} } -// scoreAIGenerated runs phase 1's classification-role call: how confident an -// agent is that the PR's own description reads as machine-written, which -// phase 3's hallucination-check dimension and phase 7's scoring both use. func scoreAIGenerated(ctx context.Context, tc *TaskContext, meta PRMetadata) (float64, error) { - // This call reads no files -- only the metadata already in its mission -- - // so it gets its own empty scratch directory rather than the pull - // request's snapshot, which does not exist yet at phase 1. scratch, err := os.MkdirTemp("", "pr-review-intake-*") if err != nil { return 0, fmt.Errorf("create intake scratch directory: %w", err) @@ -347,7 +297,6 @@ func scoreAIGenerated(ctx context.Context, tc *TaskContext, meta PRMetadata) (fl // run's scratch state at intake: the instructions a re-review must carry into // phases 3 and 4, and the approved review an approve resume must post. Called // once, where the review the run works on is established -// (docs/prds/pr-review-operator-response.md, Decision 3). func restoreReviewGate(tc *TaskContext) { gate, ok := task.DecodeReviewGate(tc.Task.ReviewGate) if !ok { @@ -360,10 +309,8 @@ func restoreReviewGate(tc *TaskContext) { } } -// operatorInstructionsBlock renders the re-review's operator instructions as -// the labelled block phase 3's and phase 4's missions carry. It is empty -- -// and therefore absent -- on a run the operator did not instruct, which is -// what keeps "a first run's do not" true. +// It is empty -- and therefore absent -- on a run the operator did not +// instruct, which is what keeps "a first run's do not" true. func operatorInstructionsBlock(tc *TaskContext) string { if tc.prReview == nil || tc.prReview.operatorInstructions == "" { return "" @@ -372,9 +319,6 @@ func operatorInstructionsBlock(tc *TaskContext) string { "previous findings. Address them in your work:\n" + tc.prReview.operatorInstructions + "\n\n" } -// stagePRAnatomy is pipeline phase 2: the read-only snapshot every later -// phase reads from, the deterministic clustering and blast radius, and one -// agent's narrative of the change. func stagePRAnatomy() Stage { return Stage{Name: "anatomy", Run: func(ctx context.Context, tc *TaskContext) error { dir, err := os.MkdirTemp("", fmt.Sprintf("pr-review-snapshot-task%d-*", tc.Task.ID)) @@ -426,8 +370,8 @@ func stagePRAnatomy() Stage { }} } -// prReviewLenses are phase 3's three fixed lenses. Each proposes review -// dimensions from a different angle; code merges, dedups and caps the result. +// Each proposes review dimensions from a different angle; code merges, dedups +// and caps the result. var prReviewLenses = []struct { name string prompt string @@ -437,11 +381,8 @@ var prReviewLenses = []struct { {name: "fit", prompt: "patterns, complexity, abstraction, test adequacy, documentation that no longer matches, dependencies, migration completeness"}, } -// stagePRLenses is pipeline phase 3: three lens agents proposing review -// dimensions in parallel, merged with the hallucination-check dimension (for -// a likely machine-written PR) as one more candidate, deduplicated and -// capped by code. The hallucination dimension competes for the same cap as -// everything else -- "at most N dimensions" is a total, not a total plus one +// The hallucination dimension competes for the same cap as everything else -- +// "at most N dimensions" is a total, not a total plus one // -- so it is added before MergeDimensions cuts the tail, never after. func stagePRLenses() Stage { return Stage{Name: "lenses", Run: func(ctx context.Context, tc *TaskContext) error { @@ -534,12 +475,10 @@ func runLens(ctx context.Context, tc *TaskContext, name, angle string) ([]prrevi return out, nil } -// stagePRReview is pipeline phase 4: one reviewer call per dimension, at most -// prReviewConcurrency at a time. A reviewer that exhausts its turn cap or -// deadline before its terminal tool call records StepFailed -- distinct from -// StepSucceeded for a reviewer that completed and found nothing -- so -// synthesis and the posted review can tell "unreviewed" from "reviewed-clean" -// (docs/prds/pr-review-agent.md, phase 4). +// A reviewer that exhausts its turn cap or deadline before its terminal tool +// call records StepFailed -- distinct from StepSucceeded for a reviewer that +// completed and found nothing -- so synthesis and the posted review can tell +// "unreviewed" from "reviewed-clean" func stagePRReview() Stage { return Stage{Name: "review", Run: func(ctx context.Context, tc *TaskContext) error { if budgetExhausted(tc, "review") { @@ -590,9 +529,6 @@ func runReviewer(ctx context.Context, tc *TaskContext, dim prreview.Dimension) [ return findings } -// reportFindingsSchema is the finding shape every pr-review agent call that -// reports findings captures them in: phase 4's reviewer, phase 6's gap -// reviewers (which reuse runReviewer directly) and consistency verification. var reportFindingsSchema = json.RawMessage(`{ "type": "object", "properties": { @@ -674,14 +610,13 @@ func decodeReportedFindings(calls []json.RawMessage, dimension string) ([]prrevi const prReviewMaxSteps = 25 // runReviewerAgent runs one phase-4 reviewer call and records its child step -// with the phase-4 status distinction (docs/prds/pr-review-agent.md, phase -// 4): StepFailed for a reviewer that exhausted its turn cap or deadline -// before its terminal tool call, StepSucceeded for one that reached it -- -// whether or not it reported any findings. tc.RunAgentChild does not serve -// this: it maps only the Go error, so a "parked" (turn-cap/deadline) result -// with no Go error would record StepSucceeded exactly like a clean, -// zero-findings run, and the two would be indistinguishable to anything -// reading the execution tree afterwards. +// with the phase-4 status distinction: StepFailed for a reviewer that exhausted +// its turn cap or deadline before its terminal tool call, StepSucceeded for one +// that reached it -- whether or not it reported any findings. tc.RunAgentChild +// does not serve this: it maps only the Go error, so a "parked" +// (turn-cap/deadline) result with no Go error would record StepSucceeded +// exactly like a clean, zero-findings run, and the two would be +// indistinguishable to anything reading the execution tree afterwards. func runReviewerAgent( ctx context.Context, tc *TaskContext, name, mission string, captureTools []agentexec.CaptureTool, ) (agentexec.Result, error) { @@ -717,11 +652,6 @@ func runReviewerAgent( return res, runErr } -// stagePRSynthesis is pipeline phase 7, code only: score, drop findings -// under their severity's confidence floor, merge duplicates, rank, and cap -// at the inline comment limit. Phase 8 (the merge gate) runs after this -// stage, so every surviving finding's Blocking flag is still whatever phase -// 5/6 left it as (false, since neither sets it) until that stage decides. func stagePRSynthesis() Stage { return Stage{Name: "synthesis", Run: func(_ context.Context, tc *TaskContext) error { scored := prreview.Score(tc.prReview.findings, prreview.ScoreInputs{ @@ -733,12 +663,9 @@ func stagePRSynthesis() Stage { }} } -// stagePROutput is pipeline phase 9: one polish call per comment, at most -// prReviewConcurrency at a time, keeping the original wording on failure, -// then posting the surviving inline-anchored findings as one forge review. -// The polish pass is what a budget-exhausted run skips; posting itself -// always runs, since it is the pipeline's only externally visible act and -// must report what happened even when every other phase was skipped. +// The polish pass is what a budget-exhausted run skips; posting itself always +// runs, since it is the pipeline's only externally visible act and must report +// what happened even when every other phase was skipped. // // Used by the standalone pr-review workflow only. Archie's own PRs trigger // (StagePRReviewAndOpenPR, prreview_own_pr.go) needs the same polish-then-post @@ -755,16 +682,10 @@ func stagePROutput() Stage { }} } -// runPROutputPhase is phase 9's actual work, factored out of stagePROutput so -// a caller that must preserve its own outcome (archie's own PRs, which has -// already set StatusPROpen by the time findings are ready to post) can run it -// without stagePROutput's unconditional StatusCompleted assignment. -// // An approve resume posts the recorded review the operator answered, not the // one this run recomputed: the engine has no partway resume, so the resumed -// phases recompute every finding, and only the recorded document is the -// review the operator saw (docs/prds/pr-review-operator-response.md, "The -// review the operator answers"). +// phases recompute every finding, and only the recorded document is the review +// the operator saw. func runPROutputPhase(ctx context.Context, tc *TaskContext) (string, error) { if approved := tc.prReview.approvedReview; approved != nil { return postApprovedReview(ctx, tc, *approved) @@ -790,7 +711,7 @@ func runPROutputPhase(ctx context.Context, tc *TaskContext) (string, error) { } // polishFinding runs one phase-9 polish call, tightening a finding's wording. -// It keeps the original finding unchanged on any failure, per the PRD. +// It keeps the original finding unchanged on any failure. func polishFinding(ctx context.Context, tc *TaskContext, f prreview.ScoredFinding) prreview.ScoredFinding { params := json.RawMessage(`{ "type": "object", @@ -842,14 +763,7 @@ func postApprovedReview(ctx context.Context, tc *TaskContext, gate task.ReviewGa } // reviewComments renders every line-anchored finding as one forge review -// comment. A finding with no line (LineStart <= 0) is dropped rather than -// posted anywhere -- docs/prds/inline-review.md's PR-body fallback list for -// whole-file findings, and REQUEST_CHANGES vs COMMENT event submission -// (workflow.Forger.CreateReviewComments always posts a COMMENT-state -// review; GitHub's implementation does not submit a review object at all, -// only per-comment calls, so REQUEST_CHANGES needs a Forger/forge change, -// not just a caller change here) are both real gaps this bead does not -// close; see the follow-up bead this bead's commit files. +// comment. Findings with no line are dropped. func reviewComments(findings []prreview.ScoredFinding) []ReviewComment { comments := make([]ReviewComment, 0, len(findings)) for _, f := range findings { @@ -926,11 +840,8 @@ func runPRReviewAgentRecorded( return res, err } -// forEachBounded runs fn(0), fn(1), ..., fn(n-1), at most limit at a time, -// and waits for all of them. It is phase 3, 4 and 9's shared concurrency -// bound: tc.RunAgentChild already supports concurrent fan-out from inside -// one stage body (each call independently records a StepExecution child), so -// this needs only a semaphore, not an engine change. +// forEachBounded runs fn(0) through fn(n-1), at most limit at a time, and waits +// for all of them. func forEachBounded(limit, n int, fn func(i int)) { if n == 0 { return diff --git a/internal/domain/workflow/prreview_stages_verify.go b/internal/domain/workflow/prreview_stages_verify.go index 015536e01..d0470b0f2 100644 --- a/internal/domain/workflow/prreview_stages_verify.go +++ b/internal/domain/workflow/prreview_stages_verify.go @@ -13,12 +13,6 @@ import ( "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) -// stagePRVerification is pipeline phase 5, over the review findings phase 4 -// produced: extract each finding's evidence package (code), check the -// high-priority findings against theirs (an evidence verifier agent), have -// an adversary confirm or challenge every finding and add anything every -// reviewer missed, then flag within-cluster compound defects -// (docs/prds/pr-review-agent.md, phase 5). func stagePRVerification() Stage { return Stage{Name: "verification", Run: func(ctx context.Context, tc *TaskContext) error { if len(tc.prReview.findings) == 0 { @@ -45,13 +39,9 @@ func stagePRVerification() Stage { }} } -// stagePRPrecisionGate is the PRD's Precision dial: an optional -// post-worthiness pass, active only when review.precision_gate is set, -// between phase 4 (review) and phase 5 (verification). It keeps every -// concrete, evidenced defect and drops nitpicks, style and unverifiable -// claims, keeping a finding when unsure -- trading recall for precision and -// cutting verification cost by filtering early. It is off by default: the -// pipeline is recall-first. +// stagePRPrecisionGate, when review.precision_gate is set, drops nitpicks, +// style and unverifiable claims between review and verification, keeping a +// finding when unsure. Off by default. func stagePRPrecisionGate() Stage { return Stage{Name: "precision-gate", Run: func(ctx context.Context, tc *TaskContext) error { if !tc.Cfg.Review.PrecisionGate || len(tc.prReview.findings) == 0 { @@ -143,28 +133,9 @@ func runPrecisionGate(ctx context.Context, tc *TaskContext, findings []prreview. return kept } -// stagePROperatorApproval is the PRD's Operator approval gate: active only -// when review.approve_before_post is set, it runs immediately after -// synthesis and before the merge gate, so an operator's re-review (which -// reruns phases 3 to 8 with instructions folded in) never has to undo a -// merge-gate verdict computed on a since-changed finding set. A review with -// no findings never waits, per the PRD, and continues straight to the merge -// gate. Setting tc.Outcome here ends the workflow run at this stage -- -// docs/prds/execution-tree-state-machine.md's engine loop stops as soon as a -// stage sets a non-empty Outcome.Status -- so the merge gate and output -// stages never run until an operator's response requeues the task. -// -// Before it waits, the gate records the review it is holding on the task's -// review_gate column: the scored findings, the head SHA, the pull request's -// identity and the workflow the wait resumes. The recorded document is what -// makes the operator's answer mean the review they saw -- the engine cannot -// resume a run partway, so a resumed pipeline recomputes its findings with -// agent calls (docs/prds/pr-review-operator-response.md, "The review the -// operator answers"). -// -// An approve resume is the same run re-entered: its review_gate carries the -// answer already, so the gate must not wait a second time -- it continues to -// the merge gate and output, where the recorded review posts. +// stagePROperatorApproval, when review.approve_before_post is set, waits for +// operator approval after synthesis and before the merge gate. A review with no +// findings never waits. Setting tc.Outcome ends the run at this stage. func stagePROperatorApproval() Stage { return Stage{Name: "operator-approval", Run: func(_ context.Context, tc *TaskContext) error { if !tc.Cfg.Review.ApproveBeforePost || len(tc.prReview.scored) == 0 { @@ -189,11 +160,9 @@ func stagePROperatorApproval() Stage { }} } -// evidencePackageFor extracts a finding's evidence package from the -// snapshot, reusing afbk.1's ExtractEvidence. A file the snapshot no longer -// has (a finding pointing at a path that does not exist) extracts an empty -// package rather than failing the stage: that emptiness is itself the -// evidence verifier's answer. +// A file the snapshot no longer has (a finding pointing at a path that does not +// exist) extracts an empty package rather than failing the stage: that +// emptiness is itself the evidence verifier's answer. func evidencePackageFor(tc *TaskContext, f prreview.Finding) prreview.EvidencePackage { pkg, err := prreview.ExtractEvidence(os.DirFS(tc.prReview.snapshotDir), prreview.EvidenceRequest{ File: f.File, LineStart: f.LineStart, LineEnd: f.LineEnd, @@ -257,14 +226,11 @@ func evidenceListing(tc *TaskContext, candidates []evidenceCandidate) string { return listing.String() } -// runEvidenceVerifier runs phase 5's evidence verifier over every -// high-priority (critical or important) finding, dropping the ones it finds -// unsupported by their own evidence package. A finding below high priority is -// never sent, and always kept: the verifier exists to catch a hallucinated -// critical, not to grade a nitpick. A failed or malformed verifier call keeps -// every finding unfiltered -- the pipeline is recall-first, so a verifier -// that could not run is not evidence any finding is wrong; the error is -// intentionally swallowed here, not propagated. +// A finding below high priority is never sent, and always kept: the verifier +// exists to catch a hallucinated critical, not to grade a nitpick. A failed or +// malformed verifier call keeps every finding unfiltered -- the pipeline is +// recall-first, so a verifier that could not run is not evidence any finding is +// wrong; the error is intentionally swallowed here, not propagated. func runEvidenceVerifier(ctx context.Context, tc *TaskContext, findings []prreview.Finding) ([]prreview.Finding, error) { candidates := highPriorityCandidates(findings) if len(candidates) == 0 { @@ -338,7 +304,7 @@ var adversaryVerdictsSchema = json.RawMessage(`{ }`) // adversarySkepticism is the extra instruction the adversary's mission -// carries when intake scored the PR as likely machine-written, per the PRD. +// carries when intake scored the PR as likely machine-written. func adversarySkepticism(aiGenerated float64) string { if prreview.IsAIGenerated(aiGenerated) { return "This PR's own description reads as likely machine-written: be more sceptical " + @@ -388,13 +354,11 @@ func applyAdversaryVerdicts(out []prreview.Finding, calls []json.RawMessage) { } } -// runAdversary runs phase 5's adversary over every surviving finding at -// once: it confirms or challenges each by index, and may report new findings -// no reviewer caught. It reads intake's machine-written confidence and is -// told to be more sceptical above the threshold, per the PRD. A failed or -// malformed call leaves every finding's Adversary verdict unset (neither -// confirmed nor challenged) and adds nothing -- an adversary that could not -// run has reached no verdict, which is different from confirming everything. +// It reads intake's machine-written confidence and is told to be more sceptical +// above the threshold. A failed or malformed call leaves every finding's +// Adversary verdict unset (neither confirmed nor challenged) and adds nothing +// -- an adversary that could not run has reached no verdict, which is different +// from confirming everything. func runAdversary(ctx context.Context, tc *TaskContext, findings []prreview.Finding) ([]prreview.Finding, error) { if len(findings) == 0 { return findings, nil @@ -430,12 +394,10 @@ func runAdversary(ctx context.Context, tc *TaskContext, findings []prreview.Find return out, nil } -// runCompoundCheck runs phase 5's compound-defect check once per cluster -// that has more than one finding, in parallel, bounded the same as every -// other pr-review fan-out. It flags the findings the agent names as -// compounding (Finding.Compound = true), which is what scoring's compound -// multiplier reads. A cluster with at most one finding cannot compound with -// anything and is skipped without an agent call. +// It flags the findings the agent names as compounding (Finding.Compound = +// true), which is what scoring's compound multiplier reads. A cluster with at +// most one finding cannot compound with anything and is skipped without an +// agent call. func runCompoundCheck(ctx context.Context, tc *TaskContext, findings []prreview.Finding) ([]prreview.Finding, error) { grouped := prreview.ClusterFindings(tc.prReview.clusters, findings) var clusterIDs []string @@ -524,15 +486,11 @@ func runCompoundClusterCheck(ctx context.Context, tc *TaskContext, clusterID str return flagged } -// prReviewGapRounds is phase 6's cap on gap-review rounds: at most 2, per the -// PRD, so a coverage gap the gap reviewers cannot close does not loop forever. const prReviewGapRounds = 2 -// stagePRCoverageConsistency is pipeline phase 6: the coverage gate and -// consistency verification run in parallel and both append to -// tc.prReview.findings, guarded by prReviewState.findingsMu -// (docs/prds/pr-review-agent.md, phase 6: "Coverage and consistency, in -// parallel"). +// stagePRCoverageConsistency runs the coverage gate and consistency +// verification in parallel; both append to tc.prReview.findings under +// prReviewState.findingsMu. func stagePRCoverageConsistency() Stage { return Stage{Name: "coverage-consistency", Run: func(ctx context.Context, tc *TaskContext) error { var wg sync.WaitGroup @@ -546,12 +504,6 @@ func stagePRCoverageConsistency() Stage { }} } -// runCoverageGate is phase 6's coverage gate: for up to prReviewGapRounds -// rounds, find the clusters and high-exposure blast-radius files no finding -// covers, run one gap reviewer per gap (reusing runReviewer, the same -// reviewer definition phase 4 uses), and append whatever they find. It stops -// early once nothing is uncovered, so a change that phase 4 already covered -// fully never spends a gap-review call. func runCoverageGate(ctx context.Context, tc *TaskContext) { for range prReviewGapRounds { tc.prReview.findingsMu.Lock() @@ -576,8 +528,7 @@ func runCoverageGate(ctx context.Context, tc *TaskContext) { } // gapDimensions builds one reviewer dimension per coverage gap: a cluster's -// files together (a cluster is reviewed as one unit, the way phase 4 would -// have if a lens had proposed it), and one per uncovered high-exposure file. +// files together, and one per uncovered high-exposure file. func gapDimensions(clusters []prreview.Cluster, files []string) []prreview.Dimension { dims := make([]prreview.Dimension, 0, len(clusters)+len(files)) for _, cluster := range clusters { @@ -597,12 +548,8 @@ func gapDimensions(clusters []prreview.Cluster, files []string) []prreview.Dimen return dims } -// runConsistencyVerification is phase 6's consistency verification: one -// agent call lists the cross-location obligations the changed code creates -// and verifies each by reading both ends, reporting only the broken ones as -// findings (the PRD's own wording -- "a broken obligation becomes a -// finding"). It reuses report_findings, the same shape every other -// findings-reporting call in the pipeline uses. +// It reuses report_findings, the same shape every other findings-reporting call +// in the pipeline uses. func runConsistencyVerification(ctx context.Context, tc *TaskContext) error { mission := fmt.Sprintf( "Read this pull request's diff and the surrounding repository. List every "+ @@ -642,11 +589,9 @@ var mergeGateSchema = json.RawMessage(`{ "required": ["blocking"] }`) -// stagePRMergeGate is pipeline phase 8: one classification call per -// surviving finding decides blocking or advisory (docs/prds/pr-review- -// agent.md, phase 8). Blocking is narrow, and a failed or malformed call -// leaves a finding advisory -- the same fallback every other pr-review -// verdict call in this pipeline uses when its agent call could not run. +// Blocking is narrow, and a failed or malformed call leaves a finding advisory +// -- the same fallback every other pr-review verdict call in this pipeline uses +// when its agent call could not run. func stagePRMergeGate() Stage { return Stage{Name: "merge-gate", Run: func(ctx context.Context, tc *TaskContext) error { if len(tc.prReview.scored) == 0 { @@ -682,7 +627,7 @@ func runMergeGateCall(ctx context.Context, tc *TaskContext, f prreview.ScoredFin Parameters: mergeGateSchema, RequiredFields: []string{"blocking"}, MaxCalls: 1, }}) if err != nil || res.Status != agentexec.StatusPassed { - return false //nolint:nilerr // a merge-gate call that could not run leaves the finding advisory, per the PRD + return false //nolint:nilerr // a merge-gate call that could not run leaves the finding advisory } calls := res.Captures["classify_blocking"] if len(calls) != 1 { diff --git a/internal/domain/workflow/remediate.go b/internal/domain/workflow/remediate.go index 4d5d9c3e6..367fbd2b8 100644 --- a/internal/domain/workflow/remediate.go +++ b/internal/domain/workflow/remediate.go @@ -27,10 +27,8 @@ type ReviewUnitComment struct { // ReviewUnit is the remediate workflow's input contract: one review (or one // standalone comment with no parent review) and every actionable comment -// grouped under it, per docs/prds/pr-review-remediation.md decision 5 ("a -// review is the unit of remediation, never an individual comment"). The -// daemon's reaction consumer builds and JSON-encodes this into -// Task.ReviewPayload before dispatch; this package only decodes and acts +// grouped under it. The daemon's reaction consumer builds and JSON-encodes this +// into Task.ReviewPayload before dispatch; this package only decodes and acts // on it. type ReviewUnit struct { ReviewID int64 `json:"review_id,omitempty"` @@ -117,8 +115,8 @@ const remediationRoundCapBytes = 2000 // retiredResumeStep is the remediate workflow's old in-container resume stage, // kept as an inert word in the step vocabulary. The resume it used to perform -// now happens in daemon.prepareWorkspace before the container starts -// (archie-core-866m): the daemon holds the forge credential that fetches the +// now happens in daemon.prepareWorkspace before the container starts: +// the daemon holds the forge credential that fetches the // branch and positions the worktree onto origin/, so by the time a // container-side stage could run there is nothing left to do. It is // deliberately not a stage of Remediate() any more -- a new definition never @@ -268,8 +266,8 @@ func StageRemediationReply() Stage { } // Remediate runs one remediation round against an archie-owned, still-open -// pull request in response to a forge review reaction -// (docs/prds/pr-review-remediation.md decision 4). It reuses the task's +// pull request in response to a forge review reaction. +// It reuses the task's // existing worktree and branch rather than opening a new PR. The daemon // positions the worktree onto the PR branch before the container starts // (prepareWorkspace), and StagePrepareWorktreeOnBranch then binds that diff --git a/internal/domain/workflow/routing.go b/internal/domain/workflow/routing.go index 7ce7137d1..ddddd3482 100644 --- a/internal/domain/workflow/routing.go +++ b/internal/domain/workflow/routing.go @@ -40,11 +40,7 @@ var defaultKindWorkflows = KindWorkflows{ var activeKindWorkflows KindWorkflows // SetKindWorkflows overrides the kind-to-workflow-name bindings Route() -// consults, e.g. from a file loaded by LoadKindWorkflowsYAML. Passing nil -// restores the built-in defaults -- the first slice of -// docs/prds/eda-playbook-engine.md: which workflow a Kind prefers is data, -// not a Go literal, without touching labelKinds or the closed NATS-subject -// set that Kind itself still governs. +// consults, e.g. from a file loaded by LoadKindWorkflowsYAML. func SetKindWorkflows(kw KindWorkflows) { activeKindWorkflows = kw } @@ -81,25 +77,12 @@ 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. +// LoadPlaybookDirs reads every *.yaml / *.yml file in the configured +// directories as a binding file and merges them into one kind map and one +// label map. A key declared by more than one file is a load failure: the +// colliding definitions are dropped and the error returned. Sources are read in +// configured directory order, then filename order. An empty list or missing +// directories return (nil, nil). func LoadPlaybookDirs(dirs []string) (KindWorkflows, LabelWorkflows, error) { kw := make(KindWorkflows) lw := make(LabelWorkflows) @@ -201,13 +184,12 @@ func bindPlaybookKey(pos, key, value string, kw KindWorkflows, lw LabelWorkflows return 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. +// 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. 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) @@ -308,12 +290,10 @@ func ResolveWorkflowID(t *Task, available map[string]struct{}, kinds KindWorkflo return "", fmt.Errorf("no routable workflow definition") } -// LabelWorkflows maps a forge issue label to the registered workflow name -// it prefers. This is the second slice of docs/prds/eda-playbook-engine.md: -// the label vocabulary itself -- not just the closed bug/feature/bootstrap -// kind set -- becomes playbook data. The closed Kind/NATS-subject set -// (workintake) is deliberately untouched; this map only extends binding -// authority for labels the kind layer does not own. +// LabelWorkflows maps a forge issue label to the registered workflow name it +// prefers. The closed Kind/NATS-subject set (workintake) is deliberately +// untouched; this map only extends binding authority for labels the kind layer +// does not own. type LabelWorkflows map[string]string // activeLabelWorkflows is what workflowForLabels consults for arbitrary diff --git a/internal/domain/workflow/steps.go b/internal/domain/workflow/steps.go index eb8720667..69959c720 100644 --- a/internal/domain/workflow/steps.go +++ b/internal/domain/workflow/steps.go @@ -116,8 +116,8 @@ func StagePrepareWorktree() Stage { // StagePrepareWorktreeOnBranch binds the task's worktree on the branch its // already-open pull request lives on -- the resume target -- for a workflow -// that continues pushed work rather than starting fresh -// (docs/prds/pr-review-remediation.md decision 4). The branch is the task's +// that continues pushed work rather than starting fresh. +// The branch is the task's // persisted branch, never recomputed from the title: the PR was opened from // that branch, and a retitled issue would otherwise name one that does not // exist. It resolves the same directory the daemon's mode-aware prepare diff --git a/internal/domain/workflow/task/caller.go b/internal/domain/workflow/task/caller.go index 6dd4d650e..345c38aff 100644 --- a/internal/domain/workflow/task/caller.go +++ b/internal/domain/workflow/task/caller.go @@ -6,7 +6,7 @@ import "context" // back while waiting. It is the consumer-owned contract the workflow engine // holds (the same shape as Store), satisfied by *staterpc.Client for an // agent-container run: the callee is a first-class task the State Store -// derives from the caller's row (docs/prds/workflow-calls.md). +// derives from the caller's row. type Caller interface { // StartCall enqueues the callee task for callerTaskID's workflow.call // step: org, workspace, identity, owner, repo and issue number are @@ -14,11 +14,9 @@ type Caller interface { // and the callee's depth is the caller's + 1. The store refuses a // caller that is not running and a call past the depth limit. StartCall(ctx context.Context, callerTaskID int64, workflow string, inputs map[string]any) (*Task, error) - // CallStatus reads one call's callee: its status, latest transition - // detail and written outputs (decoded from the callee's row; - // docs/prds/workflow-call-outputs.md, "Storage and wire" — the callee - // writes them and the caller only receives them). A store only answers - // for a task whose call_parent_task_id is callerTaskID, so a caller - // reads only its own callees. + // CallStatus reads one call's callee: its status, latest transition detail + // and written outputs. A store only answers for a task whose + // call_parent_task_id is callerTaskID, so a caller reads only its own + // callees. CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (status, detail string, outputs map[string]any, err error) } diff --git a/internal/domain/workflow/task/interface.go b/internal/domain/workflow/task/interface.go index faee5893e..be75c6a66 100644 --- a/internal/domain/workflow/task/interface.go +++ b/internal/domain/workflow/task/interface.go @@ -34,7 +34,7 @@ type InputSpec struct { // OutputSpec declares one workflow output: the same type vocabulary an // input uses. A required output the run never writes parks it before any -// terminal state (docs/prds/workflow-call-outputs.md, "Failure rules"); +// terminal state; // required defaults to false. type OutputSpec struct { Type string `yaml:"type" json:"type"` @@ -49,7 +49,7 @@ type WorkflowInterface struct { Inputs map[string]InputSpec `yaml:"inputs,omitempty" json:"inputs,omitempty"` Repository RepositoryMode `yaml:"repository,omitempty" json:"repository,omitempty"` // Outputs declares the named, typed structured results a run writes - // once each (docs/prds/workflow-call-outputs.md). A wait:true caller + // once each. A wait:true caller // reads them through WorkflowCallStatus; a call step publishes one as // one of the caller's own outputs. Outputs map[string]OutputSpec `yaml:"outputs,omitempty" json:"outputs,omitempty"` @@ -64,10 +64,9 @@ type WorkflowInterface struct { // Needs reports the harness requirements the interface carries: the declared // needs, plus the captures a declared output forces, because an output is -// written through a capture tool (docs/prds/workflow-call-outputs.md, "How a -// run writes one"). Profile selection reads this rather than DeclaredNeeds, -// so a workflow that declares outputs cannot name a Kit profile whose harness -// serves no capture tools (docs/prds/external-agent-harness.md, "Contract"). +// written through a capture tool. Profile selection reads this rather than +// DeclaredNeeds, so a workflow that declares outputs cannot name a Kit profile +// whose harness serves no capture tools. func (w WorkflowInterface) Needs() WorkflowNeeds { needs := w.DeclaredNeeds if len(w.Outputs) > 0 { @@ -163,8 +162,8 @@ func (w WorkflowInterface) CheckInputs(values map[string]any) error { // CheckOutputs rejects declared-output values that do not satisfy the // declared outputs: the same rules CheckInputs applies to inputs (required, -// undeclared, wrong type), read from the other side of the interface -// (docs/prds/workflow-call-outputs.md, "Failure rules"). A written null +// undeclared, wrong type), read from the other side of the interface. +// A written null // counts as not written, as CheckInputs treats a null input; an unwritten // optional output leaves its key absent rather than null. func (w WorkflowInterface) CheckOutputs(values map[string]any) error { @@ -240,9 +239,8 @@ func DecodeInputs(s string) (map[string]any, error) { return inputs, nil } -// EncodeOutputs is the stored and wire form of a task's written outputs: a -// JSON object, or empty for none (docs/prds/workflow-call-outputs.md, -// "Storage and wire"). +// EncodeOutputs is the stored and wire form of a task's written outputs: a JSON +// object, or empty for none. func EncodeOutputs(outputs map[string]any) (string, error) { if len(outputs) == 0 { return "", nil diff --git a/internal/domain/workflow/task/review_gate.go b/internal/domain/workflow/task/review_gate.go index 8df88c1b5..bef62adf9 100644 --- a/internal/domain/workflow/task/review_gate.go +++ b/internal/domain/workflow/task/review_gate.go @@ -8,7 +8,6 @@ import ( // ReviewGate is the operator-approval gate's whole conversation with the // operator, encoded on the task's review_gate column -// (docs/prds/pr-review-operator-response.md). // // It lives with the task record it encodes, the way EncodeInputs does, for the // same reason: the dashboard process renders and answers a gate, and it must @@ -48,8 +47,7 @@ type ReviewGate struct { // Selection is the finding keys an approve posts. Empty means all of the // offered findings. Selection []string `json:"selection,omitempty"` - // Instructions is what the operator asked a re-review to focus on. The - // PRD requires it for a re-review; the lens and reviewer missions read it. + // Instructions is what the operator asked a re-review to focus on. Instructions string `json:"instructions,omitempty"` } @@ -71,7 +69,7 @@ const ( ) // MaxRereviewRounds bounds how many operator re-reviews one review gate -// grants, per the PRD's Decision 2. It is a constant in the domain, not a +// grants. It is a constant in the domain, not a // config knob, and the guarded store write enforces it in the row so two // simultaneous re-reviews cannot spend a round the cap forbids. const MaxRereviewRounds = 2 diff --git a/internal/domain/workflow/task/step.go b/internal/domain/workflow/task/step.go index c757c454a..79c2dd63a 100644 --- a/internal/domain/workflow/task/step.go +++ b/internal/domain/workflow/task/step.go @@ -6,10 +6,8 @@ import ( "github.com/samcharles93/archie-core/internal/taskstate" ) -// The step-execution vocabulary of docs/prds/execution-tree-state-machine.md: -// one stage run, or one agent or workflow.call step an execution's tree -// records, started and finished through the State Store under the run's own -// credential. +// Step records: one stage run, agent call or workflow.call, started and +// finished through the State Store under the run's own credential. // Step kinds. `stage` is what workflow.Run records for every stage it runs; // `agent` is what the agent runtime records for one agent call; `call` is the @@ -69,9 +67,7 @@ type StepFinish struct { } // StepExecution is one recorded step: ListSteps' read, the dashboard run -// detail's authoritative source (docs/prds/execution-tree-state-machine.md; -// replaces folding stage_start/stage_finish events, which tasks.stage used to -// back). ParentID is 0 for a stage at the tree's root. +// detail's authoritative source. ParentID is 0 for a stage at the tree's root. type StepExecution struct { ID int64 ExecutionID int64 diff --git a/internal/domain/workflow/task/task.go b/internal/domain/workflow/task/task.go index 6df8ba341..d0905686b 100644 --- a/internal/domain/workflow/task/task.go +++ b/internal/domain/workflow/task/task.go @@ -1,7 +1,7 @@ // Package task is the task-execution vocabulary of the workflow domain: // the Task record, its lifecycle statuses, and the narrow Store contract // workflow stages call mid-run. It split out of package workflow -// (archie-core-8cda.5.6) so the UI process can hold the vocabulary without +// so the UI process can hold the vocabulary without // linking the pipeline engine there -- which drags in agentexec, skill and // tools. package workflow keeps aliases, so daemon-side callers are // unaffected. @@ -96,14 +96,14 @@ type Task struct { // one identity cannot control another's chat-spawned tasks. Identity string `json:"identity"` // Org is the org the task belongs to. The State Store derives it from - // the task's identity when the row is written - // (docs/prds/orgs-and-access.md, "Events and task identity"); a task + // the task's identity when the row is written; + // a task // of a single-operator install belongs to the default org. Org org.OrgID `json:"org,omitempty"` - // BindingID and BindingVersion are stamped when a task was created - // from a playbook binding dispatch (t2db.4 Phase B). They record - // provenance: which binding fired this task and at what version, so - // later edits to the binding cannot silently rewrite history. + // BindingID and BindingVersion are stamped when a task was created from a + // playbook binding dispatch. They record provenance: which binding fired + // this task and at what version, so later edits to the binding cannot + // silently rewrite history. BindingID string `json:"binding_id"` BindingVersion int `json:"binding_version"` // Inputs are the workflow inputs the binding assigned, checked against @@ -111,18 +111,17 @@ type Task struct { // structured data, never as body text. Inputs map[string]any `json:"inputs,omitempty"` // Outputs are the structured results this run wrote to the workflow's - // declared outputs (docs/prds/workflow-call-outputs.md). The set is + // declared outputs. The set is // attempt-scoped: a claim starts the next attempt with an empty set and // the finish write replaces the row's set wholesale. Callers read these // only from a successful terminal state, through WorkflowCallStatus. Outputs map[string]any `json:"outputs,omitempty"` // ReviewPayload is the JSON-encoded review unit (the forge review's - // actionable comments) the remediate workflow's current run must - // address. The daemon's reaction consumer injects it before queuing a - // remediation run, so the run is recoverable from the task record - // itself rather than only from a prompt (docs/prds/pr-review-remediation.md - // decision 4). Empty outside a remediation run. RetryCount doubles as - // the remediation round counter for this same task, bounded by the + // actionable comments) the remediate workflow's current run must address. + // The daemon's reaction consumer injects it before queuing a remediation + // run, so the run is recoverable from the task record itself rather than + // only from a prompt. Empty outside a remediation run. RetryCount doubles + // as the remediation round counter for this same task, bounded by the // repo's existing max_retries (decision 5's round cap). ReviewPayload string `json:"review_payload"` // ParkClass is the producer-recorded answer to "what kind of @@ -136,21 +135,20 @@ type Task struct { // budget: one shared counter made N operator retries eat the // review-remediation budget and vice versa. RemediationRounds int `json:"remediation_rounds"` - // ReviewGate is the operator-approval gate's whole conversation with - // the operator, persisted as one JSON document (prreview.EncodeReviewGate): - // the offer the gate writes before it waits for an operator -- the scored + // ReviewGate is the operator-approval gate's whole conversation with the + // operator, persisted as one JSON document (prreview.EncodeReviewGate): the + // offer the gate writes before it waits for an operator -- the scored // findings, the head SHA, the pull request's identity and the workflow the // wait resumes -- and the answer the response path fills in -- the outcome, // the selected findings' keys for an approve and the instructions for a // re-review. Without it, "post the selected findings" cannot mean the // findings the operator saw: the resumed run recomputes them with agent - // calls (docs/prds/pr-review-operator-response.md, "The review the operator - // answers"). Empty for a task that never reached the gate. + // calls. Empty for a task that never reached the gate. ReviewGate string `json:"review_gate"` // RereviewRounds counts how many operator re-reviews the pr-review gate // granted, incremented in the same guarded write that requeues the - // re-review and capped at prreview.MaxRereviewRounds - // (docs/prds/pr-review-operator-response.md, Decision 2). Deliberately + // re-review and capped at prreview.MaxRereviewRounds. + // Deliberately // separate from both RetryCount and RemediationRounds -- one shared // counter made unrelated retries draw another phase's budget down. RereviewRounds int `json:"rereview_rounds"` @@ -220,8 +218,8 @@ type Store interface { Update(ctx context.Context, t *Task) error Transition(ctx context.Context, taskID int64, from, to, detail string) error InsertEvent(ctx context.Context, e events.Event) (int64, error) - // StartStep records a StepExecution entering running - // (docs/prds/execution-tree-state-machine.md): the store creates the row, + // StartStep records a StepExecution entering running: + // the store creates the row, // enforces the step transition table and the execution's own status, and // writes the transition's stage_start event in the same transaction. It // returns the step's id and the persisted event, which the caller publishes diff --git a/internal/domain/workflow/task_aliases.go b/internal/domain/workflow/task_aliases.go index ab985cc5c..3274ae443 100644 --- a/internal/domain/workflow/task_aliases.go +++ b/internal/domain/workflow/task_aliases.go @@ -1,6 +1,6 @@ // Task-vocabulary aliases. The Task record, its statuses, the mid-run // Store contract, and Definition moved to internal/domain/workflow/task -// (archie-core-8cda.5.6) so the UI process can hold the vocabulary without +// so the UI process can hold the vocabulary without // linking this package's pipeline engine (which imports agentexec, skill // and tools). package workflow keeps these aliases, so daemon-side callers // are unaffected. @@ -15,7 +15,7 @@ type ( // contract that workflow stages call mid-run. Store = task.Store // StepStart and StepFinish are the step-execution writes the store - // records mid-run (docs/prds/execution-tree-state-machine.md). + // records mid-run. StepStart = task.StepStart StepFinish = task.StepFinish // Definition is the operator-safe snapshot of an executable workflow. diff --git a/internal/domain/workflow/triage.go b/internal/domain/workflow/triage.go index cf2b0555d..46d9084e9 100644 --- a/internal/domain/workflow/triage.go +++ b/internal/domain/workflow/triage.go @@ -16,9 +16,9 @@ var triageWorkflowNames = map[string]bool{ "feasibility": true, } -// Triage is the cheap-classification workflow: one read-only agent turn -// decides whether a task needs a code change at all and, if so, which -// workflow suits it best. See docs/prds/dynamic-workflow-triage.md. +// Triage is the cheap-classification workflow: one read-only agent turn decides +// whether a task needs a code change at all and, if so, which workflow suits it +// best. // // It exists because Route (workflow.go) previously had no content-aware // fallback: every task with no explicit workflow and no label match ran diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index ec7097cf2..4a1b86438 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -50,7 +50,7 @@ type Forger interface { Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) // ReplyToReview posts a threaded reply to one review comment. The // remediate workflow calls it once per remediation run, summarising - // what changed (docs/prds/pr-review-remediation.md decision 4). + // what changed. ReplyToReview(ctx context.Context, owner, repo string, number int, commentID int64, body string) error } @@ -89,10 +89,9 @@ type Trees interface { Diff(ctx context.Context, dir, base string) (string, error) ChangedFiles(ctx context.Context, dir, base string) ([]string, error) ChangedLines(ctx context.Context, dir, base string) (int, error) - // Snapshot exports HEAD's tracked files into destDir with no .git - // directory -- no commit history, branch name, or reflog. Used to - // build the reviewer's isolated workspace (see the isolation contract - // in docs/prds/pr-review-agent.md). + // Snapshot exports HEAD's tracked files into destDir with no.git directory + // -- no commit history, branch name, or reflog. Used to build the + // reviewer's isolated workspace. Snapshot(ctx context.Context, dir, destDir string) error } @@ -110,7 +109,7 @@ type TaskContext struct { // Calls starts workflow.call callees and reads them back while a // wait:true caller waits. Nil is only safe for a workflow with no // workflow.call step: such a step in a runner with no capability - // fails the run with a named error (docs/prds/workflow-calls.md). + // fails the run with a named error. Calls task.Caller // PRSource fetches a pull request under review and its head snapshot for // the pr-review workflow (see prreview_stages.go). Nil is only safe for a @@ -139,10 +138,8 @@ type TaskContext struct { // Dir/Branch are set by the prepare step. Dir string Branch string - // Stage is the name of the stage currently running, kept here (not - // persisted on Task -- docs/prds/execution-tree-state-machine.md drops - // tasks.stage in favour of the durable StepExecution record StartStep - // writes) purely so park/finish can tag the event they emit with it. + // Stage is the name of the stage currently running, kept here purely so + // park/finish can tag the event they emit with it. Stage string // StepID is the StepExecution the engine recorded for the stage whose // body is running: every agent call the stage makes records itself as @@ -253,11 +250,9 @@ func (tc *TaskContext) EmitDurable(ctx context.Context, kind, stage, detail stri return nil } -// toolCallReporter builds the agentexec.ToolCallReporter an agent stage -// passes to tc.Agent.Run, so every completed tool call during that run -// surfaces as a tool_call event on the task timeline (archie-core-467's -// task-transcript counterpart -- the interactive chat gateway has its own, -// separate ToolCallEvent). Safe to call on a nil Bus: Emit no-ops. +// toolCallReporter builds the agentexec.ToolCallReporter an agent stage passes +// to tc.Agent.Run, so every completed tool call during that run surfaces as a +// tool_call event on the task timeline. Safe to call on a nil Bus: Emit no-ops. func (tc *TaskContext) toolCallReporter(stage string) agentexec.ToolCallReporter { return func(report agentexec.ToolCallReport) { tc.Emit(events.KindToolCall, stage, report.Detail, map[string]any{ @@ -316,11 +311,10 @@ func Route(t *Task, reg Registry) Workflow { if wf, ok := workflowForLabels(reg, t.Labels); ok { return wf } - // No explicit workflow, no label match: a labelled task already has a - // free, reliable signal and never reaches here. Everything else -- - // overwhelmingly chat-spawned tasks, which rarely carry labels -- gets - // classified by triage instead of defaulting straight to the heaviest - // workflow. See docs/prds/dynamic-workflow-triage.md. + // No explicit workflow, no label match: a labelled task already has a free, + // reliable signal and never reaches here. Everything else -- overwhelmingly + // chat-spawned tasks, which rarely carry labels -- gets classified by + // triage instead of defaulting straight to the heaviest workflow. if wf, ok := reg["triage"]; ok { return wf } @@ -356,7 +350,7 @@ func Run(ctx context.Context, wf Workflow, tc *TaskContext) { park(ctx, tc, fmt.Sprintf("persist task before stage %s: %v", stage.Name, err)) return } - // Every stage is a StepExecution (docs/prds/execution-tree-state-machine.md): + // Every stage is a StepExecution: // the store records pending -> running and writes the stage_start event // in the same transaction, and refuses a start the state machine // forbids. A failed recording write parks the execution -- the step @@ -469,7 +463,6 @@ func finish(ctx context.Context, tc *TaskContext, log *slog.Logger) { // transition: an undeclared, mistyped or required-but-missing value // parks the run here, so no caller observes a terminal state that // breaks the workflow's own promise - // (docs/prds/workflow-call-outputs.md, "Failure rules"). if err := tc.validateFinishOutputs(); err != nil { park(ctx, tc, err.Error()) return @@ -587,7 +580,7 @@ func extractFailingGateOutput(s string) string { var goTestOKLine = regexp.MustCompile(`^ok\s+\S+`) // RunAgentChild records one agent call as a child StepExecution of the stage -// this run is executing (docs/prds/execution-tree-state-machine.md, "Model"): +// this run is executing: // kind agent, parented to the stage's own step, which the store derives depth // from, and finished with the call's own outcome and the tokens it // accounted. A child's recording write failure is the same park a stage's diff --git a/internal/domain/workflow/workflow_call.go b/internal/domain/workflow/workflow_call.go index 6c769a9e6..2e1373e83 100644 --- a/internal/domain/workflow/workflow_call.go +++ b/internal/domain/workflow/workflow_call.go @@ -19,7 +19,7 @@ import ( // WorkflowCallStepName is the step type that starts another workflow as its // own run. The callee is a first-class task the State Store derives from the // caller's row: its own pinned definition, its own agent profile, its own -// container and its own outcome (docs/prds/workflow-calls.md). +// container and its own outcome. const WorkflowCallStepName = "workflow.call" // MaxCallDepth bounds how deep one run may call callees. A cycle is refused @@ -32,10 +32,9 @@ const MaxCallDepth = 5 // status. A var so tests do not sleep. var callPollInterval = 2 * time.Second -// workflowCallSettings are the workflow.call step's settings. An inputs value -// is either a literal or a reference to the calling workflow's declared -// input, written "inputs." -- the PRD's `inputs: { src_ip: -// inputs.src_ip }` shape. +// workflowCallSettings are the workflow.call step's settings. An inputs value is +// a literal or "inputs.", a reference to the calling workflow's declared +// input. type workflowCallSettings struct { Workflow string `yaml:"workflow"` Inputs map[string]any `yaml:"inputs,omitempty"` @@ -43,7 +42,6 @@ type workflowCallSettings struct { // Outputs publishes a callee output as one of the caller's own: the key // names the callee's declared output, the value an outputs. // reference naming the caller's declared output - // (docs/prds/workflow-call-outputs.md, "How a caller receives one"). Outputs map[string]string `yaml:"outputs,omitempty"` } @@ -273,7 +271,6 @@ func callSucceeded(status string) bool { // validateWorkflowCalls checks every workflow.call step against the rest of // the collection: the callee must exist, the call's inputs must satisfy the // callee's declared inputs, and no workflow may reach itself through calls -// (docs/prds/workflow-calls.md). func validateWorkflowCalls(parsed map[string]YAMLDefinition) error { calls := make(map[string][]string, len(parsed)) for id, d := range parsed { @@ -341,8 +338,8 @@ func checkCallInputs(callerID string, index int, caller task.WorkflowInterface, // checkCallOutputs validates one call's saved outputs assignment: the key // must be declared by the callee, the reference must name an output the -// caller declares, and the callee's declared type must satisfy the caller's -// (docs/prds/workflow-call-outputs.md, "Save time"). The shape of the value +// caller declares, and the callee's declared type must satisfy the caller's. +// The shape of the value // (a well-formed outputs. reference) is the factory's refusal; only // the declarations are the collection's to judge, exactly as for inputs. func checkCallOutputs(callerID string, index int, caller task.WorkflowInterface, callee YAMLDefinition, outputs map[string]string) error { diff --git a/internal/domain/workintake/envelope.go b/internal/domain/workintake/envelope.go index c51fa370c..9e1f03c64 100644 --- a/internal/domain/workintake/envelope.go +++ b/internal/domain/workintake/envelope.go @@ -2,10 +2,10 @@ // durable, workflow-backed work. // // It owns the vocabulary of that promotion -- the task envelope, its routing -// kind, and the subjects it is addressed to -- because the domain that -// defines a message's meaning owns its schema. These previously lived in the -// NATS package, which made the transport responsible for knowing what a unit -// of work was; see docs/architecture/dependencies-and-contracts.md. +// kind, and the subjects it is addressed to -- because the domain that defines +// a message's meaning owns its schema. These previously lived in the NATS +// package, which made the transport responsible for knowing what a unit of work +// was // // This package names no broker. It produces and consumes bytes; carrying // them is internal/eventbus's job. @@ -50,7 +50,7 @@ type TaskEnvelope struct { Identity string `json:"identity,omitempty"` // Org is the org the identity serves, resolved by the producer before - // publishing (docs/prds/orgs-and-access.md, "Events and task identity"). + // publishing. // Empty means the default org of a single-operator install. Org org.OrgID `json:"org,omitempty"` @@ -109,10 +109,9 @@ func (t TaskEnvelope) Ref() string { // IdempotencyKey identifies this issue for delivery deduplication, so // rediscovering it on a later poll does not enqueue the same work twice. The -// key is org/identity/owner/repo/number (docs/prds/orgs-and-access.md, -// "Events and task identity"): the poller and the webhook receiver resolve -// the org and identity before publishing, so the same issue delivered both -// ways still gives one key, and the State Store's task uniqueness uses the +// key is org/identity/owner/repo/number: the poller and the webhook receiver +// resolve the org and identity before publishing, so the same issue delivered +// both ways still gives one key, and the State Store's task uniqueness uses the // same fields. This method is the one place that shape is produced. func (t TaskEnvelope) IdempotencyKey() string { return dedupKeyPrefix + string(t.org()) + "/" + t.Identity + "/" + diff --git a/internal/domain/workintake/review_envelope.go b/internal/domain/workintake/review_envelope.go index 86d0a1c78..7cbff40e6 100644 --- a/internal/domain/workintake/review_envelope.go +++ b/internal/domain/workintake/review_envelope.go @@ -40,7 +40,7 @@ type ReviewCommentEnvelope struct { // Org is the org the reaction's repo belongs to, resolved by the producer // before publishing; empty means the default org of a single-operator - // install (docs/prds/orgs-and-access.md, "Events and task identity"). + // install. Org org.OrgID `json:"org,omitempty"` } @@ -95,8 +95,8 @@ func (e ReviewCommentEnvelope) Ref() string { } // IdempotencyKey identifies one forge review record independently of delivery -// source. The key follows the task key's org/identity rule -// (docs/prds/orgs-and-access.md, "Events and task identity"), scoped to one +// source. The key follows the task key's org/identity rule, +// scoped to one // review record. func (e ReviewCommentEnvelope) IdempotencyKey() string { id := e.ReviewID diff --git a/internal/domain/workintake/subjects.go b/internal/domain/workintake/subjects.go index 318e3e8ab..bf4c816a1 100644 --- a/internal/domain/workintake/subjects.go +++ b/internal/domain/workintake/subjects.go @@ -20,7 +20,7 @@ const ( // SubjectReactionWildcard matches every reaction subject under archie.reaction. // Reactions are producer-only fan-out events -// (docs/prds/event-sources-and-reactions.md) delivered on a separate +// delivered on a separate // LimitsPolicy stream, so every registered consumer sees every matching event // -- unlike the work-queue ARCHIE_TASKS stream, where one consumer claims each // message. diff --git a/internal/eventbus/doc.go b/internal/eventbus/doc.go index da9c6deb1..78844da04 100644 --- a/internal/eventbus/doc.go +++ b/internal/eventbus/doc.go @@ -6,10 +6,6 @@ // mechanics, reconnection and serialization live in // internal/infrastructure/eventbus/nats, which implements these interfaces. // -// Per docs/architecture/dependencies-and-contracts.md, domains depend on this -// package and never on an infrastructure implementation; only application -// composition chooses a concrete broker. -// // # The bus does not own message meaning // // This package deliberately transports opaque payloads. Message schemas diff --git a/internal/events/events.go b/internal/events/events.go index 78111279b..6a2c1ff26 100644 --- a/internal/events/events.go +++ b/internal/events/events.go @@ -22,11 +22,9 @@ const ( // on events persisted before it was carried across the agent boundary, so // consumers must treat each field as optional rather than zero. KindAgentFinish = "agent_finish" // data: status, stop_reason, tokens, iterations, model, prompt_tokens, completion_tokens, cached_tokens, cache_creation_tokens - // KindToolCall marks one completed tool invocation during an agent - // stage run (archie-core-467's task-transcript counterpart -- the - // interactive chat gateway surfaces its own tool calls separately via - // gateway.ToolCallEvent). Only emitted for runners that execute in the - // same process as their tools; see agentexec.ToolCallReporter. + // KindToolCall marks one completed tool invocation during an agent stage + // run. Only emitted for runners that execute in the same process as their + // tools; see agentexec.ToolCallReporter. KindToolCall = "tool_call" // data: tool, failed KindParked = "parked" // data: reason KindOutcome = "outcome" // data: status, detail @@ -93,9 +91,9 @@ const ( // construction and by test). KindConfigCaptured = "config_captured" - // Curator family activity (epic archie-core-yp9). Curator runs ride + // Curator family activity. Curator runs ride // the same bus so background agents mutating memory stay observable: - // what ran, when, what changed, and why (archie-core-114). + // what ran, when, what changed, and why. KindCuratorRun = "curator_run" // data: curator, actions, at KindCuratorAction = "curator_action" // data: curator, type, detail, reason KindCuratorError = "curator_error" // data: curator, phase, err @@ -108,8 +106,8 @@ const ( KindJobRun = "job_run" KindJobError = "job_error" - // KindTurnCompleted marks one completed primary chat turn - // (archie-core-035). Input-driven curators wake on it. Curator output + // KindTurnCompleted marks one completed primary chat turn. + // Input-driven curators wake on it. Curator output // never produces this kind, so derived work cannot feed its own // trigger. data: session, channel. KindTurnCompleted = "turn_completed" @@ -129,7 +127,7 @@ const ( KindUnsignedEvent = "unsigned_event" // KindWorkflowCallStarted marks the moment a workflow.call step - // started its callee run (docs/prds/workflow-calls.md). data: + // started its callee run. data: // callee_task_id, workflow, wait. KindWorkflowCallStarted = "workflow_call_started" // KindWorkflowCallFinished carries the terminal state of a waited-on @@ -141,7 +139,7 @@ const ( // KindUpdateReport carries the phase-2 outcome of a dashboard-initiated // update -- whether the restarted daemon came back up healthy and on // the version it claimed, relayed once on the boot that finds the - // pending report left by the update watchdog (archie-core-nln7). + // pending report left by the update watchdog. // data: health_check, rolled_back, confirmed, drift, unverified. KindUpdateReport = "update_report" ) diff --git a/internal/forge/webhook/receiver.go b/internal/forge/webhook/receiver.go index c58467f4f..aeef70449 100644 --- a/internal/forge/webhook/receiver.go +++ b/internal/forge/webhook/receiver.go @@ -7,20 +7,19 @@ // processing; this one decodes a GitHub payload into the same TaskEnvelope // the poller produces and hands it to the same publish path, so a labelled or // assigned issue becomes work the moment it happens rather than up to -// poll_interval later (see docs/prds/event-sources-and-reactions.md). +// poll_interval later. // // GitHub's webhook must be configured with "Content type: application/json" // (the UI default). The alternate application/x-www-form-urlencoded delivery // is not decoded here and is rejected as a bad payload. // -// Idempotency is not this package's job: it decodes into the same -// TaskEnvelope and calls the same publish path the poller uses, so -// PublishUnique's dedup (keyed on TaskEnvelope.IdempotencyKey) covers both -// sources for free -- see archie-core-7d5u.5. What this package does own is -// making a wedged or non-delivering receiver observable: a GET to the -// listen address (GitHub only ever POSTs) returns Status, tracking -// authenticated deliveries and successful publishes separately so an -// operator can tell "receiver is up but nothing is arriving" apart from +// Idempotency is not this package's job: it decodes into the same TaskEnvelope +// and calls the same publish path the poller uses, so PublishUnique's dedup +// (keyed on TaskEnvelope.IdempotencyKey) covers both sources for free. What +// this package does own is making a wedged or non-delivering receiver +// observable: a GET to the listen address (GitHub only ever POSTs) returns +// Status, tracking authenticated deliveries and successful publishes separately +// so an operator can tell "receiver is up but nothing is arriving" apart from // "repo has no issue activity." // // The GET/Status route is deliberately unauthenticated, on the same @@ -121,7 +120,7 @@ func New(secret, trigger, label, botUser string, publish PublishFunc, reactionPu // Status reports the receiver's delivery activity so an operator can tell a // wedged or non-delivering receiver apart from a repo with no issue -// activity (archie-core-7d5u.5): Deliveries counts every authenticated, +// activity: Deliveries counts every authenticated, // parseable webhook -- proof GitHub reached this process at all -- while // Publishes counts only what the dispatch predicate turned into work. // LastReceivedAt is nil until the first authenticated delivery arrives. diff --git a/internal/gateway/chat_contract_aliases.go b/internal/gateway/chat_contract_aliases.go index 7c33f2bd5..33eb58179 100644 --- a/internal/gateway/chat_contract_aliases.go +++ b/internal/gateway/chat_contract_aliases.go @@ -1,5 +1,5 @@ // Wire-contract aliases. The chat contract types moved to -// internal/domain/messaging (archie-core-8cda.5.6) so the webui and +// internal/domain/messaging so the webui and // archie-ui processes can hold the contract without linking the gateway // runtime (and, transitively, its SQLite session store). internal/gateway // keeps these aliases so daemon-side callers and channel adapters are diff --git a/internal/gateway/compression.go b/internal/gateway/compression.go index 23fb391ec..3471d6898 100644 --- a/internal/gateway/compression.go +++ b/internal/gateway/compression.go @@ -117,17 +117,11 @@ type CompressedView struct { // TokensAfter is the estimated token count after compression. TokensAfter int - // ProtectedFirst and ProtectedLast are how many leading and trailing - // input messages passed through untouched, and are only meaningful when - // WasCompressed is true. - // - // They exist so a caller persisting the result can write back the - // original records for those positions rather than rebuilding them from - // Role and Content. A rebuilt message is a different message: it loses - // its canonical MessageID, its upstream SourceID and its timestamp, which - // breaks redelivery deduplication permanently and contradicts the - // immutability requirement in docs/architecture/messaging-and-work-intake - // .md lines 112-114. + // ProtectedFirst and ProtectedLast index the input messages passed through + // untouched, and are only meaningful when WasCompressed is true. A caller + // persisting the result writes back the original records for those + // positions, keeping their MessageID, SourceID and timestamp for redelivery + // deduplication. ProtectedFirst int ProtectedLast int } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 84671ed58..19a83f390 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -135,7 +135,7 @@ type TaskController interface { // exist, isn't owned by identity, or isn't in waiting_human. Approve(ctx context.Context, taskID int64, identity string) error // Cancel moves an active task to a terminal state through the one - // cancel path (docs/prds/execution-tree-state-machine.md): the store + // cancel path: the store // records the cancellation first, and the runtime delivers it by // cancelling the run's in-memory context where this process owns one. // Returns an error if the task doesn't exist, isn't owned by identity, @@ -287,7 +287,7 @@ func (r *Router) checkRateLimit(in Inbound) (blocked bool) { // per-person SenderID. The two are deliberately distinct -- SenderID means // "who sent this", and a channel whose SenderID is not a person (a webhook // route path) must not put it there, because several consumers read that -// field as a user identity (docs/prds/memory-engine-unification.md §3). +// field as a user identity. func inboundBudgetKey(in Inbound) string { if in.BudgetKey != "" { return in.BudgetKey @@ -307,7 +307,7 @@ func (r *Router) Route(ctx context.Context, in Inbound) (string, error) { // ignore the flag and treat the reply text as usual; a caller with no human // there (a webhook) needs it to answer with a proper rejection instead of // echoing the rate-limit prose as a successful delivery, or accepting an -// event that was actually dropped (archie-core-1173). +// event that was actually dropped. func (r *Router) RouteResult(ctx context.Context, in Inbound) (reply string, rateLimited bool, err error) { if r.duplicateDelivery(in) { return dedupReply, false, nil diff --git a/internal/gateway/message_dedup.go b/internal/gateway/message_dedup.go index acffb99df..3b5ed5882 100644 --- a/internal/gateway/message_dedup.go +++ b/internal/gateway/message_dedup.go @@ -150,5 +150,4 @@ func (d *MessageDeduplicator) evictLocked(at time.Time) { // the dedup window. Like the rate-limit reply it is prose addressed to a // human reader of the chat; a webhook caller should treat any successful, // non-original reply the same way it treats rate-limit prose (see -// archie-core-1173). const dedupReply = "I already received this message, so I'm ignoring this repeat delivery." diff --git a/internal/gateway/session_commands.go b/internal/gateway/session_commands.go index d944e0baa..e6c66a7ff 100644 --- a/internal/gateway/session_commands.go +++ b/internal/gateway/session_commands.go @@ -271,7 +271,7 @@ func sessionTrackerKey(channelID, threadID string) string { // Gateway's own name. Naming it is what makes SessionSource.Platform truthful -- // one Router serves every channel, so its own name is "web" even for a Telegram // turn, which made the platform a constant and left the per-user identity policy -// unreachable with a real channel name (archie-core-c1qx). +// unreachable with a real channel name. func (r *Router) sessionPlatform(in Inbound) string { if in.Platform != "" { return in.Platform diff --git a/internal/gateway/session_store_memory.go b/internal/gateway/session_store_memory.go index 048503c27..0c51d939a 100644 --- a/internal/gateway/session_store_memory.go +++ b/internal/gateway/session_store_memory.go @@ -13,11 +13,11 @@ import ( ) // memorySessionStore is the in-process SessionStore for tests and embedders -// that need no durability. It follows the PostgreSQL store's contract -// (sessionstore_conformance_test.go) including the optional TurnLedger, -// TurnHistory and TurnReplayStore capabilities: millisecond timestamps, the -// strictly-increasing append clamp, redelivery dedup on canonical IDs, and a -// search that ANDs lowercase word terms over sender and text. +// that need no durability. It follows the PostgreSQL store's contract including +// the optional TurnLedger, TurnHistory and TurnReplayStore capabilities: +// millisecond timestamps, the strictly-increasing append clamp, redelivery +// dedup on canonical IDs, and a search that ANDs lowercase word terms over +// sender and text. type memorySessionStore struct { mu sync.Mutex sessions map[string]SessionContext diff --git a/internal/gateway/slash_access.go b/internal/gateway/slash_access.go index 08da4369d..a897d6b58 100644 --- a/internal/gateway/slash_access.go +++ b/internal/gateway/slash_access.go @@ -65,15 +65,12 @@ var slashAdminOnly = map[string]bool{ // it (the ordinary commands are always available to a named user). // // The Router consults the policy before dispatching any local command, so a -// refusal executes none of the handler and is visible to the sender and to -// the daemon log; a wired SlashDenials sink records it for audit. The policy -// is keyed on the channel-native sender, not on an org principal: a chat -// message carries no identity the access chain can evaluate (the -// sender-to-identity mapping is archie-core-c1qx, still open), so this is the -// layer that can decide at the point the command is typed. A composition with -// no policy leaves every command available, which is the pre-policy -// behaviour. The posture follows docs/prds/orgs-and-access.md: deny by -// default, an explicit grant per principal. +// refusal executes none of the handler and is visible to the sender and to the +// daemon log; a wired SlashDenials sink records it for audit. The policy is +// keyed on the channel-native sender, not on an org principal: a chat message +// carries no identity the access chain can evaluate, so this is the layer that +// can decide at the point the command is typed. A composition with no policy +// leaves every command available, which is the pre-policy behaviour. type SlashAccessPolicy struct { AllowAdminFrom []string UserAllowedCommands map[string][]string diff --git a/internal/gateway/tasks.go b/internal/gateway/tasks.go index ffa4c351c..dd1c41174 100644 --- a/internal/gateway/tasks.go +++ b/internal/gateway/tasks.go @@ -138,12 +138,11 @@ type chatTaskController interface { ChatTaskStatus(ctx context.Context, taskID int64) (ChatTaskStatus, bool, error) // ApproveChatTask releases a waiting_human task through the daemon's one // task-action service, so chat and the dashboard cannot record different - // decisions for one operator intent (docs/prds/pr-review-operator- - // response.md, Decision 1). The caller has already validated the current - // status is waiting_human; the actor is the chat-bound identity, never an - // operator acting across identities. There is no review-gate payload: the - // chat surface has no instruction or selection syntax, so an approve posts - // every offered finding. + // decisions for one operator intent. The caller has already validated the + // current status is waiting_human; the actor is the chat-bound identity, + // never an operator acting across identities. There is no review-gate + // payload: the chat surface has no instruction or selection syntax, so an + // approve posts every offered finding. ApproveChatTask(ctx context.Context, taskID int64, actor taskactions.Actor) error // CancelChatTask transitions an active task to a rejected/terminal // state. Callers must have already validated the current status is @@ -203,12 +202,9 @@ func (c *StoreTaskController) Cancel(ctx context.Context, taskID int64, identity return err } // The store records the cancellation first -- the one cancel path -- and - // the context cancel delivers it. The order is the PRD's: a worker that - // keeps writing after the record fails ErrStaleTransition on its next - // step write, so it cannot win the race the old interrupt-first ordering - // guarded against. A task the store says is running but nothing is - // executing for (a crashed or migrated daemon) is unstuck by the record - // alone, which is why the delivery is reported, not required. + // the context cancel delivers it. A task the store says is running but + // nothing is executing for (a crashed or migrated daemon) is unstuck by the + // record alone, which is why the delivery is reported, not required. if err := c.store.CancelChatTask(ctx, taskID, "declined by "+identity); err != nil { return err } diff --git a/internal/gateway/turn.go b/internal/gateway/turn.go index f9ad04d75..d618a53b6 100644 --- a/internal/gateway/turn.go +++ b/internal/gateway/turn.go @@ -134,13 +134,12 @@ type TurnRunnerConfig struct { // message, per platform. It reads the platform off the inbound rather than // closing over one, because a single Router serves every channel: a resolver // bound to a channel name received "web" for a Telegram turn, which left - // Subject.UserID always empty in production (archie-core-c1qx). + // Subject.UserID always empty in production. // // False (or a nil UserIdentity) means the platform carries no per-person // identity -- the dashboard's one bearer token, or a webhook route path, // which must never be treated as a person -- and the turn's memory Subject // gets no UserID, so its read is agent and global scope only - // (docs/prds/memory-engine-unification.md §3, §4). UserIdentity func(in Inbound) (memory.IdentityID, bool) } diff --git a/internal/gateway/turn_memory.go b/internal/gateway/turn_memory.go index b533a5184..31ddb1a67 100644 --- a/internal/gateway/turn_memory.go +++ b/internal/gateway/turn_memory.go @@ -30,16 +30,10 @@ type MemoryStore interface { Query(ctx context.Context, q domainmemory.Query) ([]domainmemory.Record, error) } -// renderMemory builds the turn's block body: a scope-only Query over -// subject.Scopes() (most specific first, per Subject.Scopes' own doc), bounded -// by memoryRecordsPerScope per scope and memoryBlockByteCap overall. -// -// This is synchronous, total, and never returns an error: docs/prds/ -// memory-engine-unification.md §4 requires the chat read path to degrade to -// an empty block on any engine failure, including a panic, rather than fail -// the turn -- a memory read is an enhancement to the prompt, never a -// precondition for answering. The recover here is that contract's only -// enforcement point; every caller below runs inside it. +// renderMemory builds the turn's block from a scope-only Query over +// subject.Scopes(), bounded by memoryRecordsPerScope per scope and +// memoryBlockByteCap overall. Any engine failure, including a panic, yields an +// empty block: memory never fails a turn. func renderMemory(ctx context.Context, store MemoryStore, subject domainmemory.Subject, log *slog.Logger) (block string) { if store == nil { return "" @@ -115,10 +109,9 @@ func renderMemoryRecords(records []domainmemory.Record, log *slog.Logger) string // -- see sessioncurator.Adapter) and the session's UserIdentity resolver. A // nil resolver, or one that returns false, yields UserID "" -- Subject.Scopes // then names only agent and global, never a wider fallback -// (docs/prds/memory-engine-unification.md §3, "fail closed"). // // It takes the whole inbound rather than its message because the resolver needs -// the platform the message arrived on (archie-core-c1qx). +// the platform the message arrived on. func (r *TurnRunner) resolveSubject(in Inbound) domainmemory.Subject { subject := domainmemory.Subject{AgentID: domainmemory.AgentID(r.BotUser)} if r.UserIdentity == nil { diff --git a/internal/gateway/turn_memory_tool.go b/internal/gateway/turn_memory_tool.go index 71082e5e6..e92e92f93 100644 --- a/internal/gateway/turn_memory_tool.go +++ b/internal/gateway/turn_memory_tool.go @@ -9,12 +9,9 @@ import ( "github.com/samcharles93/archie-core/internal/tools" ) -// MemoryWriteStore is the write surface the per-turn memory tool needs: -// Create/Update/Forget/List, the four operations docs/prds/ -// memory-engine-unification.md §5 maps the tool's create/update/delete/list -// actions onto. Narrowed from domainmemory.Store (which also carries Get, -// Query and Revisions) so this package's write path cannot accidentally -// reach for read operations the tool does not expose. +// MemoryWriteStore is the write surface the per-turn memory tool needs, narrowed +// from domainmemory.Store so the tool cannot reach operations it does not +// expose. type MemoryWriteStore interface { Create(ctx context.Context, in domainmemory.NewRecord) (domainmemory.Record, error) Update(ctx context.Context, in domainmemory.RecordUpdate) (domainmemory.Record, error) @@ -50,7 +47,6 @@ func recordSummary(r domainmemory.Record) MemoryRecordSummary { // MemoryTools builds the chat tools that let the model manage its own // durable memory, scoped to one turn's resolved Subject -// (docs/prds/memory-engine-unification.md §5). // // Built per turn, not registered once at boot, because the writable scope // set is a function of the turn's Subject: two different users talking to diff --git a/internal/infrastructure/access/engine.go b/internal/infrastructure/access/engine.go index 460b8c3de..584ffd955 100644 --- a/internal/infrastructure/access/engine.go +++ b/internal/infrastructure/access/engine.go @@ -3,7 +3,7 @@ // validation against the shipped Cedar schema, and the chain evaluation: // instance ▶ org ▶ workspace ▶ object, where a level with policies must // permit, a forbid at any level wins, and with no permit the request is -// denied (docs/prds/orgs-and-access.md). +// denied. // // The cross-org forbid is enforced here, structurally, before any Cedar // runs: a principal never reaches a resource outside its org. It is not a @@ -50,7 +50,6 @@ const schemaText = `namespace Archie { // Problem is one stored policy the engine could not validate. It is what a // health issue names: the policy and the error -// (docs/prds/orgs-and-access.md, "Storing and changing policies"). type Problem struct { Policy access.Policy Err error diff --git a/internal/infrastructure/agenttransport/nats/transport.go b/internal/infrastructure/agenttransport/nats/transport.go index 7a460a898..e427cffcb 100644 --- a/internal/infrastructure/agenttransport/nats/transport.go +++ b/internal/infrastructure/agenttransport/nats/transport.go @@ -23,11 +23,10 @@ import ( "github.com/samcharles93/archie-core/internal/worktreerpc" ) -// Config contains the broker endpoint and credential for the worker -// transport, plus the State Store gRPC target (docs/prds/ -// state-store-contract.md §6). StateStoreURL is required: the agent is fully -// on gRPC for its store calls, and the legacy NATS storerpc path is deleted -// (docs/prds/state-store-contract.md §12 step 4). +// Config contains the broker endpoint and credential for the worker transport, +// plus the State Store gRPC target. StateStoreURL is required: the agent is +// fully on gRPC for its store calls, and the legacy NATS storerpc path is +// deleted type Config struct { URL string Token string @@ -63,7 +62,7 @@ type Transport struct { // Connect establishes the worker's core-NATS connection and, when // Config.StateStoreURL is set, a long-lived gRPC connection to the State -// Store (docs/prds/state-store-contract.md §6, §9). A non-loopback +// Store. A non-loopback // StateStoreURL with no token fails closed rather than dialing an // unauthenticated remote store. func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport, error) { @@ -87,10 +86,9 @@ func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport, } log.Info("worker transport connected", "url", conn.ConnectedUrl()) - // The agent is fully on gRPC for its store calls; the legacy NATS - // storerpc path is deleted (docs/prds/state-store-contract.md §12 step - // 4). A missing StateStoreURL fails fast rather than letting Store() - // hand back a client over a nil connection. + // The agent is fully on gRPC for its store calls; the legacy NATS storerpc + // path is deleted. A missing StateStoreURL fails fast rather than letting + // Store() hand back a client over a nil connection. if config.StateStoreURL == "" { conn.Close() return nil, fmt.Errorf("state store target is required: archie-agent no longer supports the legacy NATS storerpc path (docs/prds/state-store-contract.md §12 step 4)") @@ -146,9 +144,9 @@ func (t *Transport) Forger(identity string, timeout time.Duration) workflow.Forg } // Store constructs the workflow store RPC client over the long-lived State -// Store client (docs/prds/state-store-contract.md §6). Each call is bounded +// Store client. Each call is bounded // by timeout when the caller's context carries no deadline of its own. The -// legacy NATS storerpc path is deleted (§12 step 4); a transport without a +// legacy NATS storerpc path is deleted; a transport without a // State Store client cannot reach Store() because Connect refused to build // one. func (t *Transport) Store(timeout time.Duration) workflow.Store { @@ -156,7 +154,7 @@ func (t *Transport) Store(timeout time.Duration) workflow.Store { } // Calls constructs the workflow.call RPC client over the same long-lived -// State Store client (docs/prds/workflow-calls.md), bounded by timeout the +// State Store client, bounded by timeout the // same way Store() is. func (t *Transport) Calls(timeout time.Duration) task.Caller { return deadlineCaller{Caller: t.state, timeout: timeout} diff --git a/internal/infrastructure/bindingcipher/cipher.go b/internal/infrastructure/bindingcipher/cipher.go index 48f090ef2..50b201859 100644 --- a/internal/infrastructure/bindingcipher/cipher.go +++ b/internal/infrastructure/bindingcipher/cipher.go @@ -25,7 +25,7 @@ const bindingNonceLen = 12 // Domain is an envelope's marker and additional-authenticated-data: the // separator that stops a ciphertext sealed for one column being relocated to -// a different one and still authenticating (docs/prds/binding-secret-encryption.md). +// a different one and still authenticating. // Domains share the same keyring; only the marker and AAD differ. type Domain struct { marker string @@ -40,7 +40,7 @@ var ( // meaningful attack. BindingDomain = Domain{marker: "arcie-binding", aad: []byte("arcie-binding-secret")} // HarnessSecretDomain seals harness OAuth token sets - // (docs/prds/external-agent-harness.md, Credentials) -- its own + // -- its own // separator, so a row cannot be moved from oauth_secrets into a // bindings-secret column (or back) and still authenticate. HarnessSecretDomain = Domain{marker: "arcie-harness", aad: []byte("arcie-harness-secret")} diff --git a/internal/infrastructure/captureintake/receiver.go b/internal/infrastructure/captureintake/receiver.go index 7c4ff84be..df78d3885 100644 --- a/internal/infrastructure/captureintake/receiver.go +++ b/internal/infrastructure/captureintake/receiver.go @@ -1,11 +1,11 @@ // Package captureintake is the HTTP receiver for inbound webhooks archie has // no binding for yet: it persists what arrives so an operator can inspect it -// and build one (docs/prds/event-capture-storage.md). +// and build one. // // It belongs to the process that owns work intake, not to the dashboard that // displays captures. It served from the dashboard's listener while the two // shared a process; the split gives the read to the dashboard, over the State -// Store, and keeps the write here (archie-core-8cda.5.4). From the cutover +// Store, and keeps the write here. From the cutover // change in the same bead it is a persistence shim over the State Store // contract mounted by the UI process -- the only dashboard listener left -- // while the daemon's binding-dispatch loop consumes captures from the same @@ -117,8 +117,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // A body that isn't JSON has no key-value structure for the heuristic to // match against, so there is nothing to redact -- store it as received - // rather than dropping or mangling it. Best-effort, per - // docs/prds/webhook-intake-security.md point 5. + // rather than dropping or mangling it. Best-effort. redactedBody, err := webhookguard.RedactPayload(body) if err != nil { redactedBody = body @@ -141,13 +140,8 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } // Reuses the existing activity-event pipeline rather than inventing - // separate push plumbing -- see docs/prds/event-capture-storage.md. - // Deliberately LIGHTWEIGHT: the events table this feeds has no retention - // or row-count prune, unlike captured_events, so embedding the full (up - // to MaxBodyBytes) body/headers here would duplicate the payload into an - // unbounded table and defeat InsertCapture's own disk-bound guarantee. - // The captures view treats this purely as an invalidation signal and - // refetches the list for the actual row data. + // separate push plumbing. The captures view treats this purely as an + // invalidation signal and refetches the list for the actual row data. if rc.Publish != nil { rc.Publish(r.Context(), events.Event{ Kind: "capture", @@ -204,13 +198,7 @@ func (rc *Receiver) logger() *slog.Logger { } // fallbackMaxBodyBytes bounds a capture body when MaxBodyBytes is left unset -// (zero). The size cap is the only one of the three disk-bound mechanics in -// docs/prds/event-capture-storage.md that limits a SINGLE payload rather than -// total row count or write rate -- a table pruned to maxEvents rows still -// holds one arbitrarily large row if nothing ever bounded that row's size, so -// this must never be skippable by a missing wiring value the way the rate -// limiter (best-effort, not disk-bound-load-bearing on its own) is allowed to -// be. +// (zero). const fallbackMaxBodyBytes = 256 * 1024 func maxBodyBytesOrFallback(configured int64) int64 { diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index 8eb1468b6..a5b41a7d3 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -38,9 +38,7 @@ const ( // small enough that a large download cannot occupy the daemon. defaultWebFetchMaxBytes = 2_000_000 - // Capture defaults, per docs/prds/event-capture-storage.md's disk-bound - // mechanics: retention + row cap + per-request size cap + per-source - // rate limit, composed. + // Capture defaults. defaultCaptureRetention = 7 * 24 * time.Hour defaultCaptureMaxEvents = 5000 defaultCaptureMaxBodyBytes = 256 * 1024 @@ -121,8 +119,8 @@ func applyMemoryDefaults(cfg *config.Config) { } } -// DefaultCapture returns the webhook capture endpoint's default settings -// (docs/prds/event-capture-storage.md). applyCaptureDefaults fills a decoded +// DefaultCapture returns the webhook capture endpoint's default settings. +// applyCaptureDefaults fills a decoded // config with them; the UI process composes the same capture receiver and // must produce the same effective values when it is driven by flags alone // and no configuration file projected [capture] to it. diff --git a/internal/infrastructure/configuration/denied_keys.go b/internal/infrastructure/configuration/denied_keys.go index 4b1c65d77..7f0a00649 100644 --- a/internal/infrastructure/configuration/denied_keys.go +++ b/internal/infrastructure/configuration/denied_keys.go @@ -7,7 +7,7 @@ package configuration // API returns 4xx) and again in the overlay's Set, not silently dropped at // read time. Owned here rather than in the overlay package so the webui // config renderer can reference the policy without linking the overlay's -// SQLite store (archie-core-8cda.5.6). +// SQLite store. var DeniedKeys = map[string]string{ "database_url": "required for bootstrap; cannot be changed at runtime", "state_dir": "required for bootstrap; cannot be changed at runtime", diff --git a/internal/infrastructure/configuration/doc.go b/internal/infrastructure/configuration/doc.go index 2f6bb6736..a06337b8e 100644 --- a/internal/infrastructure/configuration/doc.go +++ b/internal/infrastructure/configuration/doc.go @@ -13,18 +13,16 @@ // # Why this package exists // // Loading used to live inside internal/config, alongside the runtime types -// every package imports. That made the shared model responsible for file -// I/O, so a package that merely wanted a settings struct also pulled in a -// TOML decoder, and defaulting, validation and decoding were interleaved in -// one function. See docs/architecture/configuration.md. +// every package imports. That made the shared model responsible for file I/O, +// so a package that merely wanted a settings struct also pulled in a TOML +// decoder, and defaulting, validation and decoding were interleaved in one +// function. // // # The temporary seam // -// docs/architecture/configuration.md requires a private input document that -// is translated into per-domain settings and never returned as the -// application's runtime model. [Document.Config] is not that yet: it is the -// existing internal/config.Config, exposed here so this package can take -// over loading without every consumer changing at once. +// [Document.Config] is not that yet: it is the existing internal/config.Config, +// exposed here so this package can take over loading without every consumer +// changing at once. // // It is deliberately a named field rather than a bare return value so the // compromise is visible at each use site. It should be replaced by typed diff --git a/internal/infrastructure/configuration/loader.go b/internal/infrastructure/configuration/loader.go index 758298a5c..ec996ef20 100644 --- a/internal/infrastructure/configuration/loader.go +++ b/internal/infrastructure/configuration/loader.go @@ -16,9 +16,7 @@ import ( type Document struct { // Config is the translated settings. // - // TEMPORARY. docs/architecture/configuration.md requires this to become - // typed per-domain sections that never expose a whole-application model. - // It stays for now so this package can own loading without every + // TEMPORARY. It stays for now so this package can own loading without every // consumer changing at once. Delete when internal/config is dissolved. Config config.Config // Scheduling is the decoded [scheduling] input. Application composition @@ -402,11 +400,7 @@ func (l *Loader) loadDir(doc *Document, dir string, layer Layer) error { return nil } -// decodeMain decodes the daemon-level file in whichever format it uses. An -// overlay layer's file is FOLDED over what the base layer decoded, the same way -// a single overlay file folds over its base -- otherwise a map-valued entry it -// only partly addresses would clear the fields it does not name, which is the -// archie-core-e2e2 failure on the directory form of the same flag. +// decodeMain decodes the daemon-level file in whichever format it uses. func (l *Loader) decodeMain(doc *Document, path string, isYAMLFile bool, layer Layer) error { if layer == LayerOverlay { cfgKeys, err := applyOverlayFile(path, &doc.Config) diff --git a/internal/infrastructure/configuration/setup/step_provider.go b/internal/infrastructure/configuration/setup/step_provider.go index 408495976..d9ecc8640 100644 --- a/internal/infrastructure/configuration/setup/step_provider.go +++ b/internal/infrastructure/configuration/setup/step_provider.go @@ -10,12 +10,8 @@ import ( ) // cloudProvider is one selectable cloud LLM provider: the config class it -// writes and the env var name its secret is stored under. Both the -// provider step (which writes providers..api_key = {engine, key}) -// and the secret sink (which is asked to store the value under exactly -// that key) read from this single table, so the two can never name the -// secret differently -- the exact class of bug archie-core-cbk exists to -// close for forge tokens, applied the same way to provider keys. +// writes and the env var its secret is stored under. The provider step and the +// secret sink both read this table, so they always name the same secret. type cloudProvider struct { name string class string diff --git a/internal/infrastructure/configuration/tomlwrite/tomlwrite.go b/internal/infrastructure/configuration/tomlwrite/tomlwrite.go index ebb22dfad..0ac8eecc3 100644 --- a/internal/infrastructure/configuration/tomlwrite/tomlwrite.go +++ b/internal/infrastructure/configuration/tomlwrite/tomlwrite.go @@ -4,14 +4,12 @@ // // # Why not decode/re-marshal // -// BurntSushi/toml (this project's TOML library, and every other Go TOML -// encoder evaluated for archie-core-rs9) does not round-trip comments: a -// Decode followed by an Encode reproduces the data but discards every -// comment. config.example.toml carries substantial documentation as inline -// comments that operators are meant to read and hand-edit, and archied -// setup must be able to write into that same file -- and be re-run later -// to change one value -- without deleting it. A full re-marshal was -// rejected for that reason (archie-core-rs9). +// BurntSushi/toml does not round-trip comments: a Decode followed by an Encode +// reproduces the data but discards every comment. config.example.toml carries +// substantial documentation as inline comments that operators are meant to read +// and hand-edit, and archied setup must be able to write into that same file -- +// and be re-run later to change one value -- without deleting it. A full +// re-marshal was rejected for that reason. // // # The chosen strategy // @@ -25,14 +23,11 @@ // the document). Every line Apply was not asked to touch is copied through // unchanged, byte for byte. // -// This trades generality for the property archie-core-rs9 requires: a -// second setup run that changes one value leaves every other line -- -// comments included -- identical to the first run's output. It only -// understands single-line scalar and inline-table values (strings, +// It only understands single-line scalar and inline-table values (strings, // numbers, booleans, `{ engine = "...", key = "..." }` secret refs), which // covers everything archied setup writes. Multi-line arrays and -// [[array-of-tables]] entries are not targets for Apply; other code paths -// (e.g. adding a [[repos]] entry) must not use it. +// [[array-of-tables]] entries are not targets for Apply; other code paths (e.g. +// adding a [[repos]] entry) must not use it. package tomlwrite import ( diff --git a/internal/infrastructure/configuration/validate.go b/internal/infrastructure/configuration/validate.go index efaa76ab1..a3b30d72a 100644 --- a/internal/infrastructure/configuration/validate.go +++ b/internal/infrastructure/configuration/validate.go @@ -84,16 +84,14 @@ func validate(cfg *config.Config) error { // State Store. [Loader] applies this to every file source. // // It deliberately omits the settings the control plane stores, because a stale -// TOML value in one of them must not be able to fail a process's startup -// (docs/prds/runtime-control-plane.md, "Bootstrap, migration, and recovery": -// after migration, settings in TOML are ignored and cannot block State Store -// startup). archie-state-store resolves its file config and seeds the -// control-plane resources from that same document on a fresh database, and a -// seed it cannot validate is skipped rather than fatal -// (controlplane.Server.ImportConfig), so a check left here is a check that can -// still block it. Those checks live in validateDatabaseOwned and run on the -// effective document instead -- which is where the process that uses the value -// refuses it, and where the operator's fix is the file again. +// TOML value in one of them must not be able to fail a process's startup. +// archie-state-store resolves its file config and seeds the control-plane +// resources from that same document on a fresh database, and a seed it cannot +// validate is skipped rather than fatal (controlplane.Server.ImportConfig), so +// a check left here is a check that can still block it. Those checks live in +// validateDatabaseOwned and run on the effective document instead -- which is +// where the process that uses the value refuses it, and where the operator's +// fix is the file again. func validateBootstrap(cfg *config.Config) error { if err := validateForgeIntake(cfg); err != nil { return err @@ -394,7 +392,6 @@ func validateSingleIdentity(cfg *config.Config) error { // the only point the value being judged is the one a process will use. The // per-identity lists are verified there for a different reason: no resource // carries them, and the daemon is the only process that reads them -// (docs/architecture/configuration.md's IdentityConfig note). func validateRepositoryContents(cfg *config.Config) error { if len(cfg.Identities) == 0 { return ValidateRepositories(cfg.Repos) diff --git a/internal/infrastructure/controlplanerpc/client.go b/internal/infrastructure/controlplanerpc/client.go index 91a307279..95baea6f7 100644 --- a/internal/infrastructure/controlplanerpc/client.go +++ b/internal/infrastructure/controlplanerpc/client.go @@ -2,7 +2,7 @@ // contract: the generic resource client, the channel-settings document it // projects, and the wire sentinels both sides match on. It exists so a service // that only reads stored settings does not link the store-backed server, the -// workflow engine or the SQLite driver (archie-core-1ng1). +// workflow engine or the SQLite driver. package controlplanerpc import ( diff --git a/internal/infrastructure/egress/grants.go b/internal/infrastructure/egress/grants.go index a7156ab8d..599d03174 100644 --- a/internal/infrastructure/egress/grants.go +++ b/internal/infrastructure/egress/grants.go @@ -5,12 +5,10 @@ import ( "sync" ) -// GrantResolver is the production Resolver: it holds, per active run, only -// the secrets a caller explicitly Grant-ed it -- the intersection a run -// credential carries (docs/prds/external-agent-harness.md, Credentials; -// docs/prds/orgs-and-access.md, "Agents: decided once, carried as a run -// credential"). It never derives a secret from anything else, so a service -// nobody granted, or granted to a different run, always answers ErrUnbound. +// GrantResolver is the production Resolver: it holds, per active run, only the +// secrets a caller explicitly Grant-ed it -- the intersection a run credential +// carries. It never derives a secret from anything else, so a service nobody +// granted, or granted to a different run, always answers ErrUnbound. type GrantResolver struct { mu sync.RWMutex grants map[string]map[string]string diff --git a/internal/infrastructure/egress/oauth.go b/internal/infrastructure/egress/oauth.go index 23134d5c3..dfd5e82e1 100644 --- a/internal/infrastructure/egress/oauth.go +++ b/internal/infrastructure/egress/oauth.go @@ -22,7 +22,7 @@ import ( const maxTokenExchange = 1 << 20 // OAuthStore persists one org's OAuth token set per credential binding -// service (docs/prds/external-agent-harness.md, Credentials). It is +// service. It is // storecontract.HarnessSecretStore's method set, declared narrow here. type OAuthStore interface { GetHarnessSecret(ctx context.Context, org, service string) (harnesssecret.Secret, error) diff --git a/internal/infrastructure/eventbus/nats/doc.go b/internal/infrastructure/eventbus/nats/doc.go index 3f65cce01..0f2f163a5 100644 --- a/internal/infrastructure/eventbus/nats/doc.go +++ b/internal/infrastructure/eventbus/nats/doc.go @@ -9,7 +9,6 @@ // Callers receive [Message], not jetstream.Msg, and publish [TaskEnvelope] or // [Request], not *nats.Msg. That keeps the broker replaceable and stops SDK // types leaking into domain packages, per -// docs/architecture/dependencies-and-contracts.md. // // Layout: // diff --git a/internal/infrastructure/eventbus/nats/embedded.go b/internal/infrastructure/eventbus/nats/embedded.go index d2aaf8571..149282274 100644 --- a/internal/infrastructure/eventbus/nats/embedded.go +++ b/internal/infrastructure/eventbus/nats/embedded.go @@ -16,7 +16,7 @@ import ( // // The daemon embeds one of these for single-process deployments so reaction // delivery and task distribution share the same transport whether NATS runs -// as a separate server or in-process (docs/prds/embedded-nats.md). The daemon +// as a separate server or in-process. The daemon // owns the lifecycle: StartEmbedded before dialing the client, Shutdown after // the client closes. type EmbeddedServer struct { diff --git a/internal/infrastructure/gatewayrpc/auth.go b/internal/infrastructure/gatewayrpc/auth.go index 4121b64c0..2e3a18013 100644 --- a/internal/infrastructure/gatewayrpc/auth.go +++ b/internal/infrastructure/gatewayrpc/auth.go @@ -14,7 +14,7 @@ import ( // tokenMetadataKey is the gRPC metadata key the Gateway Bearer [REDACTED] // travels in. Metadata, never a URL, mirroring the State Store's -// token lifecycle (docs/prds/state-store-contract.md §9). +// token lifecycle. const tokenMetadataKey = "gateway-token" // TargetIsLoopback reports whether addr's host is a loopback address. Both diff --git a/internal/infrastructure/kit/credential_file.go b/internal/infrastructure/kit/credential_file.go index 84accdc87..2b9fa9a89 100644 --- a/internal/infrastructure/kit/credential_file.go +++ b/internal/infrastructure/kit/credential_file.go @@ -28,13 +28,11 @@ const ( credentialFileMode = "0600" ) -// renderCredentialFile renders c's oauth.credentialFile: the declared -// structure with the Kit's sentinels substituted for the token placeholders, -// the stored token set's scopes for {{.Scopes}} and its expiry for -// {{.ExpiresAt}}, encoded in the declared format. facts is the only thing the -// renderer receives about the stored token set, so a real token cannot reach -// the file (docs/prds/external-agent-harness.md, "Verification: the credential -// file holds only sentinels"). +// renderCredentialFile renders c's oauth.credentialFile: the declared structure +// with the Kit's sentinels substituted for the token placeholders, the stored +// token set's scopes for {{.Scopes}} and its expiry for {{.ExpiresAt}}, encoded +// in the declared format. facts is the only thing the renderer receives about +// the stored token set, so a real token cannot reach the file. func renderCredentialFile(c spec.CredentialCapability, facts OAuthFacts) (string, error) { cf := c.OAuth.CredentialFile var sentinels spec.Sentinels diff --git a/internal/infrastructure/kit/kit.go b/internal/infrastructure/kit/kit.go index 9f3cc21ac..f4ac4865d 100644 --- a/internal/infrastructure/kit/kit.go +++ b/internal/infrastructure/kit/kit.go @@ -152,7 +152,7 @@ func FromMerge(merged *spec.MergeResult) (*Plan, error) { } // ValidateNeeds rejects a Plan that cannot meet what the workflow's stages -// declared they need (docs/prds/external-agent-harness.md, "Contract"): a +// declared they need: a // gate that may retry needs the Kit's agent-sessions resume verb, because // archie resumes the session with the gate's output rather than starting // over. gateRetries is zero for a workflow with no gated stage, which no diff --git a/internal/infrastructure/kitrun/launcher.go b/internal/infrastructure/kitrun/launcher.go index a4202359b..136bff16b 100644 --- a/internal/infrastructure/kitrun/launcher.go +++ b/internal/infrastructure/kitrun/launcher.go @@ -42,7 +42,6 @@ type Grants interface { // Kit's credential file can render that set's expiry. It is the store's read // half only: kitrun never writes a token set, and nothing but the expiry // leaves oauthExpiries, so a real token cannot reach the credential file -// (docs/prds/external-agent-harness.md, "Verification"). type OAuthSecrets interface { GetHarnessSecret(ctx context.Context, org, service string) (harnesssecret.Secret, error) } @@ -66,11 +65,9 @@ type Launcher struct { // construction: credential bindings are their own live control-plane // resource (controlplane.CredentialBindingsKind), so a binding added or // changed after this daemon started must take effect on the very next - // dispatch, the same way an agent profile already does - // (docs/prds/external-agent-harness.md, "Selection": applies without a - // restart). A nil Secrets or Grants degrades every credential to unbound - // rather than panicking: a daemon with no Kit profile configured wires - // neither. + // dispatch, the same way an agent profile already does. A nil Secrets or + // Grants degrades every credential to unbound rather than panicking: a + // daemon with no Kit profile configured wires neither. Config *config.Holder Secrets SecretResolver Grants Grants @@ -100,13 +97,10 @@ type Request struct { // a positive one, and Launch refuses it rather than starting a // container no gate failure could ever resume. GateRetries int - // Org and GrantedServices are the dispatching identity's own facts - // (config.Config.Org, config.Config.GrantedCredentials), carried here - // because kitrun holds no store or config of its own. Launch resolves a - // Kit credential only where these agree with a configured - // CredentialBinding and the Kit's own declared service -- the - // declared-and-granted intersection docs/prds/external-agent-harness.md - // and orgs-and-access.md both require; neither side widens the other. + // Org and GrantedServices are the dispatching identity's own facts. A Kit + // credential resolves only where these agree with a configured + // CredentialBinding and the Kit's declared service; neither side widens the + // other. Org string GrantedServices []string } diff --git a/internal/infrastructure/memory/builtin_engine.go b/internal/infrastructure/memory/builtin_engine.go index 9f1a83a13..24108d7be 100644 --- a/internal/infrastructure/memory/builtin_engine.go +++ b/internal/infrastructure/memory/builtin_engine.go @@ -1,8 +1,7 @@ -// Package memory implements domain/memory.MemoryEngine over concrete -// backends. The builtin engine persists each scope's records as markdown -// under its root -- human-readable and hand-editable -- with a per-scope -// HISTORY.md retaining the states that are no longer live. See -// docs/prds/memory-engine-unification.md for the decision this implements. +// Package memory implements domain/memory.MemoryEngine over concrete backends. +// The builtin engine persists each scope's records as markdown under its root +// -- human-readable and hand-editable -- with a per-scope HISTORY.md retaining +// the states that are no longer live. package memory import ( @@ -45,7 +44,6 @@ const defaultQueryLimit = 100 // contentScanner is the family's content scanner, applied in Create and // Update. Those two are the one choke point every producer crosses, so the // curator's model-extracted content is covered as well as the chat tool's -// (docs/prds/memory-engine-unification.md §7). var contentScanner domainmemory.Scanner = &domainmemory.DefaultScanner{} // scopeStores is one scope's on-disk pair: the heads, and the states that @@ -403,13 +401,13 @@ func (e *BuiltinEngine) Update(_ context.Context, in domainmemory.RecordUpdate) } // Read the document as it is on disk before anything is decided from it. - // This engine caches the scope's document and rewrites it whole (the PRD - // leaves "two processes, one scope file" undecided), so the copy it holds - // can be a whole write out of date -- the Expected check below would - // compare against a revision that is already superseded, and the rewrite - // that follows it would write the stale copy back over the current one. - // What this does not fix: the rewrite is still last-writer-wins for this - // record and every other one, between the reload and the write. + // This engine caches the scope's document and rewrites it whole, so the + // copy it holds can be a whole write out of date -- the Expected check + // below would compare against a revision that is already superseded, and + // the rewrite that follows it would write the stale copy back over the + // current one. What this does not fix: the rewrite is still + // last-writer-wins for this record and every other one, between the reload + // and the write. if err := stores.live.Reload(); err != nil { return domainmemory.Record{}, err } @@ -436,7 +434,6 @@ func (e *BuiltinEngine) Update(_ context.Context, in domainmemory.RecordUpdate) // Crash safety, in this order: the superseded state is durable in // HISTORY.md before the live block is touched. A crash between the two // leaves an extra history entry and an unchanged record -- recoverable, - // per §2 -- and never a record whose previous state is gone. if err := appendHistory(stores.history, current.marker, current.content(), now, false); err != nil { return domainmemory.Record{}, err } diff --git a/internal/infrastructure/memory/history.go b/internal/infrastructure/memory/history.go index 48e6b65bb..efc42b518 100644 --- a/internal/infrastructure/memory/history.go +++ b/internal/infrastructure/memory/history.go @@ -11,7 +11,6 @@ import ( // historyFileName is the second document in each scope's directory: every // state the scope's records no longer live in -- superseded by an Update, or // removed by a Forget -- so a record's provenance outlives its content -// (docs/prds/memory-engine-unification.md §2). const historyFileName = "HISTORY.md" // historySectionName is the single section every retained state is appended @@ -23,14 +22,10 @@ const historySectionName = "history" // the live document's bound (builtin's 100KB default, which is what // production passes: bootstrap builds the engine with a 0 maxFileBytes). // -// It has its own bound because history grows on every Update and every -// Forget while the live document does not. Inheriting the live document's -// bound would make a scope start refusing updates after a handful of -// revisions of one large record -- trading the PRD's open "unbounded -// history" question ("Not determined", no compaction policy) for a new -// failure mode at the point of write. That question stays open; this bound -// only makes reaching it a deliberate, enormous amount of history rather -// than an accident. +// It has its own bound because history grows on every Update and every Forget +// while the live document does not. That question stays open; this bound only +// makes reaching it a deliberate, enormous amount of history rather than an +// accident. const historyMaxFileBytes = 4 * 1024 * 1024 // appendHistory appends one retained state -- the record as it was while @@ -54,7 +49,7 @@ func appendHistory(h *builtin.Store, m markerData, content string, at time.Time, // oldest first. Document order is append order, and a retained state is // appended exactly when it stops being live, so no sort is needed -- or // wanted: a crash between a history append and the live write leaves two -// entries for one revision (§2, recoverable), and sorting would not make +// entries for one revision, and sorting would not make // that less true. func revisionsOf(h *builtin.Store, scope domainmemory.Scope, id domainmemory.RecordID) []domainmemory.Revision { var revisions []domainmemory.Revision diff --git a/internal/infrastructure/memory/marker.go b/internal/infrastructure/memory/marker.go index 300c610dc..12c1247ef 100644 --- a/internal/infrastructure/memory/marker.go +++ b/internal/infrastructure/memory/marker.go @@ -8,14 +8,9 @@ import ( "time" ) -// The engine writes each record as one blank-line-delimited markdown block -// whose first line is a marker comment followed by the record's content, so -// a block stays readable and editable by hand. The marker began life as a -// bare id (``, the incumbent format); it is JSON now -// because the retained provenance -- revision, kind, author, originating -// user, source and both timestamps -- has nowhere else to live, which is -// exactly what the PRD's Settles table records the bare form could not -// carry. +// Each record is one blank-line-delimited markdown block whose first line is a +// JSON marker comment carrying the record's provenance, followed by its +// content, so a block stays editable by hand. const ( markerPrefix = "" diff --git a/internal/infrastructure/postgres/access.go b/internal/infrastructure/postgres/access.go index f002e8465..c6869ac18 100644 --- a/internal/infrastructure/postgres/access.go +++ b/internal/infrastructure/postgres/access.go @@ -1,6 +1,6 @@ // Access policies and denial records: the Postgres implementation of -// internal/domain/access's PolicyStore, Resetter and DenialStore -// (docs/prds/orgs-and-access.md). Policy changes are versioned per level +// internal/domain/access's PolicyStore, Resetter and DenialStore. +// Policy changes are versioned per level // scope and audited as one sys_audit row per change naming who made it. package postgres diff --git a/internal/infrastructure/postgres/orgs.go b/internal/infrastructure/postgres/orgs.go index c0bfc59ea..af9be40ec 100644 --- a/internal/infrastructure/postgres/orgs.go +++ b/internal/infrastructure/postgres/orgs.go @@ -1,7 +1,6 @@ // Orgs, workspaces, memberships and agent assignments: the Postgres // implementation of internal/domain/org's contracts, plus the resumable // default org/workspace upgrade the State Store runs at boot -// (docs/prds/orgs-and-access.md, "Upgrading existing installs"). // // The upgrade refuses nothing itself; the refusal to serve scoped calls // until it has finished is enforced by the boot order -- the State Store diff --git a/internal/infrastructure/postgres/pgtest/pgtest.go b/internal/infrastructure/postgres/pgtest/pgtest.go index 68f8933c4..bcf8b25b0 100644 --- a/internal/infrastructure/postgres/pgtest/pgtest.go +++ b/internal/infrastructure/postgres/pgtest/pgtest.go @@ -1,8 +1,6 @@ // Package pgtest runs a throwaway PostgreSQL 18 container for one test binary // and gives each test its own database on it. // -// A package using it calls Main from TestMain: -// // func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) } // // It needs a running Docker daemon. diff --git a/internal/infrastructure/postgres/postgresdb/access.sql.go b/internal/infrastructure/postgres/postgresdb/access.sql.go index 67be055d2..f53302714 100644 --- a/internal/infrastructure/postgres/postgresdb/access.sql.go +++ b/internal/infrastructure/postgres/postgresdb/access.sql.go @@ -19,9 +19,6 @@ type CountShippedOrgPoliciesParams struct { Column2 []string } -// How many of an org's shipped role policies are stored. The seeding runs -// only when the org carries none of them, so a restart never overwrites an -// edited role policy (the shipped IDs are reserved for the shipped text). func (q *Queries) CountShippedOrgPolicies(ctx context.Context, arg CountShippedOrgPoliciesParams) (int64, error) { row := q.db.QueryRow(ctx, countShippedOrgPolicies, arg.OrgID, arg.Column2) var count int64 @@ -72,7 +69,6 @@ type DeleteAccessPolicyVersionParams struct { WorkspaceID string } -// Tidy a level-scope with no policies left: its version row has no reader. func (q *Queries) DeleteAccessPolicyVersion(ctx context.Context, arg DeleteAccessPolicyVersionParams) error { _, err := q.db.Exec(ctx, deleteAccessPolicyVersion, arg.Level, arg.OrgID, arg.WorkspaceID) return err @@ -88,8 +84,6 @@ type DeleteOrgPoliciesNotShippedParams struct { Column2 []string } -// The org reset's removal half: every org-level policy except the shipped -// role set. func (q *Queries) DeleteOrgPoliciesNotShipped(ctx context.Context, arg DeleteOrgPoliciesNotShippedParams) error { _, err := q.db.Exec(ctx, deleteOrgPoliciesNotShipped, arg.OrgID, arg.Column2) return err @@ -139,8 +133,6 @@ type InsertAccessPolicyAuditParams struct { RequestID string } -// One audit row per policy change: the policy's old and new text -// (docs/prds/orgs-and-access.md, "Storing and changing policies"). func (q *Queries) InsertAccessPolicyAudit(ctx context.Context, arg InsertAccessPolicyAuditParams) error { _, err := q.db.Exec(ctx, insertAccessPolicyAudit, arg.RecordKey, @@ -159,9 +151,6 @@ INSERT INTO sys_audit (at, table_name, record_key, field, record_version, actor, VALUES (now(), 'access_policies', $1, 'reset', 1, 'archied access reset', 'archied', '') ` -// The one audit row a reset is recorded as; the reset's policy changes -// carry their own rows (docs/prds/orgs-and-access.md, "Recovering from a -// locked-out org"). func (q *Queries) InsertAccessResetAudit(ctx context.Context, recordKey string) error { _, err := q.db.Exec(ctx, insertAccessResetAudit, recordKey) return err @@ -173,9 +162,7 @@ SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, upd FROM access_policies ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id ` -// Access policies and denial records (internal/domain/access): the durable -// half of the policy-chain contract. Versioning is per level-scope; every -// policy change writes one sys_audit row naming who made it. +// Access policies and denial records (internal/domain/access) func (q *Queries) ListAccessPolicies(ctx context.Context) ([]AccessPolicy, error) { rows, err := q.db.Query(ctx, listAccessPolicies) if err != nil { @@ -266,8 +253,6 @@ type RecordDenialParams struct { } // One row per (principal, action, resource, level, policies, minute); -// a repeat inside the minute bumps the count (docs/prds/orgs-and-access.md, -// "Audit retention"). func (q *Queries) RecordDenial(ctx context.Context, arg RecordDenialParams) error { _, err := q.db.Exec(ctx, recordDenial, arg.OrgID, diff --git a/internal/infrastructure/postgres/postgresdb/audit.sql.go b/internal/infrastructure/postgres/postgresdb/audit.sql.go index becd1d945..88d919337 100644 --- a/internal/infrastructure/postgres/postgresdb/audit.sql.go +++ b/internal/infrastructure/postgres/postgresdb/audit.sql.go @@ -81,8 +81,6 @@ type InsertResourceAuditParams struct { Value []byte } -// Records the fields one resource write changed, against the version it -// replaced. Runs in the write's own transaction. func (q *Queries) InsertResourceAudit(ctx context.Context, arg InsertResourceAuditParams) error { _, err := q.db.Exec(ctx, insertResourceAudit, arg.At, diff --git a/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go b/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go index bb57539ce..0bb086e0f 100644 --- a/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go +++ b/internal/infrastructure/postgres/postgresdb/call_tasks.sql.go @@ -54,15 +54,7 @@ type EnqueueCallTaskParams struct { MaxDepth int32 } -// The callee of a workflow.call step (docs/prds/workflow-calls.md). The -// caller row is read FOR UPDATE, so two steps of the same run cannot race a -// depth re-check, and the callee inherits the caller's org, workspace, -// identity, owner and repo: a called workflow works the same run's context -// under its own definition and profile. The issue number is a fresh -// synthetic one for the inherited owner/repo, the same allocator -// InsertChatTask uses. The insert refuses a caller that is not running and -// a call that would pass the depth limit (the engine checks it too; the -// store is what owns the table, so it re-checks). +// The callee of a workflow.call step (docs/prds/workflow-calls.md) func (q *Queries) EnqueueCallTask(ctx context.Context, arg EnqueueCallTaskParams) (Task, error) { row := q.db.QueryRow(ctx, enqueueCallTask, arg.ID, diff --git a/internal/infrastructure/postgres/postgresdb/edastore.sql.go b/internal/infrastructure/postgres/postgresdb/edastore.sql.go index af1df8abe..97076a03f 100644 --- a/internal/infrastructure/postgres/postgresdb/edastore.sql.go +++ b/internal/infrastructure/postgres/postgresdb/edastore.sql.go @@ -757,9 +757,6 @@ type ListUndispatchedCapturesParams struct { EntryLimit int32 } -// A capture is undispatched while some armed binding on its source, whose -// mapping belongs to the capture's event type, has not dispatched it. An -// unidentified capture has no event type, so it is never listed. func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispatchedCapturesParams) ([]Capture, error) { rows, err := q.db.Query(ctx, listUndispatchedCaptures, arg.Sources, arg.EntryLimit) if err != nil { diff --git a/internal/infrastructure/postgres/queries/access.sql b/internal/infrastructure/postgres/queries/access.sql index 6788796fd..cbe78ffce 100644 --- a/internal/infrastructure/postgres/queries/access.sql +++ b/internal/infrastructure/postgres/queries/access.sql @@ -1,6 +1,4 @@ --- Access policies and denial records (internal/domain/access): the durable --- half of the policy-chain contract. Versioning is per level-scope; every --- policy change writes one sys_audit row naming who made it. +-- Access policies and denial records (internal/domain/access) -- name: ListAccessPolicies :many SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at @@ -23,15 +21,10 @@ WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4 AND object_id = $5 AND policy_id = $6; -- name: CountShippedOrgPolicies :one --- How many of an org's shipped role policies are stored. The seeding runs --- only when the org carries none of them, so a restart never overwrites an --- edited role policy (the shipped IDs are reserved for the shipped text). SELECT count(*) FROM access_policies WHERE level = 'org' AND org_id = $1 AND policy_id = ANY($2::text[]); -- name: DeleteOrgPoliciesNotShipped :exec --- The org reset's removal half: every org-level policy except the shipped --- role set. DELETE FROM access_policies WHERE level = 'org' AND org_id = $1 AND NOT (policy_id = ANY($2::text[])); @@ -45,22 +38,17 @@ DO UPDATE SET version = access_policy_versions.version + 1, updated_at = now() RETURNING version; -- name: DeleteAccessPolicyVersion :exec --- Tidy a level-scope with no policies left: its version row has no reader. DELETE FROM access_policy_versions v WHERE v.level = $1 AND v.org_id = $2 AND v.workspace_id = $3 AND NOT EXISTS (SELECT 1 FROM access_policies p WHERE p.level = v.level AND p.org_id = v.org_id AND p.workspace_id = v.workspace_id); -- name: InsertAccessPolicyAudit :exec --- One audit row per policy change: the policy's old and new text --- (docs/prds/orgs-and-access.md, "Storing and changing policies"). INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id) VALUES (now(), 'access_policies', $1, 'text', $2, $3, $4, $5, $6, $7); -- name: RecordDenial :exec -- One row per (principal, action, resource, level, policies, minute); --- a repeat inside the minute bumps the count (docs/prds/orgs-and-access.md, --- "Audit retention"). INSERT INTO access_denials (org_id, principal, action, resource_kind, resource_id, level, policies) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at) @@ -69,9 +57,7 @@ DO UPDATE SET count = access_denials.count + 1, updated_at = now(); -- name: ListDenials :many SELECT id, org_id, principal, action, resource_kind, resource_id, level, policies, minute_at, count, created_at, updated_at FROM access_denials WHERE org_id = $1 ORDER BY id DESC LIMIT $2; + -- name: InsertAccessResetAudit :exec --- The one audit row a reset is recorded as; the reset's policy changes --- carry their own rows (docs/prds/orgs-and-access.md, "Recovering from a --- locked-out org"). INSERT INTO sys_audit (at, table_name, record_key, field, record_version, actor, source, request_id) VALUES (now(), 'access_policies', $1, 'reset', 1, 'archied access reset', 'archied', ''); diff --git a/internal/infrastructure/postgres/queries/audit.sql b/internal/infrastructure/postgres/queries/audit.sql index f87cce609..00f608b40 100644 --- a/internal/infrastructure/postgres/queries/audit.sql +++ b/internal/infrastructure/postgres/queries/audit.sql @@ -1,6 +1,4 @@ -- name: InsertResourceAudit :exec --- Records the fields one resource write changed, against the version it --- replaced. Runs in the write's own transaction. INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id) SELECT sqlc.arg(at)::timestamptz, 'resources', sqlc.arg(record_key)::text, d.field, d.old_value, d.new_value, sqlc.arg(version)::bigint, sqlc.arg(actor)::text, sqlc.arg(source)::text, sqlc.arg(request_id)::text diff --git a/internal/infrastructure/postgres/queries/call_tasks.sql b/internal/infrastructure/postgres/queries/call_tasks.sql index dd8e42069..0fd63eb24 100644 --- a/internal/infrastructure/postgres/queries/call_tasks.sql +++ b/internal/infrastructure/postgres/queries/call_tasks.sql @@ -1,13 +1,5 @@ -- name: EnqueueCallTask :one --- The callee of a workflow.call step (docs/prds/workflow-calls.md). The --- caller row is read FOR UPDATE, so two steps of the same run cannot race a --- depth re-check, and the callee inherits the caller's org, workspace, --- identity, owner and repo: a called workflow works the same run's context --- under its own definition and profile. The issue number is a fresh --- synthetic one for the inherited owner/repo, the same allocator --- InsertChatTask uses. The insert refuses a caller that is not running and --- a call that would pass the depth limit (the engine checks it too; the --- store is what owns the table, so it re-checks). +-- The callee of a workflow.call step (docs/prds/workflow-calls.md) WITH caller AS ( SELECT t.* FROM tasks t WHERE t.id = $1 FOR UPDATE ) diff --git a/internal/infrastructure/postgres/queries/edastore.sql b/internal/infrastructure/postgres/queries/edastore.sql index 810149d4d..eed534dc9 100644 --- a/internal/infrastructure/postgres/queries/edastore.sql +++ b/internal/infrastructure/postgres/queries/edastore.sql @@ -11,9 +11,6 @@ ORDER BY received_at DESC LIMIT $1; -- name: ListUndispatchedCaptures :many --- A capture is undispatched while some armed binding on its source, whose --- mapping belongs to the capture's event type, has not dispatched it. An --- unidentified capture has no event type, so it is never listed. SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type, c.org_id, c.workspace_id FROM captures c WHERE c.source = ANY(@sources::text[]) diff --git a/internal/infrastructure/postgres/steps.go b/internal/infrastructure/postgres/steps.go index d00f4fd3a..bf58241a9 100644 --- a/internal/infrastructure/postgres/steps.go +++ b/internal/infrastructure/postgres/steps.go @@ -16,13 +16,9 @@ import ( "github.com/samcharles93/archie-core/internal/taskstate" ) -// The step-execution writes of docs/prds/execution-tree-state-machine.md. -// Each is one transaction: the guarded row write, and the domain event row -// the step transition produces, so the events table records exactly the -// transitions the step row does. The events land in the table; the caller -// publishes the returned event to its bus after the write commits, and the -// daemon's event sink skips already-persisted rows by their assigned ID -- -// the EmitDurable convention. +// The events land in the table; the caller publishes the returned event to its +// bus after the write commits, and the daemon's event sink skips +// already-persisted rows by their assigned ID -- the EmitDurable convention. // StartStep records a StepExecution entering running: the row is created // pending, guarded into running under the shared step transition table, and @@ -251,7 +247,7 @@ func stepEventData(to taskstate.StepStatus, durationMS int64, detail string) map // ListSteps reads one execution's recorded steps, every attempt oldest first // when attempt is 0, or just the one it names. It is the dashboard run -// detail's authoritative source (docs/prds/execution-tree-state-machine.md), +// detail's authoritative source, // replacing the fold over stage_start/stage_finish events tasks.stage used to // back -- unlike StartStep/FinishStep, this is a plain read with no // transition to guard, so it takes no transaction. @@ -291,14 +287,14 @@ func stepParentID(parentID int64) pgtype.Int8 { return pgtype.Int8{Int64: parentID, Valid: parentID != 0} } -// CancelExecution is the one cancel path (docs/prds/execution-tree-state-machine.md, -// "Cancellation"): one transaction moves every non-terminal StepExecution of -// the execution's current attempt to cancelled -- one event row each -- and -// the execution itself to the status the operator action names, under the -// shared execution transition table. Staleness is decided before legality, as -// guardTransition decides it, and the audit row lands in the same write. The -// caller cancels the in-memory context after this commits; the worker's next -// step write then fails ErrStaleTransition and stops. +// CancelExecution is the one cancel path: one transaction moves every +// non-terminal StepExecution of the execution's current attempt to cancelled -- +// one event row each -- and the execution itself to the status the operator +// action names, under the shared execution transition table. Staleness is +// decided before legality, as guardTransition decides it, and the audit row +// lands in the same write. The caller cancels the in-memory context after this +// commits; the worker's next step write then fails ErrStaleTransition and +// stops. func (s *Store) CancelExecution(ctx context.Context, taskID int64, reason, to string) ([]int64, error) { tx, err := s.pool.Begin(ctx) if err != nil { diff --git a/internal/infrastructure/postgres/store.go b/internal/infrastructure/postgres/store.go index e3e131e1c..dedba3adf 100644 --- a/internal/infrastructure/postgres/store.go +++ b/internal/infrastructure/postgres/store.go @@ -40,8 +40,8 @@ func (s *Store) queries() *postgresdb.Queries { // guardTransition locks the task's row and checks the status write the caller // is about to perform: a row whose status is not the expected from is stale // (ErrStaleTransition), a from->to pair outside the shared transition table is -// refused with ErrIllegalTransition -// (docs/prds/execution-tree-state-machine.md). Staleness is decided first, so +// refused with ErrIllegalTransition. +// Staleness is decided first, so // a caller that is wrong about the row's state gets the stale sentinel even // when its pair is also unroutable. The row stays locked for the caller's // transaction, so the checks cannot race the guarded write that follows. @@ -78,7 +78,7 @@ const syntheticIssueNumberBase = 1_000_000_000_000_000 // structured payload (review_payload today, task outputs now). A value that // would exceed it is refused for outputs -- clipped JSON does not parse, and a // caller must receive an object or nothing -- where the legacy review payload -// is still clipped (docs/prds/workflow-call-outputs.md, "Storage and wire"). +// is still clipped. const structuredPayloadBytes = 4000 // taskFromRow maps the generated task row to the workflow.Task the daemon and @@ -295,7 +295,7 @@ func (s *Store) ParkTask(ctx context.Context, taskID int64, from, detail, class // Update persists mutable task fields written by workflows. func (s *Store) Update(ctx context.Context, t *workflow.Task) error { - // The row write is where a run's outputs land (docs/prds/workflow-call-outputs.md). + // The row write is where a run's outputs land. // An encoded set past the bound the store applies to a structured payload // is refused rather than clipped: clipped JSON does not parse, and a caller // would receive a broken object as a value. The engine turns the refusal @@ -414,8 +414,8 @@ func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, wf, ret }) } -// RespondReviewGate is the review gate response write -// (docs/prds/pr-review-operator-response.md, Decision 2): one guarded +// RespondReviewGate is the review gate response write: +// one guarded // requeue that records the operator's answer, increments rereview_rounds for // a re-review only, and writes one audit row -- all in one transaction. The // cap is checked under the row lock the transition guard takes, so two @@ -522,13 +522,9 @@ func (s *Store) ArchiveTask(ctx context.Context, taskID int64, fromStatus string // RecoverStale re-queues tasks left running by a crashed or replaced daemon // and, in the same transaction, moves the steps those executions left running -// to the step transition table's interrupted outcome -// (docs/prds/execution-tree-state-machine.md, "Crash recovery"): one event row -// per step transition and the execution's audit row land in the same write. -// Both edges are pinned in SQL (the execution's running->queued, the step's -// running->interrupted) and pinned to the tables by -// TestSQLPinnedTransitionsAreTableLegal. The next attempt starts with fresh -// steps; earlier attempts are never rewritten. +// to the step transition table's interrupted outcome: one event row per step +// transition and the execution's audit row land in the same write. The next +// attempt starts with fresh steps; earlier attempts are never rewritten. func (s *Store) RecoverStale(ctx context.Context) (int64, error) { tx, err := s.pool.Begin(ctx) if err != nil { @@ -675,8 +671,8 @@ func (s *Store) TaskByID(ctx context.Context, taskID int64) (*workflow.Task, err return taskFromRow(t), nil } -// StartCall enqueues the callee of callerTaskID's workflow.call step -// (docs/prds/workflow-calls.md). The store owns the table, so it re-checks +// StartCall enqueues the callee of callerTaskID's workflow.call step. +// The store owns the table, so it re-checks // both runtime invariants the engine checks: the caller must be running and // the call must not pass workflow.MaxCallDepth. The callee inherits the // caller's org, workspace, identity, owner and repo, and takes a fresh @@ -741,8 +737,8 @@ func (s *Store) CallStatus(ctx context.Context, callerTaskID, callTaskID int64) if callee.CallParentTaskID != callerTaskID { return "", "", nil, storecontract.ErrCallNotYours } - // The row is the callee's own; its outputs travel beside status and detail - // (docs/prds/workflow-call-outputs.md, "Storage and wire"). The caller + // The row is the callee's own; its outputs travel beside status and detail. + // The caller // decides whether to use them -- only a successful terminal state's values // reach it. outputs, _ := task.DecodeOutputs(callee.Outputs) diff --git a/internal/infrastructure/prsource/archive.go b/internal/infrastructure/prsource/archive.go index 475fc8938..66c5a0991 100644 --- a/internal/infrastructure/prsource/archive.go +++ b/internal/infrastructure/prsource/archive.go @@ -12,14 +12,13 @@ import ( "strings" ) -// extractTarGz extracts a gzipped tar stream into destDir, stripping a -// single common leading path component when every entry shares one (the -// wrapper directory GitHub's and Gitea's repository archives both add, -// named after the repo and ref -- e.g. "acme-widget-deadbeef/"). A .git -// entry is never written: PRSource's isolation contract (docs/prds/ -// pr-review-agent.md) requires the pipeline to read a .git-free snapshot, -// and a malicious PR's own tarball is exactly the input this cannot trust, -// so an entry escaping destDir via ".." or an absolute path is refused +// extractTarGz extracts a gzipped tar stream into destDir, stripping a single +// common leading path component when every entry shares one (the wrapper +// directory GitHub's and Gitea's repository archives both add, named after the +// repo and ref -- e.g. "acme-widget-deadbeef/"). A.git entry is never written: +// PRSource's isolation contract requires the pipeline to read a.git-free +// snapshot, and a malicious PR's own tarball is exactly the input this cannot +// trust, so an entry escaping destDir via ".." or an absolute path is refused // rather than silently written outside it. func extractTarGz(r io.Reader, destDir string) error { gz, err := gzip.NewReader(r) diff --git a/internal/infrastructure/prsource/prsource.go b/internal/infrastructure/prsource/prsource.go index 995a5d660..444eb5bbf 100644 --- a/internal/infrastructure/prsource/prsource.go +++ b/internal/infrastructure/prsource/prsource.go @@ -1,18 +1,14 @@ // Package prsource implements workflow.PRSource: fetching an arbitrary // external pull request's metadata, diff and a read-only snapshot of its -// head, for the pr-review pipeline (docs/prds/pr-review-agent.md). It is +// head, for the pr-review pipeline. It is // the PR-under-review counterpart to worktree.Manager's use as the task's // own Trees: that path only ever reaches the task's own worktree, never a // third-party PR being reviewed. // -// Every call goes over the forge's HTTP API -- never a git-shell checkout. -// The pipeline's Stage.Run bodies execute inside the sandboxed archie-agent -// process, which holds no forge credential and no git-level credential -// either; a git clone would need one. An HTTP call carries only whatever -// bearer token the forge client was constructed with, matching the PRD's -// Isolation rule ("no pipeline agent holds a forge credential") for the -// pipeline's own agent calls, while this package's construction site is the -// one place a forge-reading token is actually held. +// Every call goes over the forge's HTTP API -- never a git-shell checkout. The +// pipeline's Stage.Run bodies execute inside the sandboxed archie-agent +// process, which holds no forge credential and no git-level credential either; +// a git clone would need one. package prsource import ( @@ -59,10 +55,10 @@ func New(forge Forge) *Source { return &Source{forge: forge} } -// Metadata returns the pull request's title and body. Commit messages are -// left empty: no existing Forge capability returns them, and they are only -// ever one of three inputs to the hallucination-check heuristic (docs/prds/ -// pr-review-agent.md, phase 1), not load-bearing on their own. +// Metadata returns the pull request's title and body. Commit messages are left +// empty: no existing Forge capability returns them, and they are only ever one +// of three inputs to the hallucination-check heuristic, not load-bearing on +// their own. func (s *Source) Metadata(ctx context.Context, owner, repo string, number int) (workflow.PRMetadata, error) { pr, err := s.forge.GetPullRequest(ctx, owner, repo, number) if err != nil { diff --git a/internal/infrastructure/readiness/probes.go b/internal/infrastructure/readiness/probes.go index 1b281889b..0b1b0f9af 100644 --- a/internal/infrastructure/readiness/probes.go +++ b/internal/infrastructure/readiness/probes.go @@ -62,9 +62,8 @@ func (p *StoreProbe) Check(ctx context.Context) health.Result { // ContractProbe reports whether a service this process consumes over the wire // answers a cheap call within a bounded timeout. It is the readiness signal // available to a process that depends on a service it does not own: the probe -// consumes the dependency's own result and never inspects its manager, -// registry or database (docs/prds/ui-service-boundary.md, "Listen, -// authentication, and readiness"). +// consumes the dependency's own result and never inspects its manager, registry +// or database. type ContractProbe struct { ProbeName string Timeout time.Duration @@ -99,7 +98,7 @@ func (p *ContractProbe) Check(ctx context.Context) health.Result { // PolicyProblems reports the stored access policies this process's engine // could not validate. The policy chain is the source; a policy that failed // startup re-validation denies its level and must be named here with its -// error (docs/prds/orgs-and-access.md, "Storing and changing policies"). +// error. type PolicyProblems interface { Problems() []access.Problem } diff --git a/internal/infrastructure/servicediscovery/nats/doc.go b/internal/infrastructure/servicediscovery/nats/doc.go index 8b1f3ea39..b1c3ac0bb 100644 --- a/internal/infrastructure/servicediscovery/nats/doc.go +++ b/internal/infrastructure/servicediscovery/nats/doc.go @@ -1,11 +1,9 @@ // Package nats is the NATS JetStream KV transport for service discovery. // -// It implements the broker-neutral -// [servicediscovery.ServiceRegistry] contract against a JetStream KeyValue -// store, and additionally provides the registration side a service uses to -// announce itself. It is the fallback discovery mechanism for single-host, -// no-Kubernetes installs (Path B of -// docs/inspiration/service-discovery-research-2026-09-05.md); the +// It implements the broker-neutral [servicediscovery.ServiceRegistry] contract +// against a JetStream KeyValue store, and additionally provides the +// registration side a service uses to announce itself. It is the fallback +// discovery mechanism for single-host, no-Kubernetes installs; the // Kubernetes-native primary is a sibling implementation of the same contract. // // # Two buckets: presence versus liveness diff --git a/internal/infrastructure/sessioncurator/adapter.go b/internal/infrastructure/sessioncurator/adapter.go index a00c4e219..2ed60a0a9 100644 --- a/internal/infrastructure/sessioncurator/adapter.go +++ b/internal/infrastructure/sessioncurator/adapter.go @@ -1,7 +1,5 @@ -// Package sessioncurator implements domain/curator.CuratorEngine for -// session memory extraction. See docs/prds/session-memory-curator.md for -// what a pass does and why, and the scope this package deliberately does -// not cover. +// Package sessioncurator implements domain/curator.CuratorEngine for session +// memory extraction. package sessioncurator import ( @@ -15,9 +13,9 @@ import ( ) // Adapter implements curator.ConversationSource over a real -// gateway.SessionStore, narrowed to the two read-only operations a -// curator needs -- never the full session CRUD/branch/search surface a -// chat gateway exposes. See docs/prds/session-memory-curator.md. +// gateway.SessionStore, narrowed to the two read-only operations a curator +// needs -- never the full session CRUD/branch/search surface a chat gateway +// exposes. type Adapter struct { store gateway.SessionStore agentID string @@ -38,7 +36,7 @@ func NewAdapter(store gateway.SessionStore, agentID string) *Adapter { // RecentSessions returns sessions active at or after since, newest first. // AgentID is the agent every session's memory is addressed by -- the // composition's configured bot user, the same value a chat turn addresses -// its own reads with (see docs/architecture/identity.md). +// its own reads with. func (a *Adapter) RecentSessions(ctx context.Context, since time.Time) ([]curator.SessionSummary, error) { sessions, err := a.store.List(ctx) if err != nil { diff --git a/internal/infrastructure/sessioncurator/sessioncurator.go b/internal/infrastructure/sessioncurator/sessioncurator.go index 379c137b6..af2b8d35c 100644 --- a/internal/infrastructure/sessioncurator/sessioncurator.go +++ b/internal/infrastructure/sessioncurator/sessioncurator.go @@ -33,9 +33,9 @@ const ActionSkipped = "memory.skipped" const DefaultInterval = time.Hour const ( - // messageTailSize bounds how much of a session's history one pass - // reads, deliberately generous against the model's context rather - // than tuned tightly. See docs/prds/session-memory-curator.md. + // messageTailSize bounds how much of a session's history one pass reads, + // deliberately generous against the model's context rather than tuned + // tightly. messageTailSize = 40 // maxObservationsPerSession caps how many facts one pass writes for // one session -- a prompt-precision problem to fix, not a limit to @@ -46,10 +46,7 @@ const ( defaultLookback = 24 * time.Hour ) -// Curator implements domain/curator.CuratorEngine. See -// docs/prds/session-memory-curator.md for what a pass does and why: -// session-scoped extraction only, written through the bound memory -// engine, no cross-session consolidation, no forgetting. +// Curator implements domain/curator.CuratorEngine. type Curator struct { interval time.Duration engineName string @@ -94,10 +91,9 @@ func (c *Curator) Check(ctx context.Context) (bool, error) { return len(sessions) > 0, nil } -// Pass extracts durable observations from every session active since the -// last pass (or defaultLookback on the first pass) and writes them -// through the bound memory engine. See docs/prds/session-memory-curator.md -// for the exact extraction and classification rules. +// Pass extracts durable observations from every session active since the last +// pass (or defaultLookback on the first pass) and writes them through the bound +// memory engine. func (c *Curator) Pass(ctx context.Context, in curator.PassInput) (curator.PassResult, error) { engine, ok := c.host.MemoryEngines.Get(c.engineName) if !ok { diff --git a/internal/infrastructure/skillcurator/skillcurator.go b/internal/infrastructure/skillcurator/skillcurator.go index 9bca1b81c..5eaf0d8fc 100644 --- a/internal/infrastructure/skillcurator/skillcurator.go +++ b/internal/infrastructure/skillcurator/skillcurator.go @@ -30,10 +30,7 @@ const ( ActionNormalized = "skill.normalized" ) -// Curator implements domain/curator.CuratorEngine. See -// docs/prds/skill-curator.md for what a pass does and why: mechanical -// validation and safe whitespace normalization only -- no LLM-authored -// rewrites, no deletion. +// Curator implements domain/curator.CuratorEngine. type Curator struct { interval time.Duration host curator.Registrar @@ -71,11 +68,9 @@ func (c *Curator) Check(ctx context.Context) (bool, error) { return len(refs) > 0, nil } -// Pass reviews every skill currently on disk. There is no per-skill -// "already reviewed" state: each pass re-checks everything, which is -// cheap (file reads, no model calls) and errs toward catching a -// regression over missing one. See docs/prds/skill-curator.md for the -// exact classification rules. +// Pass reviews every skill currently on disk. There is no per-skill "already +// reviewed" state: each pass re-checks everything, which is cheap (file reads, +// no model calls) and errs toward catching a regression over missing one. func (c *Curator) Pass(ctx context.Context, in curator.PassInput) (curator.PassResult, error) { refs, err := c.host.Skills.List(ctx) if err != nil { @@ -107,11 +102,10 @@ func (c *Curator) reviewOne(ctx context.Context, name string) ([]curator.Action, fm, _, fail := skill.Parse([]byte(sk.Content)) if fail != nil { - // A parse failure is a per-skill finding to report, not an - // execution error to propagate: Pass()'s loop aborts the whole - // batch on a non-nil error, which would stop reviewing every - // other skill over one bad file (see skillcurator_test.go's - // "must not abort review of the others"). + // A parse failure is a per-skill finding to report, not an execution + // error to propagate: Pass()'s loop aborts the whole batch on a non-nil + // error, which would stop reviewing every other skill over one bad + // file. return invalidFinding(name, fail) } diff --git a/internal/infrastructure/skillcurator/store.go b/internal/infrastructure/skillcurator/store.go index cefccf739..e7e99d5f2 100644 --- a/internal/infrastructure/skillcurator/store.go +++ b/internal/infrastructure/skillcurator/store.go @@ -1,6 +1,5 @@ // Package skillcurator implements domain/curator.CuratorEngine for skill -// maintenance. See docs/prds/skill-curator.md for what a pass does and -// why, and the scope this package deliberately does not cover. +// maintenance. package skillcurator import ( @@ -14,7 +13,7 @@ import ( ) // skillsDir mirrors internal/skill's own unexported constant of the same -// name and value -- the discovery convention (.agents/skills/) is fixed +// name and value -- the discovery convention is fixed // across both packages, not configurable per caller. const skillsDir = ".agents/skills" @@ -22,16 +21,16 @@ const skillsDir = ".agents/skills" // its own directory under skillsDir. const skillFile = "SKILL.md" -// Store implements curator.SkillStore over one root directory's -// .agents/skills/*/SKILL.md files. List and Read never parse frontmatter -// themselves beyond a best-effort Description: a per-skill parse failure is -// the curator's problem to report as an Action, not this store's problem to -// abort on. See docs/prds/skill-curator.md. +// Store implements curator.SkillStore over one root directory's. +// agents/skills/*/SKILL.md files. List and Read never parse frontmatter +// themselves beyond a best-effort Description: a per-skill parse failure is the +// curator's problem to report as an Action, not this store's problem to abort +// on. type Store struct { root string } -// NewStore builds a Store rooted at root (root/.agents/skills/...). +// NewStore builds a Store rooted at root. func NewStore(root string) *Store { return &Store{root: root} } diff --git a/internal/infrastructure/staterpc/access.go b/internal/infrastructure/staterpc/access.go index d8c3edec8..f515e9ac6 100644 --- a/internal/infrastructure/staterpc/access.go +++ b/internal/infrastructure/staterpc/access.go @@ -1,4 +1,4 @@ -// Access: the policy-chain and denial-record RPCs (docs/prds/orgs-and-access.md). +// Access: the policy-chain and denial-record RPCs. // The policies surface is the engine's snapshot plus the administrative // writes; the denials surface is the two callers' write path and the // operator's read. diff --git a/internal/infrastructure/staterpc/access_client.go b/internal/infrastructure/staterpc/access_client.go index a6fa18d43..3293bc7dd 100644 --- a/internal/infrastructure/staterpc/access_client.go +++ b/internal/infrastructure/staterpc/access_client.go @@ -1,5 +1,5 @@ -// Access: the client half of the policy-chain and denial-record RPCs -// (docs/prds/orgs-and-access.md). The reset surface is deliberately absent: +// Access: the client half of the policy-chain and denial-record RPCs. +// The reset surface is deliberately absent: // `archied access reset` runs on the State Store host, never over the wire. package staterpc diff --git a/internal/infrastructure/staterpc/auth.go b/internal/infrastructure/staterpc/auth.go index 041b404e0..31b654993 100644 --- a/internal/infrastructure/staterpc/auth.go +++ b/internal/infrastructure/staterpc/auth.go @@ -8,13 +8,12 @@ import ( ) // tokenMetadataKey is the gRPC metadata key the bearer token travels in. -// Metadata, never a URL, per docs/prds/state-store-contract.md §9's token -// lifecycle note. +// Metadata, never a URL. const tokenMetadataKey = "state-store-token" // UnaryClientTokenInterceptor attaches token to every outgoing call's // metadata under tokenMetadataKey. One token covers a task's container -// lifetime (§9's per-incumbence lifecycle) so it does not need to be +// lifetime so it does not need to be // refreshed mid-connection. Used by the agent's long-lived client // connection to the State Store's bridge-address listener. func UnaryClientTokenInterceptor(token string) grpc.UnaryClientInterceptor { diff --git a/internal/infrastructure/staterpc/client.go b/internal/infrastructure/staterpc/client.go index 24bde5a9a..4a6ddb3b9 100644 --- a/internal/infrastructure/staterpc/client.go +++ b/internal/infrastructure/staterpc/client.go @@ -25,14 +25,14 @@ import ( // Client is the single remote adapter wrapping one StateStoreServiceClient, // asserted against whichever narrow Go interfaces its caller needs -- exactly // as gatewayrpc.Client asserts both messaging.ChatContract and -// messaging.SessionStore. See docs/prds/state-store-contract.md §2. +// messaging.SessionStore. type Client struct { client pb.StateStoreServiceClient controlPlane controlpb.ControlPlaneServiceClient } // NewClient wraps conn's generated client. Close is a no-op: the store -// service owns its own DB lifecycle (§11). +// service owns its own DB lifecycle. func NewClient(conn grpc.ClientConnInterface) *Client { return &Client{client: pb.NewStateStoreServiceClient(conn), controlPlane: controlpb.NewControlPlaneServiceClient(conn)} } @@ -115,7 +115,7 @@ func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail } // StartStep and FinishStep record the run's step executions -// (docs/prds/execution-tree-state-machine.md) under the run credential, which +// under the run credential, which // the State Store's grant interceptor scopes to the execution the requests // name. Each returns the transition's persisted event for the caller's // post-commit publish. @@ -135,7 +135,7 @@ func (c *Client) StartStep(ctx context.Context, s task.StepStart) (int64, events return r.StepId, event, nil } -// CancelExecution is the one cancel path (docs/prds/execution-tree-state-machine.md): +// CancelExecution is the one cancel path: // the State Store records the cancellation -- every non-terminal step of the // current attempt plus the execution's own move -- and returns the steps it // cancelled; the caller cancels the run's in-memory context afterwards. @@ -641,11 +641,10 @@ func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, bod return taskValue(r.Task), nil } -// WorkflowCaller: the workflow.call step's two RPCs (docs/prds/ -// workflow-calls.md). StartCall encodes the call's inputs in the same form -// every other wire crossing uses; CallStatus rehydrates the sentinels the -// server maps, so a caller's errors.Is(err, storecontract.ErrCallNotYours) -// works across the wire. +// WorkflowCaller: the workflow.call step's two RPCs. StartCall encodes the +// call's inputs in the same form every other wire crossing uses; CallStatus +// rehydrates the sentinels the server maps, so a caller's errors.Is(err, +// storecontract.ErrCallNotYours) works across the wire. func (c *Client) StartCall(ctx context.Context, callerTaskID int64, wf string, inputs map[string]any) (*task.Task, error) { encoded, err := task.EncodeInputs(inputs) diff --git a/internal/infrastructure/staterpc/dial.go b/internal/infrastructure/staterpc/dial.go index ff5b96266..d5eac0c34 100644 --- a/internal/infrastructure/staterpc/dial.go +++ b/internal/infrastructure/staterpc/dial.go @@ -12,11 +12,11 @@ import ( ) // Dial returns a State Store contract client for target, applying the -// transport security boundary (docs/prds/state-store-contract.md §9): a +// transport security boundary: a // loopback target dials insecure with no credential, while a non-loopback // target requires a bearer token and fails closed without one. The returned // cleanup closes the connection; Client.Close is a no-op because the store -// service owns its own DB lifecycle (§11). +// service owns its own DB lifecycle. // // The rule lives here rather than in a composition root so the server side // (which decides whether to install the token interceptors) and every client diff --git a/internal/infrastructure/staterpc/server.go b/internal/infrastructure/staterpc/server.go index a0c7c5db9..6548e2881 100644 --- a/internal/infrastructure/staterpc/server.go +++ b/internal/infrastructure/staterpc/server.go @@ -1,7 +1,6 @@ -// Package staterpc adapts the State Store contract (internal/domain/storecontract's -// producer-owned surfaces plus the consumer-owned workflow.Store) to gRPC. -// See docs/prds/state-store-contract.md for the ratified contract this -// package implements against. +// Package staterpc adapts the State Store contract +// (internal/domain/storecontract's producer-owned surfaces plus the +// consumer-owned workflow.Store) to gRPC. package staterpc import ( @@ -30,9 +29,8 @@ import ( ) // Unavailable-capability errors, mirroring gatewayrpc's missing-session-store -// pattern (docs/prds/state-store-contract.md §7's "capability absent -> -// Unavailable" row): a nil optional Deps field maps to codes.Unavailable -// rather than a nil-pointer panic. +// pattern: a nil optional Deps field maps to codes.Unavailable rather than a +// nil-pointer panic. var ( errCaptureUnavailable = status.Error(codes.Unavailable, "capture store unavailable") errConfigSnapshotsUnavailable = status.Error(codes.Unavailable, "config snapshot store unavailable") @@ -92,38 +90,38 @@ type Deps struct { Sources storecontract.SourceStore BindingDispatcher storecontract.BindingDispatcher BindingTaskCreator storecontract.BindingTaskCreator - // WorkflowCalls is the workflow.call surface (docs/prds/workflow-calls.md): + // WorkflowCalls is the workflow.call surface: // the workflow engine's task.Caller over this contract. Optional: nil // answers both RPCs with codes.Unavailable, which is the honest answer // for a store that owns no task table. WorkflowCalls storecontract.WorkflowCaller - // Steps is the step-execution write surface - // (docs/prds/execution-tree-state-machine.md): the guarded row writes the + // Steps is the step-execution write surface: + // the guarded row writes the // workflow engine's run credential calls. Optional: nil answers both RPCs // with codes.Unavailable. Steps storecontract.StepRecorder - // Canceller is the one cancel path (docs/prds/execution-tree-state-machine.md): + // Canceller is the one cancel path: // an operator action's guarded write over the execution and its steps. // Optional: nil answers the RPC with codes.Unavailable. Canceller storecontract.ExecutionCanceller - // StepReader lists an execution's recorded steps for the dashboard/API - // (docs/prds/execution-tree-state-machine.md): a plain read, never + // StepReader lists an execution's recorded steps for the dashboard/API: + // a plain read, never // task-scoped-grant callable. Optional: nil answers ListSteps with // codes.Unavailable. StepReader storecontract.StepReader - // HarnessSecrets persists harness OAuth token sets - // (docs/prds/external-agent-harness.md, Credentials). Optional: nil + // HarnessSecrets persists harness OAuth token sets. + // Optional: nil // answers both RPCs with codes.Unavailable. HarnessSecrets storecontract.HarnessSecretStore - // PlaybookDispatcher is the side-effecting-action idempotency ledger - // (docs/prds/eda-playbook-engine.md gap 2). Optional: nil disables the + // PlaybookDispatcher is the side-effecting-action idempotency ledger. + // Optional: nil disables the // two playbook dispatch RPCs with codes.Unavailable. PlaybookDispatcher storecontract.PlaybookDispatcher // Principals assembles the access principal for one identity: the org it // serves and its memberships. Optional: nil answers GetPrincipal with // codes.Unavailable. Principals access.PrincipalSource - // Policies is the stored policy chain (docs/prds/orgs-and-access.md). + // Policies is the stored policy chain. // Optional: nil answers the access RPCs with codes.Unavailable. The reset // surface is deliberately not an RPC: `archied access reset` runs on the // State Store host, never over the network. @@ -148,8 +146,8 @@ type server struct { // RegisterServer registers the StateStore gRPC service against registrar, // backed by deps. Optionally wrap registrar's interceptor chain with -// TokenInterceptor for the bridge-address (agent-consumed) topology; the -// caller decides, per docs/prds/state-store-contract.md §9's listener rule. +// TokenInterceptor for the bridge-address (agent-consumed) topology; the caller +// decides. func RegisterServer(registrar grpc.ServiceRegistrar, deps Deps) { if deps.Log == nil { deps.Log = slog.New(slog.DiscardHandler) @@ -223,8 +221,8 @@ func (s *server) Transition(ctx context.Context, r *pb.TransitionRequest) (*pb.T return &pb.TransitionResponse{}, nil } -// StartStep and FinishStep are the step-execution writes -// (docs/prds/execution-tree-state-machine.md). Each is the store's own +// StartStep and FinishStep are the step-execution writes. +// Each is the store's own // transaction -- guarded row write plus the event row -- and the store's // response carries the persisted event back for the caller's post-commit // publish. @@ -243,7 +241,7 @@ func (s *server) StartStep(ctx context.Context, r *pb.StartStepRequest) (*pb.Sta return &pb.StartStepResponse{StepId: stepID, Event: eventProto(event)}, nil } -// CancelExecution is the one cancel path (docs/prds/execution-tree-state-machine.md): +// CancelExecution is the one cancel path: // the store records the cancellation and returns the steps it cancelled; the // caller delivers it by cancelling the run's in-memory context afterwards. func (s *server) CancelExecution(ctx context.Context, r *pb.CancelExecutionRequest) (*pb.CancelExecutionResponse, error) { @@ -621,7 +619,6 @@ func (s *server) InsertCapture(ctx context.Context, r *pb.InsertCaptureRequest) // StreamCaptures streams one capture per message: a batch of large capture // bodies in one unary response can exceed gRPC's 4MiB message cap -// (docs/prds/state-store-contract.md). func (s *server) StreamCaptures(r *pb.StreamCapturesRequest, stream pb.StateStoreService_StreamCapturesServer) error { cs, err := s.capture() if err != nil { @@ -959,7 +956,7 @@ func (s *server) EnqueueBindingTask(ctx context.Context, r *pb.EnqueueBindingTas } // WorkflowCaller: a workflow.call step starts its callee and reads it back -// while waiting (docs/prds/workflow-calls.md). The grant already named the +// while waiting. The grant already named the // caller; the store's own row checks are what make both calls answer only // for this caller's own callees. diff --git a/internal/infrastructure/staterpc/task_grants.go b/internal/infrastructure/staterpc/task_grants.go index 2fe7c4f18..a3d0aceb5 100644 --- a/internal/infrastructure/staterpc/task_grants.go +++ b/internal/infrastructure/staterpc/task_grants.go @@ -90,19 +90,11 @@ func (g *TaskGrants) taskFor(token string) int64 { return 0 } -// authorizesTaskScopedCall reports whether req -- a call to one of the RPCs -// a task grant may ever authorize -- targets taskID. Every other RPC -// (including RegisterTaskGrant/RevokeTaskGrant themselves) falls through to -// false: a task grant can only ever narrow, never expand. -// -// The two workflow.call RPCs and the two step-execution writes are the -// sanctioned widenings: a workflow.call step must start its callee and read it -// back, the callee being the caller's child (docs/prds/workflow-calls.md), and -// the container records its stages and its own agent calls under the run -// credential of docs/prds/execution-tree-state-machine.md. The step requests -// carry the caller's own task ID, which the grant check verifies; the step's -// membership in that execution is a handler-side row check, so this -// interceptor never reads the database. +// authorizesTaskScopedCall reports whether a task-scoped token may make this +// call: only when the RPC is in taskScopedTargets and targets taskID. Every +// other RPC, including grant registration, is refused, so a task grant only +// narrows. workflow.call and step-execution writes carry the caller's own task +// ID; the handler checks step membership, so this never reads the database. func authorizesTaskScopedCall(fullMethod string, req any, taskID int64) bool { target := taskScopedTargets[fullMethod] return target != nil && target(req) == taskID diff --git a/internal/infrastructure/staterpc/values.go b/internal/infrastructure/staterpc/values.go index 76fa00d54..0425d80c8 100644 --- a/internal/infrastructure/staterpc/values.go +++ b/internal/infrastructure/staterpc/values.go @@ -393,7 +393,7 @@ func dayTokensValue(d *pb.DayTokens) storecontract.DayTokens { return storecontract.DayTokens{Day: d.Day, Tokens: int(d.Tokens)} } -// Canonical public phrases for sentinel errors (rev. 2c §7). These strings +// Canonical public phrases for sentinel errors. These strings // are the wire contract for sentinel identity -- the client rehydrates by // matching (code, message), never by parsing free-form text. const ( @@ -431,13 +431,13 @@ const ( // codes.Internal with a sanitised message; the caller is expected to log the // full error server-side before calling mapError. // -// A context cancellation/deadline raised by the store (or by a caller ctx that -// expires mid-call, §6) must retain its identity, not be folded into -// codes.Internal: gRPC-Go surfaces context.Canceled/DeadlineExceeded to the -// client only for those exact codes, and the agent's workflow consumer -// depends on errors.Is(err, context.DeadlineExceeded) to distinguish an -// interrupted stage from a failed one. So a context error maps to its own -// gRPC code (and unmapError rehydrates it back to the sentinel). +// A context cancellation/deadline raised by the store must retain its identity, +// not be folded into codes.Internal: gRPC-Go surfaces +// context.Canceled/DeadlineExceeded to the client only for those exact codes, +// and the agent's workflow consumer depends on errors.Is(err, +// context.DeadlineExceeded) to distinguish an interrupted stage from a failed +// one. So a context error maps to its own gRPC code (and unmapError rehydrates +// it back to the sentinel). func mapError(err error) error { if err == nil { return nil @@ -461,7 +461,7 @@ func mapError(err error) error { // the wire. A non-status error (e.g. a transport failure) is returned // unchanged. // -// The deadline/cancel identity must survive too (§6): the agent's +// The deadline/cancel identity must survive too: the agent's // deadlineStore bounds each Store call with context.WithTimeout, and the // workflow consumer checks errors.Is(err, context.DeadlineExceeded) to // decide whether a stage was interrupted by shutdown rather than failed @@ -497,7 +497,7 @@ func unmapError(err error) error { // sentinelForStatus maps a status to the store or logging sentinel it stands // for, matched on (code, exact canonical message) -- those message constants -// are part of the wire contract (§4). A code whose message is not one this +// are part of the wire contract. A code whose message is not one this // package defines returns nil, so the caller falls back to the wrapped form. func sentinelForStatus(st *status.Status) error { return wireSentinels[wireStatus{st.Code(), st.Message()}] diff --git a/internal/infrastructure/taskactions/store.go b/internal/infrastructure/taskactions/store.go index dfe47282f..707b4f7d8 100644 --- a/internal/infrastructure/taskactions/store.go +++ b/internal/infrastructure/taskactions/store.go @@ -20,8 +20,8 @@ func (s Store) TaskByID(ctx context.Context, id int64) (*taskactions.Task, error return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, RetryCount: t.RetryCount, Attempt: t.Attempt, Branch: t.Branch, RetryMode: t.RetryMode, ForgeBacked: t.IsForgeBacked(), ReviewGate: t.ReviewGate, RereviewRounds: t.RereviewRounds}, nil } -// CancelExecution delegates to the store's one cancel path -// (docs/prds/execution-tree-state-machine.md). Both adapters -- the +// CancelExecution delegates to the store's one cancel path. +// Both adapters -- the // PostgreSQL store and the remote gRPC client -- implement it; the type // assertion failing would be a composition bug, so it is named rather than // panicked over. diff --git a/internal/infrastructure/workflowsteps/workflowsteps.go b/internal/infrastructure/workflowsteps/workflowsteps.go index 0f3e6512a..cda181bf5 100644 --- a/internal/infrastructure/workflowsteps/workflowsteps.go +++ b/internal/infrastructure/workflowsteps/workflowsteps.go @@ -67,19 +67,9 @@ func (eventSteps) StepTypes() []workflow.StepType { return []workflow.StepType{workflow.AgentRunStepType(), workflow.WorkflowCallStepType()} } -// commandSteps is the provider for the command.run step type: the single step -// type the maintainer's command-step trust decision allows -// (archie-core-ndm8), and the migration target that the refusal of -// .archie/stages/*.go now names. -// -// It is a contributor of exactly one step type, which is the shape -// docs/prds/workflow-step-vocabulary.md prescribes for this case -- "a new -// contributor of exactly one step type at a named provider" -- and it is a -// provider of its own rather than part of repoHooks because a command step is -// not a repository hook: repoHooks carries the replacement for .archie/gate.go, -// whose rules the *repository* authored, while this carries the replacement for -// .archie/stages/*.go, whose commands the *operator* authors in the stored -// definition. +// commandSteps provides the command.run step type: operator-authored commands +// from the stored workflow definition. It is separate from repoHooks, which +// carries repository-authored gate rules. type commandSteps struct{} func (commandSteps) Name() string { return "command" } diff --git a/internal/pairing/store.go b/internal/pairing/store.go index a73bfe9cf..fb084f246 100644 --- a/internal/pairing/store.go +++ b/internal/pairing/store.go @@ -10,10 +10,7 @@ import ( "time" ) -// Tuning constants. See package doc and the design note on -// archie-core-abg.22.3 for why SHA-256 (a fast hash, not a slow KDF) is -// an acceptable choice for HashCode: these values are the actual -// security boundary for a leaked pending code, not the hash function. +// Tuning constants. const ( // CodeTTL is how long a requested pairing code remains valid. CodeTTL = time.Hour diff --git a/internal/plugin/host.go b/internal/plugin/host.go index ab93a34d6..4875f7897 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -496,7 +496,7 @@ func reverseClone(values []string) []string { } // Add registers and starts a module on a host that is already running, the -// running-state half of a live plugin load (docs/prds/plugin-settings-live.md). +// running-state half of a live plugin load. // The module starts on its own -- every module registered before it is already // running -- and a failed start removes it again without disturbing them. On a // host that has not started, Add behaves like Register and the module starts diff --git a/internal/plugin/plugin.go b/internal/plugin/plugin.go index 2e496e940..8ce9999d4 100644 --- a/internal/plugin/plugin.go +++ b/internal/plugin/plugin.go @@ -1,7 +1,7 @@ // Package plugin defines the core plugin interface for extending archie-core's -// daemon at startup. Plugins are Yaegi-interpreted .go files loaded from +// daemon at startup. Plugins are Yaegi-interpreted.go files loaded from // ~/.config/archie/plugins/ that register themselves with the daemon's -// extension registry. PRD section 5 Layer 2. +// extension registry. package plugin import ( @@ -31,7 +31,7 @@ type Plugin interface { // LoadDir discovers and evaluates .go files in the given directory. // Each file must export a variable named "Plugin" that implements the // Plugin interface. Failed plugins are logged and skipped -- the daemon -// starts with the remaining plugins (PRD section 5). +// starts with the remaining plugins. // // extraSymbols are additional Yaegi symbol tables made available to // interpreted code. Callers should pass pluginextract.Symbols so that diff --git a/internal/releaseupdate/command.go b/internal/releaseupdate/command.go index b1f6438ad..a0ccd603c 100644 --- a/internal/releaseupdate/command.go +++ b/internal/releaseupdate/command.go @@ -39,7 +39,7 @@ func (c CommandCatalog) Check(ctx context.Context) (Snapshot, error) { // CommandInstaller runs the deployment's own install command. HealthURL is // the base URL its restart tooling must poll for /healthz -- only this // process knows which address it actually serves, so a script left to guess -// one rolls back releases that came up healthy (archie-core-1r4g). Empty +// one rolls back releases that came up healthy. Empty // leaves ARCHIE_HEALTH_URL as the environment already has it. type CommandInstaller struct { Command []string diff --git a/internal/sdnotify/sdnotify.go b/internal/sdnotify/sdnotify.go index 536d42eac..a8d438894 100644 --- a/internal/sdnotify/sdnotify.go +++ b/internal/sdnotify/sdnotify.go @@ -9,12 +9,10 @@ // WatchdogSec) sends nothing and serves exactly as before, and a socket that // cannot be written to is logged and ignored. // -// It is cross-cutting per docs/architecture/organisation.md: any layer and any -// binary may import it, and it imports nothing of ours. It lives outside a -// composition package because a process that must announce itself cannot -// import another process's composition -- archied and archie-messaging are two -// processes that announce, and only one of them can own archied's boot -// (archie-core-g5g8). +// It lives outside a composition package because a process that must announce +// itself cannot import another process's composition -- archied and +// archie-messaging are two processes that announce, and only one of them can +// own archied's boot // // What stays with the caller is everything that is the caller's: which marker // counts as progress, how long its loop may go without a pass, and the point @@ -116,7 +114,7 @@ func sendNotify(addr, state string) error { // (next to its own health surface), and the serve steps of archie-gateway, // archie-state-store and archie-messaging, which have readiness of their own // and would otherwise hang a Type=notify unit until TimeoutStartSec while -// perfectly healthy (archie-core-1174, archie-core-g5g8). +// perfectly healthy. func Ready(log *slog.Logger) { New(os.Getenv, log).Send(ReadyState) } diff --git a/internal/secret/secret.go b/internal/secret/secret.go index 2123c4aba..d116e0766 100644 --- a/internal/secret/secret.go +++ b/internal/secret/secret.go @@ -2,7 +2,7 @@ package secret import "github.com/samcharles93/archie-core/internal/config" -// SecretRef moved to internal/config (archie-core-8cda.5.6): the type is +// SecretRef moved to internal/config: the type is // config vocabulary, and config cannot import this package (the UI process // renders config projections but never resolves a secret). type SecretRef = config.SecretRef diff --git a/internal/servicediscovery/doc.go b/internal/servicediscovery/doc.go index b6d3f05ee..e347d1bc6 100644 --- a/internal/servicediscovery/doc.go +++ b/internal/servicediscovery/doc.go @@ -2,16 +2,10 @@ // // It defines only the shape archie-core needs to discover and watch the // services of its decomposed fleet: a way to resolve a named service to its -// live endpoints, and a way to watch that membership change over time. It -// names no registry. A NATS JetStream KV implementation lives in -// internal/infrastructure/servicediscovery/nats; the Kubernetes-native -// primary (Service/EndpointSlice + CoreDNS, per -// docs/inspiration/service-discovery-research-2026-09-05.md) is the sibling -// that serves the same contract. -// -// Per docs/architecture/dependencies-and-contracts.md, consumers depend on -// this package and never on an infrastructure implementation; only -// application composition chooses a concrete registry. +// live endpoints, and a way to watch that membership change over time. It names +// no registry. A NATS JetStream KV implementation lives in +// internal/infrastructure/servicediscovery/nats; the Kubernetes-native primary +// is the sibling that serves the same contract. // // # NotInstalled is not Down // diff --git a/internal/skill/plugin.go b/internal/skill/plugin.go index 55e069164..9d4312f23 100644 --- a/internal/skill/plugin.go +++ b/internal/skill/plugin.go @@ -37,7 +37,7 @@ func (p *Plugin) Run(input string) (string, error) { return fn(input), nil } -// LoadPlugins loads plugins from dir/.agents/skills//plugins/. +// LoadPlugins loads plugins. // // When allowed is non-empty, only the listed filenames are loaded in // declared order -- the plugins/ prefix is stripped before matching. diff --git a/internal/skill/skill.go b/internal/skill/skill.go index e80af043b..19f713a0e 100644 --- a/internal/skill/skill.go +++ b/internal/skill/skill.go @@ -1,5 +1,5 @@ -// Package skill parses agentskills.io SKILL.md files and discovers skills -// from the .agents/skills/ directory convention. It follows the same discovery +// Package skill parses agentskills.io SKILL.md files and discovers skills. +// It follows the same discovery // pattern as internal/workflow/wfeval (missing directory is not an error). package skill @@ -37,13 +37,12 @@ type CatalogEntry struct { Description string Workflow string // from metadata.archie.workflow -- which workflow this skill handles Dir string // skill directory name - Root string // catalog root containing .agents/skills + Root string // catalog root containing.agents/skills } -// Catalog scans dir/.agents/skills/*/SKILL.md and returns catalog entries -// (Tier 1: name + description + workflow only). Only the frontmatter is -// parsed -- full bodies are not loaded. Missing directory or a file at the -// skills path returns nil (no error) -- the caller treats this as "no skills." +// Only the frontmatter is parsed -- full bodies are not loaded. Missing +// directory or a file at the skills path returns nil (no error) -- the caller +// treats this as "no skills." func Catalog(dir string) ([]CatalogEntry, error) { skillsPath := filepath.Join(dir, skillsDir) entries, err := os.ReadDir(skillsPath) @@ -51,7 +50,6 @@ func Catalog(dir string) ([]CatalogEntry, error) { return nil, nil } if err != nil { - // A file at .agents/skills (ENOTDIR) is not fatal -- treat as no skills. // Same for permission errors and other non-fatal ReadDir failures. return nil, nil //nolint:nilerr // documented above: a non-directory or unreadable skills path means no skills, not a fatal error } diff --git a/internal/skillscript/yaegi.go b/internal/skillscript/yaegi.go index c60cfa12c..79041e48a 100644 --- a/internal/skillscript/yaegi.go +++ b/internal/skillscript/yaegi.go @@ -1,4 +1,4 @@ -// Package skillscript runs skill-bundled Go scripts (.agents/skills//scripts/*.go) +// Package skillscript runs skill-bundled Go scripts // via Yaegi. Unlike the gate and workflow-stage extension surfaces, these // scripts only need the Go standard library -- they wrap external tools // (gitleaks, trivy, ...) the way a shell script would -- so no diff --git a/internal/taskstate/taskstate.go b/internal/taskstate/taskstate.go index 36656b830..1c924214f 100644 --- a/internal/taskstate/taskstate.go +++ b/internal/taskstate/taskstate.go @@ -286,10 +286,9 @@ func ActionCatalog() []ActionMeta { } // Park classes: the producer-side answer to "what kind of intervention does -// this park need?" (docs/prds/pr-review-remediation.md's F2, the typed -// classification agent-system.md:327 acknowledges the data model lacks). -// The class is recorded at the park site, where the cause is known, and is -// never inferred later from reason text. It is part of the on-disk format. +// this park need?". The class is recorded at the park site, where the cause is +// known, and is never inferred later from reason text. It is part of the +// on-disk format. const ( // ParkNeedsHuman parks need an operator decision: gate failures, // review verdicts, diff caps, remediation round caps. It is the diff --git a/internal/taskstate/taskstatetest/taskstatetest.go b/internal/taskstate/taskstatetest/taskstatetest.go deleted file mode 100644 index 68943bb5e..000000000 --- a/internal/taskstate/taskstatetest/taskstatetest.go +++ /dev/null @@ -1,105 +0,0 @@ -// Package taskstatetest seeds task lifecycle states for tests. -// -// A fixture that needs a task in a finished state used to write the pair it -// wanted -- queued -> merged, queued -> parked -- because the store accepted -// it. The transition tables (internal/taskstate) refuse most of those pairs, -// so a fixture that keeps writing one fails the moment the store enforces -// them. Seeding through this package moves the task along the table's legal -// edges instead, and fails loudly when no legal route exists. -package taskstatetest - -import ( - "context" - "fmt" - "slices" - "testing" - - "github.com/samcharles93/archie-core/internal/taskstate" -) - -// Transitioner is the guarded status write the seeder needs: the store's own -// Transition, which refuses a from that is not the task's current status. -type Transitioner interface { - Transition(ctx context.Context, taskID int64, from, to, detail string) error -} - -// Seed moves taskID from the status it holds to want, one legal edge at a -// time, recording detail on every edge. It fails the test on the edge that the -// store refuses, or before any edge when the table has no route at all. -// -// ctx is the caller's, so a fixture that seeds with a context of its own -// chooses it rather than inheriting one the helper invented. -func Seed(ctx context.Context, t testing.TB, st Transitioner, taskID int64, from, want, detail string) { - t.Helper() - route, err := Path(from, want) - if err != nil { - t.Fatalf("seed task %d: %v", taskID, err) - } - at := from - for _, to := range route { - if err := st.Transition(ctx, taskID, at, to, detail); err != nil { - t.Fatalf("seed task %d to %s: %s -> %s: %v", taskID, want, at, to, err) - } - at = to - } -} - -// Path returns the statuses a task moves through to get from one status to -// another, as the shortest route through the execution transition table. A nil -// route means from is already want. -// -// It is exported for the fixtures that seed from a goroutine, where t.Fatalf is -// not callable: those compute the route on the test goroutine and apply it in -// the callback. -func Path(from, want string) ([]string, error) { - statuses := statusIDs() - if !slices.Contains(statuses, from) { - return nil, fmt.Errorf("%q is not a task status", from) - } - if !slices.Contains(statuses, want) { - return nil, fmt.Errorf("%q is not a task status", want) - } - if from == want { - return nil, nil - } - - // Breadth-first, walking each row's edges in catalog order, so the route a - // fixture takes is the shortest one and the same on every run. - arrivedFrom := map[string]string{from: from} - queue := []string{from} - for len(queue) > 0 { - at := queue[0] - queue = queue[1:] - for _, next := range statuses { - if _, seen := arrivedFrom[next]; seen || !taskstate.CanTransition(at, next) { - continue - } - arrivedFrom[next] = at - if next == want { - return route(arrivedFrom, from, want), nil - } - queue = append(queue, next) - } - } - return nil, fmt.Errorf("no legal route from %s to %s", from, want) -} - -// route reconstructs the way to want, ending with it and leaving out the -// status the task was already in. -func route(arrivedFrom map[string]string, from, want string) []string { - var reverse []string - for at := want; at != from; at = arrivedFrom[at] { - reverse = append(reverse, at) - } - slices.Reverse(reverse) - return reverse -} - -func statusIDs() []string { - catalog := taskstate.Statuses() - ids := make([]string, 0, len(catalog)) - for _, meta := range catalog { - ids = append(ids, meta.ID) - } - return ids -} diff --git a/internal/taskstate/transitions.go b/internal/taskstate/transitions.go index 5f72d3353..f936a72df 100644 --- a/internal/taskstate/transitions.go +++ b/internal/taskstate/transitions.go @@ -7,8 +7,8 @@ import ( ) // StepStatus is the lifecycle of a StepExecution -- one stage run, or one agent -// call a stage makes, inside a WorkflowExecution -// (docs/prds/execution-tree-state-machine.md). It is part of the on-disk +// call a stage makes, inside a WorkflowExecution. +// It is part of the on-disk // format, like the execution statuses above. // // It is a distinct type from those statuses even though the two vocabularies diff --git a/internal/tools/builtin/bridge.go b/internal/tools/builtin/bridge.go index c8f5bb1e6..347f5927c 100644 --- a/internal/tools/builtin/bridge.go +++ b/internal/tools/builtin/bridge.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/bridge.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/builtin.go b/internal/tools/builtin/builtin.go index 205e4835c..303077b5d 100644 --- a/internal/tools/builtin/builtin.go +++ b/internal/tools/builtin/builtin.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/builtin.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/edit.go b/internal/tools/builtin/edit.go index f75884a03..81c890b96 100644 --- a/internal/tools/builtin/edit.go +++ b/internal/tools/builtin/edit.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/edit.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/find.go b/internal/tools/builtin/find.go index 5211cdaaa..2c96cfdbf 100644 --- a/internal/tools/builtin/find.go +++ b/internal/tools/builtin/find.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/find.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/fsutil.go b/internal/tools/builtin/fsutil.go index 2e63d8412..df7bdd56a 100644 --- a/internal/tools/builtin/fsutil.go +++ b/internal/tools/builtin/fsutil.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/fsutil.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/grep.go b/internal/tools/builtin/grep.go index df78a29e3..aa449ea73 100644 --- a/internal/tools/builtin/grep.go +++ b/internal/tools/builtin/grep.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/grep.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/mutation.go b/internal/tools/builtin/mutation.go index bb121c154..d401b6320 100644 --- a/internal/tools/builtin/mutation.go +++ b/internal/tools/builtin/mutation.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/mutation.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/pathutil.go b/internal/tools/builtin/pathutil.go index 2e7560ee5..f3ecf9a22 100644 --- a/internal/tools/builtin/pathutil.go +++ b/internal/tools/builtin/pathutil.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/pathutil.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/procgroup_unix.go b/internal/tools/builtin/procgroup_unix.go index bbc45ea36..f51da6f1d 100644 --- a/internal/tools/builtin/procgroup_unix.go +++ b/internal/tools/builtin/procgroup_unix.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/procgroup_unix.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/procgroup_windows.go b/internal/tools/builtin/procgroup_windows.go index 7b79f0e36..6a83c80b6 100644 --- a/internal/tools/builtin/procgroup_windows.go +++ b/internal/tools/builtin/procgroup_windows.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/procgroup_windows.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/read.go b/internal/tools/builtin/read.go index 95ef8f6a6..064b42c32 100644 --- a/internal/tools/builtin/read.go +++ b/internal/tools/builtin/read.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/read.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/read_outline.go b/internal/tools/builtin/read_outline.go index fccb0d623..93d67aecc 100644 --- a/internal/tools/builtin/read_outline.go +++ b/internal/tools/builtin/read_outline.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/read_outline.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/read_tracker.go b/internal/tools/builtin/read_tracker.go index b6053b2e0..245e2106b 100644 --- a/internal/tools/builtin/read_tracker.go +++ b/internal/tools/builtin/read_tracker.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/read_tracker.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/registry.go b/internal/tools/builtin/registry.go index 6900ff9f7..c860c67c7 100644 --- a/internal/tools/builtin/registry.go +++ b/internal/tools/builtin/registry.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/registry.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/shell.go b/internal/tools/builtin/shell.go index abf601590..d53a740e8 100644 --- a/internal/tools/builtin/shell.go +++ b/internal/tools/builtin/shell.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/shell.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/truncate.go b/internal/tools/builtin/truncate.go index ee2cec255..d69f1b66b 100644 --- a/internal/tools/builtin/truncate.go +++ b/internal/tools/builtin/truncate.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/truncate.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/builtin/write.go b/internal/tools/builtin/write.go index ec7a0f711..0bd7c76a4 100644 --- a/internal/tools/builtin/write.go +++ b/internal/tools/builtin/write.go @@ -1,5 +1,5 @@ // Lifted from tau internal/agent/tools/write.go -// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27). +// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d. // // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an diff --git a/internal/tools/command/parse.go b/internal/tools/command/parse.go index 16b885d01..8232b7abc 100644 --- a/internal/tools/command/parse.go +++ b/internal/tools/command/parse.go @@ -7,7 +7,7 @@ // knowing where a command actually begins, which means parsing quoting and // separators rather than pattern-matching the raw text. // -// Tool execution owns command constraints (see docs/architecture/policy.md). +// Tool execution owns command constraints. // When internal/policy's evaluation API lands, [Hardline] becomes an // evaluator registered there; the rules themselves stay here. package command diff --git a/internal/webhookguard/doc.go b/internal/webhookguard/doc.go index 466cba805..3e5de0b11 100644 --- a/internal/webhookguard/doc.go +++ b/internal/webhookguard/doc.go @@ -2,11 +2,7 @@ // inbound webhook-shaped HTTP requests before anything trusts them: // signature verification, per-source rate limiting, and payload redaction. // -// It is cross-cutting per docs/architecture/organisation.md: importable by -// any layer, and it imports none of domain, infrastructure, or app. It owns -// none of a caller's vocabulary -- not what a "source" is, not how a +// It owns none of a caller's vocabulary -- not what a "source" is, not how a // captured event is stored, not what a binding's approval state means. Those -// stay with the packages that own that state (see -// docs/prds/event-sources-and-reactions.md for why a generic Source -// interface was rejected). +// stay with the packages that own that state. package webhookguard diff --git a/internal/webhookguard/ratelimit.go b/internal/webhookguard/ratelimit.go index aaf6f50a4..80cdbcaf5 100644 --- a/internal/webhookguard/ratelimit.go +++ b/internal/webhookguard/ratelimit.go @@ -5,16 +5,13 @@ import ( "time" ) -// RateLimiter caps request volume per source using a token bucket per -// source ID. Source IDs are assumed to come from a registered, operator- -// controlled set (per docs/prds/webhook-intake-security.md's "a source -// registers with a secret before its events can trigger anything"), not -// from unbounded attacker-supplied request data -- the bucket map is not -// itself bounded, because the key space is bounded by registration. +// RateLimiter caps request volume per source using a token bucket per source +// ID. Source IDs are assumed to come from a registered, operator- controlled +// set, not from unbounded attacker-supplied request data -- the bucket map is +// not itself bounded, because the key space is bounded by registration. // -// A rejected request must be surfaced as an observable rejection by the -// caller (HTTP 429), never silently dropped -- see -// docs/prds/webhook-intake-security.md point 3. +// A rejected request must be surfaced as an observable rejection by the caller +// (HTTP 429), never silently dropped. type RateLimiter struct { mu sync.Mutex rate float64 // tokens added per second diff --git a/internal/webhookguard/redact.go b/internal/webhookguard/redact.go index 4146f111e..a15b6efc5 100644 --- a/internal/webhookguard/redact.go +++ b/internal/webhookguard/redact.go @@ -36,14 +36,12 @@ var jwtTokenRe = regexp.MustCompile(`^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z // inbound webhook body before persisting it. // // This intentionally does NOT reuse internal/gateway/stream.go's -// SummarizeToolParameters shape unchanged: that function replaces every -// string value regardless of key, which produces a bounded one-line summary -// for a chat transcript. A captured webhook payload exists to be inspected -// and mapped field-by-field (see docs/prds/event-sources-and-reactions.md -// and t2db.3's schema-by-example mapping) -- redacting every string would -// make that impossible. Only a value whose key matches the marker list, or -// whose value is an unambiguous secret shape, is touched; everything else is -// returned exactly as decoded. +// SummarizeToolParameters shape unchanged: that function replaces every string +// value regardless of key, which produces a bounded one-line summary for a chat +// transcript. A captured webhook payload exists to be inspected and mapped +// field-by-field -- redacting every string would make that impossible. Only a +// value whose key matches the marker list, or whose value is an unambiguous +// secret shape, is touched; everything else is returned exactly as decoded. // // A key match redacts its entire value, including a nested object or array // -- "credentials": {"host": ..., "user": ...} is wholesale replaced, not diff --git a/internal/webui/api_apply_status.go b/internal/webui/api_apply_status.go index 1f11e5ef4..78a022748 100644 --- a/internal/webui/api_apply_status.go +++ b/internal/webui/api_apply_status.go @@ -12,7 +12,7 @@ import ( // The readings an operator acts on. A process is current when it is running // what it last reported, failed when it rejected what the store holds, and // unknown when it has stopped re-stamping: a record that outlived its process -// must never read as current (docs/prds/control-plane-apply-status.md). +// must never read as current. const ( applyStateCurrent = "current" applyStateFailed = "failed" diff --git a/internal/webui/api_chat.go b/internal/webui/api_chat.go index 4b3df5eed..144a19ae1 100644 --- a/internal/webui/api_chat.go +++ b/internal/webui/api_chat.go @@ -400,10 +400,9 @@ func (s chatStreamSink) ToolCall(event messaging.ToolCallEvent) { }) } -// Media has no inline rendering path on the dashboard yet (see -// archie-core-1786748942243-6-f109697e), so it degrades to a link in the -// delta stream -- the same fallback Telegram's liveReply uses when its own -// SendMedia call fails. +// Media has no inline rendering path on the dashboard yet, so it degrades to a +// link in the delta stream -- the same fallback Telegram's liveReply uses when +// its own SendMedia call fails. // // A local file cannot be linked and this channel cannot upload one, so it // is REPORTED as undelivered rather than skipped. Skipping was right while diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index b1d50b81f..7aa9e24d5 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -122,7 +122,7 @@ type ConfigView struct { // Review is the layered pr-review policy: what a review may post, and // whether a human decides. It is a plain projection of the effective // cfg.Review, so the published snapshot tells a reader which dials are in - // force (docs/prds/review-settings-resource.md). + // force. Review ReviewView `json:"review"` Storage StorageView `json:"storage"` Containers ContainersView `json:"containers"` @@ -156,7 +156,7 @@ type ConfigView struct { // Server.resolveForge (api_tasks.go). Empty for a single-identity // deployment, whose forge is Identity above. Identities []ForgeIdentityView `json:"identities,omitempty"` - // Schema is the field-descriptor catalog (archie-core-b6ew) attached to + // Schema is the field-descriptor catalog attached to // this view's own values and locked reasons -- see config_schema.go. It // carries the labels, sections and types a generic configuration renderer // needs, instead of making each rendering process hardcode them; the flat @@ -359,7 +359,7 @@ type CatalogProviderView struct { // // It is deliberately a function, not a method: rendering the view is not a // property of an HTTP server, and the process that owns configuration is not -// the process that serves this page (archie-core-ml30). +// the process that serves this page. func BuildConfigView(in ConfigViewInput) ConfigView { cfg := in.Config provenance := append([]ConfigOrigin(nil), in.Provenance...) @@ -427,7 +427,7 @@ func BuildConfigView(in ConfigViewInput) ConfigView { // // The definition lives in config.ChatConfig.FrontEnds, not here: the daemon's // channel status manager answers the same question on /api/channels, and -// deciding it twice is how the two answers drifted apart (GitHub #821). +// deciding it twice is how the two answers drifted apart. func chatChannelConfigured(chat config.ChatConfig) bool { return chat.AnyFrontEndConfigured() } diff --git a/internal/webui/api_curators.go b/internal/webui/api_curators.go index 818dd8b6d..645a27d24 100644 --- a/internal/webui/api_curators.go +++ b/internal/webui/api_curators.go @@ -19,8 +19,8 @@ type CuratorActionView struct { // registry: the names, point-in-time health, and recent activity the // dashboard's curator view renders. It is deliberately narrower than the // registry itself -- whose engine contract drags in the agent toolchain -- -// so the UI process holds the view without linking it -// (archie-core-8cda.5.6). Whoever owns the registry supplies an adapter at +// so the UI process holds the view without linking it. +// Whoever owns the registry supplies an adapter at // bootstrap. type CuratorStatus interface { Names() []string @@ -60,7 +60,7 @@ type CuratorHealthView struct { // handleCurators reports which curators are registered, their point-in-time // health, and their recent activity -- which curators exist, when each last -// ran, what it changed, and why (archie-core-1786637489932-6). The registry +// ran, what it changed, and why. The registry // is the sole source of truth; this handler is transport only. func (s *Server) handleCurators(w http.ResponseWriter, r *http.Request) { if s.Curators == nil { diff --git a/internal/webui/api_harness.go b/internal/webui/api_harness.go index fb7908071..11004ee8f 100644 --- a/internal/webui/api_harness.go +++ b/internal/webui/api_harness.go @@ -48,16 +48,14 @@ type harnessProfileDoc struct { // HarnessTerminal opens an ephemeral setup session for one Kit profile: a // duplex byte stream to the container's PTY, on the same egress path a Kit -// task runs on (docs/prds/external-agent-harness.md, "Setup terminal"). +// task runs on. // -// It is a seam, not an implementation. The container, the sandbox network -// and the egress session belong to the daemon, and the dashboard process is -// forbidden from linking them (cmd/archie-ui/architecture_test.go bans -// internal/container, internal/app/archied and internal/agentexec). A -// composition wires whichever transport carries the session; nil answers the -// route 503 rather than pretending a terminal exists. The interface's -// method types are stdlib only, so a future transport that implements it -// cannot drag a banned package into the UI binary. +// It is a seam, not an implementation. The container, the sandbox network and +// the egress session belong to the daemon, and the dashboard process is +// forbidden from linking them. A composition wires whichever transport carries +// the session; nil answers the route 503 rather than pretending a terminal +// exists. The interface's method types are stdlib only, so a future transport +// that implements it cannot drag a banned package into the UI binary. type HarnessTerminal interface { Open(ctx context.Context, orgID, profile string) (io.ReadWriteCloser, error) } diff --git a/internal/webui/api_mapping.go b/internal/webui/api_mapping.go index fa96a57bf..4de9d1802 100644 --- a/internal/webui/api_mapping.go +++ b/internal/webui/api_mapping.go @@ -187,7 +187,7 @@ func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) { // mappingPreviewRequest lets an operator resolve a candidate set of fields // against a real captured event before saving anything -- Fields is loose -// input, not a saved mapping ID, per docs/prds/payload-field-mapping.md. +// input, not a saved mapping ID type mappingPreviewRequest struct { CaptureID string `json:"capture_id"` Fields []mapping.Field `json:"fields"` @@ -225,10 +225,8 @@ func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) { } // captureByID finds one captured event by ID. CaptureStore exposes only -// ListCaptures (see docs/prds/event-capture-storage.md -- capture has -// exactly one reader, the dashboard list view, so a by-ID lookup was never -// needed until preview), so this scans the newest window rather than -// adding a new store method for a single low-volume caller. +// ListCaptures, so this scans the newest window rather than adding a new store +// method for a single low-volume caller. func (s *Server) captureByID(ctx context.Context, id string) (*storecontract.CapturedEvent, error) { captures, err := s.Captures.ListCaptures(ctx, mappingCaptureScanWindow(s.CaptureMaxEvents)) if err != nil { diff --git a/internal/webui/api_skills.go b/internal/webui/api_skills.go index bea376fff..31ed8de44 100644 --- a/internal/webui/api_skills.go +++ b/internal/webui/api_skills.go @@ -14,7 +14,7 @@ type SkillView struct { // SkillCatalog is the webui-owned source of the dashboard's skill // catalogue. It is deliberately a view over already-discovered entries, not // the discovery machinery: the cataloguer (internal/skill) drags the agent -// toolchain in, and the UI process must not link it (archie-core-8cda.5.6). +// toolchain in, and the UI process must not link it. // Whoever owns the runtime -- the daemon, via its config -- supplies an // adapter at bootstrap; an unwired catalog degrades to an empty page. type SkillCatalog interface { diff --git a/internal/webui/api_source.go b/internal/webui/api_source.go index 94539640f..c3df95125 100644 --- a/internal/webui/api_source.go +++ b/internal/webui/api_source.go @@ -10,11 +10,10 @@ import ( "github.com/samcharles93/archie-core/internal/domain/storecontract" ) -// Capture sources and their signing setting (docs/prds/event-automation.md -// "Sources"). A secret is returned only by the two writes that generate it, -// so the operator can copy it into the sender; every other read withholds it. -// Turning signing off is a request plus an approval, both behind the same -// mutation gate that arms a binding. +// Capture sources and their signing setting. A secret is returned only by the +// two writes that generate it, so the operator can copy it into the sender; +// every other read withholds it. Turning signing off is a request plus an +// approval, both behind the same mutation gate that arms a binding. func (s *Server) handleSourcesList(w http.ResponseWriter, r *http.Request) { if s.Sources == nil { diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index 6c156cc7a..1bb540d30 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -190,9 +190,8 @@ func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) { type taskActionRequest struct { Action string `json:"action"` // Instructions is the re-review's focus, required by the rereview action - // and ignored by every other one (docs/prds/pr-review-operator- - // response.md, Decision 1). The dashboard is the authoritative surface - // that carries operators' instructions; chat is a shortcut with no + // and ignored by every other one. The dashboard is the authoritative + // surface that carries operators' instructions; chat is a shortcut with no // instruction syntax. Instructions string `json:"instructions"` // Findings are the keys of the offered findings an approve posts; an @@ -358,7 +357,7 @@ func validOrigin(u *url.URL, wantScheme, wantHost string) bool { // applyOperatorTaskAction sends the action to whoever owns task execution. // The dashboard operator is authenticated and acts across identities, which -// the Gateway contract carries as its own method (archie-core-8cda.5.4). +// the Gateway contract carries as its own method. // // The UI process cannot run this itself: retry limits come from the daemon's // configuration, closing the forge issue needs its forge client, the diff --git a/internal/webui/api_tasks_attempts.go b/internal/webui/api_tasks_attempts.go index e8893319a..668196f32 100644 --- a/internal/webui/api_tasks_attempts.go +++ b/internal/webui/api_tasks_attempts.go @@ -70,8 +70,8 @@ type taskStageView struct { // stages it recorded. Attempt bounds, event counts and which attempt numbers // exist still come from the task's events (an attempt can carry events with // no step, e.g. agent calls, so events remain the complete attempt index); -// the stages themselves are step_executions, the authoritative record -// (docs/prds/execution-tree-state-machine.md), not a fold over +// the stages themselves are step_executions, the authoritative record, +// not a fold over // stage_start/stage_finish events. func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) { t, ok := s.taskByPathID(w, r) @@ -243,8 +243,8 @@ func attemptBounds(evs []events.Event) (first, last time.Time) { } // stageViewsFromSteps builds an attempt's ordered stage occurrences directly -// from its recorded StepExecutions -- the authoritative record -// (docs/prds/execution-tree-state-machine.md), not a fold over +// from its recorded StepExecutions -- the authoritative record, +// not a fold over // stage_start/stage_finish events. Only kind "stage" steps are shown: agent // and call steps are the tree's own detail, not this rail's. func stageViewsFromSteps(steps []task.StepExecution, inFlight bool) []taskStageView { diff --git a/internal/webui/api_workflows.go b/internal/webui/api_workflows.go index d8a56d79f..5242195c2 100644 --- a/internal/webui/api_workflows.go +++ b/internal/webui/api_workflows.go @@ -54,7 +54,6 @@ type workRequest struct { // pr_number, for instance. The handler checks the assignment against the // declaration before the task is admitted, so a request that could only // fail at the workflow's first stage is refused here instead - // (archie-core-06nq). Inputs map[string]any `json:"inputs"` } diff --git a/internal/webui/authorize.go b/internal/webui/authorize.go index 9ef34dd22..f85de41b6 100644 --- a/internal/webui/authorize.go +++ b/internal/webui/authorize.go @@ -1,12 +1,11 @@ -// The access chain at the dashboard and API request path: the second of the -// two places that call the Authorizer (docs/prds/orgs-and-access.md, "Where -// it lives"). A request that carries an identity is assembled into a -// principal; the action and resource kind are derived from the route; the -// chain decides; a denial is recorded with the level that decided it and -// reported as forbidden without the reason. +// The access chain at the dashboard and API request path: the second of the two +// places that call the Authorizer. A request that carries an identity is +// assembled into a principal; the action and resource kind are derived from the +// route; the chain decides; a denial is recorded with the level that decided it +// and reported as forbidden without the reason. // -// The shared token is the single-operator install's owner of the default org -// (docs/prds/orgs-and-access.md, "Credentials"): the token principal is +// The shared token is the single-operator install's owner of the default org: +// the token principal is // assembled here, not looked up, until principal credentials exist. package webui @@ -80,7 +79,7 @@ func (s *Server) authorize(h http.Handler) http.Handler { return } // A denial inside the caller's org is forbidden, without the - // reason (docs/prds/orgs-and-access.md, "Denials"). + // reason. http.Error(w, "forbidden", http.StatusForbidden) return } @@ -174,8 +173,8 @@ func routeOverride(action access.Action, path string) (access.Action, access.Res return access.ActionUpdate, access.KindSecret, segmentValue(path, 2), true case matchPrefix(path, "/api/harness/terminal"): // Opening the setup terminal captures the binding's OAuth tokens, so - // it is the update action on the secret - // (docs/prds/external-agent-harness.md, "Setup terminal"). The shipped + // it is the update action on the secret. + // The shipped // org-owner and org-admin policies grant it; the terminal is // admin-only. return access.ActionUpdate, access.KindSecret, "", true diff --git a/internal/webui/config_schema.go b/internal/webui/config_schema.go index 425c8265e..01b302e95 100644 --- a/internal/webui/config_schema.go +++ b/internal/webui/config_schema.go @@ -1,6 +1,6 @@ package webui -// Configuration schema contract (archie-core-b6ew.1): descriptor types and +// Configuration schema contract: descriptor types and // hand-authored field/section metadata for the Configuration page. // // This is deliberately NOT a reflection-based schema over config.Config. @@ -13,12 +13,11 @@ package webui // attaches a label to a value that was already vetted as safe to show, // rather than inventing a new safety boundary. // -// See docs/prds/config-schema.md for the full design. // ConfigFieldType is how the frontend's generic renderer decides what // control to show for a field. FieldStructured fields (repositories, // models, providers) opt out of the generic renderer entirely and keep -// their dedicated editors (archie-core-b6ew.4). +// their dedicated editors. type ConfigFieldType string const ( @@ -32,7 +31,7 @@ const ( // ConfigField is one field's rendering contract: what it is, what it means, // and what changing it would require. Value is attached by the caller -// building the schema against a live ConfigView (archie-core-b6ew.2) -- the +// building the schema against a live ConfigView -- the // descriptor itself is data-independent. type ConfigField struct { // Key is the dotted path this field is addressed by. @@ -68,7 +67,7 @@ type ConfigSection struct { // configFieldDescriptors is the hand-authored catalog: one entry per field // ConfigView exposes today, in the section grouping settings.js already // renders. Values and LockedReason are attached separately -// against a live ConfigView (archie-core-b6ew.2); this list is the +// against a live ConfigView; this list is the // data-independent half of the contract -- key, label, type, and the // safety-relevant property (restart_required) that must be decided // deliberately rather than defaulted. diff --git a/internal/webui/event_pump.go b/internal/webui/event_pump.go index 6aba3e75f..7e4fc2ca8 100644 --- a/internal/webui/event_pump.go +++ b/internal/webui/event_pump.go @@ -31,20 +31,11 @@ const ( eventPumpPrimeRetryMax = 30 * time.Second ) -// eventPump is the UI process's substitute for the daemon's in-process event -// bus. The daemon hands persisted events to Server.Broadcast from its own bus -// subscription (internal/app/archied/main.go's persistAndBroadcastEvents); a -// process that owns no bus reads the same events back out of the State Store -// instead, over the EventsSince cursor. -// -// Polling is sufficient rather than a compromise, for the reasons recorded in -// docs/architecture/migration-decisions.md ("Dashboard live event delivery"): -// EventsSince pages a total order over (at, id) with a fixed-width time key -// and a deterministic id tie-break, so the cursor cannot skip or repeat; -// sseStream.drain treats a broadcast as a wakeup and re-reads the gap from the -// store, so nothing here changes SSE semantics; and reading the table catches -// writers that never touch a bus, including the audit event ArchiveTask writes -// inside its transaction. +// eventPump stands in for the daemon's event bus in the UI process: it polls +// persisted events from the State Store over the EventsSince cursor and +// broadcasts them. EventsSince pages a total order over (at, id), so the cursor +// never skips or repeats, and polling the table also catches writers that never +// publish to a bus. type eventPump struct { store eventReader log func(string, ...any) diff --git a/internal/webui/server.go b/internal/webui/server.go index e4764277b..7d4455b00 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -26,8 +26,8 @@ type Server struct { Store storecontract.TaskStore Log *slog.Logger - // Steps lists one execution's recorded StepExecutions - // (docs/prds/execution-tree-state-machine.md): the run detail's + // Steps lists one execution's recorded StepExecutions: + // the run detail's // authoritative source, GET /api/tasks/{id}/attempts. Nil degrades the // route to reporting no steps rather than folding stage_start/ // stage_finish events, which tasks.stage used to back and no longer @@ -50,8 +50,8 @@ type Server struct { // process whichever implementation it can use: the daemon (whose state // directory holds the files) its own *logging.TaskRegistry, and the // dashboard process, which owns no such directory, the State Store client - // -- the read crosses a contract rather than opening a file - // (docs/prds/ui-service-boundary.md). Nil means this process has no + // -- the read crosses a contract rather than opening a file. + // Nil means this process has no // task-log capability at all, which the handlers report as disabled rather // than as "the attempt has no log": those are different claims and only one // of them is about configuration. @@ -71,9 +71,9 @@ type Server struct { // /api/skills to an empty page. Skills SkillCatalog - // Curators is the daemon's live curator registry (epic archie-core-yp9). + // Curators is the daemon's live curator registry. // Backs GET /api/curators: registered names, per-curator health, and - // recent activity (archie-core-1786637489932-6). Optional: nil reports + // recent activity. Optional: nil reports // an empty curator list rather than failing the dashboard. Curators CuratorStatus @@ -94,7 +94,7 @@ type Server struct { // ApplyStatus reports which control-plane resource version each process // is running. Optional: nil renders an empty page rather than failing the - // dashboard (docs/prds/control-plane-apply-status.md). + // dashboard. ApplyStatus storecontract.ApplyStatusStore // now is the clock applyState reads staleness against. Nil means // time.Now; tests set it to pin a record's age. @@ -118,8 +118,8 @@ type Server struct { // through a browser -- an agent does exactly that. Login identity.LoginFlow - // Access evaluates the policy chain for each request - // (docs/prds/orgs-and-access.md). Optional: nil keeps the credential + // Access evaluates the policy chain for each request. + // Optional: nil keeps the credential // check as the whole gate -- the documented behaviour of an install that // has not built the chain. Principals assembles the request principal // from the acting identity; Denials records refusals. All three are @@ -134,8 +134,8 @@ type Server struct { Events EventPublisher // Captures backs the dashboard's read of captured events: the - // GET /api/captures list and the mapping preview's by-ID scan - // (docs/prds/event-capture-storage.md). Optional: nil makes the list + // GET /api/captures list and the mapping preview's by-ID scan. + // Optional: nil makes the list // answer {"enabled": false} rather than the dashboard failing to start. Captures storecontract.CaptureStore // CaptureMaxEvents is the operator's configured [capture] max_events, @@ -147,46 +147,45 @@ type Server struct { // senders, so it cannot sit behind requireToken. The handler is owned // by internal/infrastructure/captureintake.Receiver; this package only // mounts the route and reads the rows back. The UI process composes - // it from the cutover change (archie-core-8cda.5.4) -- it is the only + // it from the cutover change -- it is the only // dashboard listener left, and a capture POST answered by the // token-gated mux would leave intake with no owner. Nil removes the // route, which is what a store without the capture contract gets: // two listeners with the same intake authority is what the boundary - // forbids (docs/prds/ui-service-boundary.md:30-33). + // forbids. CaptureIntake http.Handler - // Mappings persists payload field mappings (docs/prds/payload-field-mapping.md). + // Mappings persists payload field mappings. // Optional: nil makes every /api/mappings route answer 503 rather than // the dashboard failing to start. Mappings storecontract.MappingStore - // EventTypes persists event types (docs/prds/event-automation.md). Optional: + // EventTypes persists event types. Optional: // nil reports the inspector's event types as disabled. EventTypes storecontract.EventTypeStore // Bindings persists playbook bindings: matcher + mapping + workflow - // triples that turn a captured webhook into an archie task - // (docs/prds/webhook-intake-security.md). Optional: nil makes every + // triples that turn a captured webhook into an archie task. + // Optional: nil makes every // /api/bindings route answer 503 rather than the dashboard failing to start. Bindings storecontract.BindingStore - // Sources persists capture sources and their signing setting - // (docs/prds/event-automation.md "Sources"). Optional: nil makes every + // Sources persists capture sources and their signing setting. + // Optional: nil makes every // /api/sources route answer 503 and marks no binding unsigned. Sources storecontract.SourceStore // HarnessSecrets reads each credential binding's captured OAuth token // set, so the harness page can report whether a binding is configured, - // when it expires and which scopes it carries - // (docs/prds/external-agent-harness.md, Credentials). The token values + // when it expires and which scopes it carries. + // The token values // themselves never reach the browser. Optional: nil answers // /api/harness/bindings 503 rather than claiming the org has none. HarnessSecrets storecontract.HarnessSecretStore // HarnessTerminal opens the setup terminal, a duplex PTY session in an - // ephemeral Kit container (docs/prds/external-agent-harness.md, "Setup - // terminal"). Optional: nil answers /api/harness/terminal 503. The - // implementation belongs to a process that owns containers; the + // ephemeral Kit container. Optional: nil answers /api/harness/terminal 503. + // The implementation belongs to a process that owns containers; the // dashboard consumes it over a contract and never links one. HarnessTerminal HarnessTerminal @@ -203,7 +202,7 @@ type Server struct { // its next boot -- the webui counterpart of // channels/telegram.Gateway.UpdateReportPath. Empty (the default unless // composition wires it) means dashboard-initiated updates get no - // phase-2 report (archie-core-nln7): the operator only sees the + // phase-2 report: the operator only sees the // synchronous install result, never restart/health/version outcome. UpdateReportPath string @@ -376,7 +375,6 @@ func (s *Server) Handler() http.Handler { } // The chain runs after the credential check and before any handler: the // principal exists only once the credential resolved - // (docs/prds/orgs-and-access.md, "Where it lives"). top.Handle("/", s.requireToken(s.authorize(mux))) return top } diff --git a/internal/webui/sse.go b/internal/webui/sse.go index c476b766e..e562087ec 100644 --- a/internal/webui/sse.go +++ b/internal/webui/sse.go @@ -70,11 +70,6 @@ func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) { stream.drain(r.Context(), conn, stale, logs) } -// sseSince is the task-only cursor view retained for legacy clients/tests. -// Native reconnects prefer Last-Event-ID; deliberate reconnects use ?since=. -// An invalid or pre-cursor integer degrades to replay from the beginning. -func sseSince(r *http.Request) string { return sseCursors(r).Tasks } - type streamCursors struct { Tasks string `json:"tasks"` Logs int64 `json:"logs"` diff --git a/internal/worktree/worktree.go b/internal/worktree/worktree.go index 83550ead5..081109607 100644 --- a/internal/worktree/worktree.go +++ b/internal/worktree/worktree.go @@ -50,8 +50,8 @@ import ( // It lives inside .git deliberately. The previous implementation kept it // in the working tree and hid it via .git/info/exclude, which worked // because `git add -A` honours that file -- go-git's Add does NOT, so the -// sentinel was committed and pushed onto every task branch. Nothing under -// .git can ever be tracked, so placing it here removes the failure mode +// sentinel was committed and pushed onto every task branch. Nothing under. +// git can ever be tracked, so placing it here removes the failure mode // rather than papering over it. const preparedSentinel = ".git/archie-prepared" @@ -864,12 +864,11 @@ func fileChange(fp fdiff.FilePatch) task.FileChange { return change } -// Snapshot exports HEAD's tracked files into a fresh, empty destDir with no -// .git directory: file contents only, no commit history, branch name, or -// reflog. Used to build the reviewer's isolated workspace (the isolation -// contract in docs/prds/pr-review-agent.md) -- stripping .git is -// what makes the implementer's reasoning (commit messages, branch name, -// history) structurally unreachable rather than merely undisclosed. +// Snapshot exports HEAD's tracked files into a fresh, empty destDir with no. +// git directory: file contents only, no commit history, branch name, or reflog. +// Used to build the reviewer's isolated workspace -- stripping.git is what +// makes the implementer's reasoning (commit messages, branch name, history) +// structurally unreachable rather than merely undisclosed. func (m *Manager) Snapshot(ctx context.Context, dir, destDir string) error { r, err := git.PlainOpen(dir) if err != nil {