The gateway work added /whoami, /profile, /sessions, /resume and /agents as
executable commands; TestPublishedCommandsMatchExecutableCommandSurface
correctly caught that they were undiscoverable. Two workers touching a
coupled surface -- the test is the thing that noticed.
These five command handlers were dropped during parallel merges of the
Telegram workers; the Router fields they depend on (Identity, Models,
Sessions, Agents) were already in place.
/new, /reset, /topic, /retry, /undo, /title, /branch, /fork, /compress,
and /compact are executable via the gateway router but were missing
from gatewayCommandSpecs, making them undiscoverable in Telegram's
command menu and /help output.
internal/config both defined the types every package imports and performed
the file I/O to produce them. Importing a settings struct therefore pulled
in a TOML decoder and a YAML decoder, and the shared model owned discovery,
decoding, overlays, defaulting and validation all at once. See
docs/architecture/configuration.md, which requires loading to move out and
internal/config to be dissolved.
internal/config is now types only -- no os, no filepath, no toml. The new
package owns loading, one concern per file:
features.go the closed set of recognised feature files
discovery.go directory scan and classification
decode.go TOML/YAML decoding, format dispatch
defaults.go filling absent values, no errors
validate.go judging supplied values, no mutation
provenance.go which file contributed what
loader.go Loader wiring the above; File/Overlay/Dir
Beyond relocating, this fixes what the old code conflated:
- Defaulting and validation were interleaved. applyAgentDefaults and
applyDispatchDefaults returned validation errors; validateContainers and
validateSingleIdentity quietly mutated the config. There was no point at
which you could see what the operator actually supplied. They are now
separate passes: applyDefaults never fails, validate never writes.
- Errors were fmt.Errorf strings prefixed "config: ", so a caller could not
distinguish operator-fixable input from an unreadable file without
matching message text. Five sentinels now carry that distinction.
- dataHome() read XDG_DATA_HOME directly and discarded the error from
os.UserHomeDir, so defaulting could not be tested without the
environment. It is injectable on Loader and no longer swallows the error.
- Nothing recorded where a value came from. With overlays, feature files
and conf.d/ all able to set the same field, "which file set this?" was
answerable only by re-deriving precedence by hand. Provenance records it.
- Feature files were applied in map iteration order, making load order and
any resulting error arbitrary. Discovery now returns them sorted.
- loadMainConfig reported "no config.yaml or config.toml found in %s" with
an empty string: the directory was lost when it was extracted from
loadDirInto, so the error named no directory.
- Unreadable or malformed conf.d/ extras were skipped silently, which
presents as a setting the operator wrote simply not taking effect.
- Decode errors from the main config were returned bare, without naming
the file that failed to parse.
The 40 loader tests moved with the code and their assertions are unchanged,
so the defaulting and validation rewrite is behaviour-preserving.
Document.Config is the temporary seam: still internal/config.Config, named
as a field so the compromise is visible at each use site, with its deletion
condition recorded in doc.go. Building typed per-domain sections now, while
every consumer still reads config.Config, would mean two shapes kept in sync
by hand with no consumer for the new one; that belongs with the dissolution
work, not ahead of it.
No consumer outside cmd/archied changed.
Verified: go build, go vet, gofmt clean; go test ./internal/config/... and
./internal/infrastructure/configuration/... pass. Pre-existing gateway and
telegram failures are unchanged.
RegisterAll returned as soon as nc.Subscribe had queued each SUB frame on
the client. Delivery to the server is asynchronous, so a caller that
registered a responder and immediately issued a request could beat its own
subscription and get nats.ErrNoResponders from a responder that was, by
then, listening.
This made TestRunTaskExecutesBootstrapWorkflowEndToEnd flaky in CI: it
passed in isolation and failed under full-suite load, when the scheduler
was contended enough for the request to win the race.
Flushing after subscribing gives Register a real guarantee -- a nil error
now means the subjects are reachable. That applies to production startup
too, not just tests: archied registers storerpc, forgerpc and worktreerpc
the same way.
The duplicated rollback loop is now a single unsubscribeAll closure, which
also becomes the returned unsubscribe func.
Verified: three consecutive full-suite runs with no archie-agent failure,
plus five targeted runs of the rpc packages. Remaining gateway and
telegram failures are pre-existing and unrelated.
The event bus was inspecting forge issue labels ("bug", "feature",
"bootstrap") to pick a subject. That put a forge vocabulary inside
infrastructure and duplicated the label table already owned by
workflow.Route -- adding a label meant remembering both places, and
nothing would have caught it if you forgot.
The label table now lives once, in internal/workflow, which already owns
label semantics:
- workflow.Kind names the routing category, with labelKinds as the
single label vocabulary and kindWorkflows mapping kind to registry
entry. Route consumes the ordered kind list so a "bug,feature" task
still falls through to feasibility when no tdd workflow is
registered, exactly as the switch did.
- nats.TaskKind is a closed, validated set of subject tokens.
PublishTask rejects an unknown kind rather than silently delivering
it to the default queue; the zero kind means default, so messages
queued before this field decode unchanged.
- The daemon classifies at the publish site and sets TaskEnvelope.Kind.
Also fixes two defects this exposed:
- drainNATS never reached its SQLite fallback. Replacing the old
(nil, nil) no-message signal with ErrNoMessage in 492ca20 made that
case continue at the top of the loop, but no-message is precisely
when the fallback must run -- requeued tasks (waiting_human approval,
retry-parked) never go through a NATS publish, so nothing would ever
arrive to trigger them. go vet caught it as unreachable code.
- config.classifyFeatureFile silently overwrote duplicate feature
files, so config.gateway.yaml and conf.d/gateway.yaml together
applied one at random. Its own doc comment recorded the bug
("or "" on success/duplicate"). The known-feature list in the error
message is now derived from knownFeatureNames instead of being
spelled out a second time beside it.
A test also called t.Fatalf from a non-test goroutine, where it does not
stop the test.
Verified: go build, go vet, gofmt clean. Pre-existing gateway (18) and
telegram (1) failures are unchanged in count -- they are lost routing
wiring from the parallel telegram merges, tracked separately.
Relocating internal/nats as-is would have cemented its problems into the
approved layout, so this is a rewrite rather than a move.
What was wrong:
- Conn() *nats.Conn, PublishMsg(*nats.Msg) and Fetch() jetstream.Msg pushed
SDK types into all four consumers, so the broker was not replaceable --
the opposite of what dependencies-and-contracts.md requires.
- PublishTask took seven positional parameters, six of them strings, where a
transposed argument was a silent bug.
- Labels travelled as a comma-separated string and were re-split on every
publish.
- Fetch returned (nil, nil) for 'no message', which every caller had to
remember to special-case.
- The logger field was stored and never used.
- Stream name, consumer name and every timeout were hardcoded constants.
- Errors were inconsistently wrapped; several paths returned bare errors.
- Connect repeated nc.Close() on each failure branch.
What replaces it:
- One concern per file: config, errors, subjects, message, client,
publisher, consumer.
- Publisher/Consumer/Requester interfaces with compile-time assertions, so
callers depend on behaviour and can be faked without a broker.
- A Message wrapper keeps jetstream types behind the boundary; consumers no
longer import the NATS SDK at all.
- TaskEnvelope with []string labels and JSON methods preserving the
comma-separated wire form for already-queued messages.
- Sentinel errors (ErrNoMessage, ErrNotConnected, ErrNoReplyAddress,
ErrInvalidConfig) and %w wrapping with operation context throughout.
- Config with validation and defaults; a single deferred cleanup in Connect.
- CoreConn() as the one documented escape hatch, for the *rpc packages that
are themselves NATS infrastructure.
Consumers migrated: cmd/archied, cmd/archie-agent, internal/daemon,
internal/agentexec. Behaviour, subjects and wire format unchanged.
- bodyclose: add deferred resp.Body.Close() in storage_test.go Docker test handler
- contextcheck: thread context through email handleSMTP/processMessage; replace
context.Background() with context.WithoutCancel(ctx) in telegram, webhook, webui
shutdown paths and container pool cleanup; add ctx parameter to Pool.Release
- containedctx: replace ctx context.Context struct field with stopCh chan struct{}
in StdioTransport and SSETransport; thread lifecycle context through goroutine
chains instead of storing it in structs
- fatcontext: lift context deadline derivation out of PrefetchContext loop
Add gateway/runtime-owned commands that remain usable when LLM credits
are exhausted:
- /start — acknowledgement without consuming a reply
- /new [name] (alias: /reset) — create a fresh session
- /topic [off|help|<session-id>] — session switching for threaded chats
- /retry — remove last assistant message, replay last user turn
- /undo [N] — remove last N messages from history (default: 1)
- /title [name] — set or display session title
- /branch [name] (alias: /fork) — create child session with inherited history
- /compress [here N|focus topic|--preview|--dry-run] (alias: /compact)
Design:
- sessionTracker maps channel+thread to active session, auto-creating
implicit sessions with the legacy sessionKey format for backward
compatibility with existing persisted data
- /new and /branch create explicit UUID-backed sessions
- SessionStore extended with DeleteRecentMessages, MessageCount, and
SaveMessages for undo/retry/branch/compress operations
- SessionContext extended with Title, ParentSessionID, BranchName
- All commands report 'not configured' when session store isn't wired
Session resolution is wired into the LLM responder so /new, /branch,
and /topic switches affect subsequent chat turns.
Implement session-scoped goal/subgoal/steer/queue state management
with thread-safe access and prompt injection for standing goals.
Commands:
- /steer <text> — queue a message to inject after the next tool call
- /goal [text|draft|show|pause|resume|clear|status|wait|unwait]
- /subgoal [text|remove N|clear]
- /queue (aliases /q, /bg, /btw, /background) [text|remove N|clear]
Architecture:
- SessionState in internal/gateway holds per-session goals, subgoals,
steer queue, wait flag, and background queue
- Goals are injected into the system prompt via BuildGoalPrompt()
- Steer messages are consumed between agent tool-calling steps via a
MaxSteps=1 loop in the daemon's respond closure
- Commands route through the existing gateway.Router with not-configured
guards when State is nil
Closes: archie-core-alm.1
Extend /model command to support:
- /model [model] (direct switch)
- --provider <name> (provider switch)
- --global (persist scope, with ModelPersist callback)
- --session (explicit session scope, default)
- --refresh (show current active model)
Add /personality command:
- /personality lists available personalities with inline keyboard
- /personality <name> switches directly
- Callback handling for inline keyboard selection
Router changes:
- Add Personas field (wired to PersonaRegistry in main.go)
- Add ModelPersist callback for --global persistence
- Route /personality as a local command
- Extend handleModel to accept full rest text with flag parsing
Gateway-local commands that report from Archie-owned state:
- /whoami: reports the Archie identity the user is talking to
- /profile: shows active Archie profile (identity, provider, model, available models)
- /sessions: lists recent sessions with last-active timestamps
- /resume [id]: resumes a session by ID or prefix match
- /agents: lists active agents and running/waiting tasks
Adds SessionLister and AgentReader interfaces to Router, wired from the
daemon composition root. SessionStore already satisfies SessionLister.
AgentReader is a thin adapter over store.Task list filtered to active
states (running, waiting_human, parked).
All commands are published in Telegram's menu and /help, and respond
with 'not configured' when their backing interface is nil.
Closes archie-core-alm.2
Hide /approve from Telegram's command menu, help text, and discoverability.
Telegraph users can no longer learn about task approvals through the bot.
/approve remains executable in the gateway router for email and webhook
channels; non-Telegram workflow callers are unaffected. Daemon polling of
forged waiting_human tasks and the Requeue(→implement) handoff are untouched.
Auto-fix lint issues and reformat imports across all files.
gci: group imports per project convention
gofumpt: format unused imports with blank lines
gofix: Go standard fixes
goimports: organize imports
Remaining 54 issues require manual judgment (not auto-fixable).
- Remove unnecessary string() conversion on res.Status in workflow/agent.go
(Status is already string in agentexec.Result)
- Fix TestRunWrapsExternalCommand: sh -c only reads the first argument as
the command string. exec.CommandContext("sh", "-c", "echo wrapped")
passes the intent correctly, while the previous split form
(", "", "echo", "wrapped"") treated "wrapped" as /bin/bash.
Move 5 skills (2093 lines) to /work/apps/archie-skills-parked: they
commissioned architecture campaigns, decision ledgers, evidence packets
and acceptance gates on every agent that opened the repo. Twelve factual
skills remain (6376 -> 4283 lines).
Add a CLAUDE.md scope-discipline section stating the architecture docs
are complete and authoritative, so agents implement against them instead
of extending them. Close the two architecture planning issues.
Fold the old docs/ into the VitePress site and rename docs-2 -> docs.
The 12 architecture PRDs become first-class pages at docs/architecture/
with sidebar nav, rather than being buried under an archive path.
Historical material stays at docs/archive/. Rewrites every docs-2 and
docs/prds/architecture reference across the repo. Site builds clean.
Missed in f800e1d, which ported internal/worktree but stopped at "the
sibling package still compiles".
Both NATS handlers ran their work under context.Background(). The client
side has a Timeout and passes a context, but the server discarded it, so
a prepare or push ran unbounded. That was survivable when the work was a
git child process that could be killed; after f800e1d it is an in-process
go-git clone, so an unresponsive forge wedges the handler goroutine
permanently. Removing the per-repo object cache in that same commit made
clones longer, which widens the window further.
Server now has a Timeout (defaulting to 15 minutes, sized for a large
clone over a slow link) applied via handlerContext, with a table test
asserting both the explicit and default paths produce a bounded deadline.
The fixtures also still shelled out to git, so every test in the package
skipped when no git binary was present and the helpers tripped noctx.
Rebuilt on go-git to match internal/worktree's suite, including pinning
commit.gpgSign=false on the seed repo so fixtures do not inherit signing
from the host's global config.
internal/worktree no longer executes the git binary. Clone, fetch,
checkout, commit, push and diff all run in-process through go-git v6,
which also removes the package's 9 noctx findings since the Context
variants are first-class.
Security: the forge token no longer leaves the process. The old
implementation wrote a GIT_ASKPASS shell script to disk and exported the
token into the environment of every git child process. Authentication is
now an in-process credential passed via client.WithHTTPAuth. cloneURL
also stops embedding the bot user in the GitHub URL.
Dropped the per-repo object cache (PreparePersistent, prepareCache,
CleanupExpiredCaches). go-git can clone with shared alternates but has no
equivalent of --dissociate, so a cached bare repo would remain a live
dependency of every worktree built from it, and expiring one would
corrupt running tasks rather than fail cleanly. Every task now gets an
independent full clone. repo.PersistentStorage still governs the
container volume; only the git object cache is gone.
Two real defects surfaced while porting, both caught by the new tests:
- go-git honours the host's global git config and cannot sign commits
(no gpg fallback, only an ObjectSigner plugin). On any machine with
commit.gpgSign=true set globally, every bot commit would have failed
with "cannot auto-sign commit". setIdentity now pins gpgsign=false in
the clone's own config so daemon behaviour does not depend on the
ambient config of whatever host it runs on.
- go-git's Add(All) does NOT honour .git/info/exclude, which is how the
.archie-prepared sentinel was kept untracked. It was being committed
and would have been pushed onto every task branch. The sentinel now
lives at .git/archie-prepared, where nothing can ever track it, and a
regression test asserts it never appears in a commit.
Diff is now merge-base relative via Commit.MergeBase, matching the three
dot semantics of `git diff origin/base...HEAD`; diffing against the remote
tip would attribute commits landed on base since the branch started to
this task and could trip the diff-size cap. Base resolution tries the
remote-tracking ref first and falls back to the short "origin/<base>"
revision, keeping git's more permissive lookup.
The test suite was rebuilt on go-git fixtures and no longer needs a git
binary installed to run.
97 -> 85. Not one of the eleven nilerr findings was a bug.
I called these "real bug candidates" when I planned the phases. I was
wrong, and the reason is worth recording: every site is the same
deliberate idiom, and a linter cannot see intent.
- inprocess.go (5) and gateway.go (2) are handlers that report a
problem as TEXT to their consumer. A tool handler returning a Go
error aborts the tool call; returning "rejected: ..." lets the model
read the feedback and retry with valid arguments. A chat handler
returning a Go error surfaces as a gateway fault instead of a usage
hint to the human.
- worker.go carries runErr in the response envelope's Error field.
Returning it as a Go error too would double-report and abort the
NATS reply.
- email.go returns nil when Accept fails because context cancellation
closed the listener. That is a clean shutdown.
- codesearch.go skips an unreadable entry and continues the walk. A
best-effort index must not abort on one bad file.
- skill.go is documented in the function comment already: a
non-directory skills path means "no skills", not a fatal error.
Annotated each with //nolint:nilerr and the specific reason rather than
excluding the linter by path, so nilerr stays live everywhere else and
the next reader wondering "why nil here?" gets an answer at the site.
This is the phase I insisted on keeping single-session and out of the
subagent fan-out. A worker told to "fix nilerr" would have converted all
eleven to error returns: malformed tool arguments would hard-fail the
agent loop instead of being correctable, chat typos would read as
gateway faults, and shutdown would log spurious errors. Every test would
still have passed.
130 -> 96. forcetypeassert, predeclared and usetesting are now at zero.
Fanned out across four isolated worktrees partitioned by package so no
two workers could touch the same file: internal/tools (20 assertions),
internal/webui, internal/memory + internal/ratelimit, internal/secret.
Four stragglers outside those scopes fixed inline (internal/pairing,
internal/forge, internal/channels/telegram, internal/tools/mcp).
Unchecked type assertions became comma-ok with a t.Fatalf naming the
actual type. One site in a goroutine uses t.Errorf + return instead,
since t.Fatalf from a non-test goroutine is undefined behaviour.
predeclared renames chose names from meaning rather than adding a
suffix: max -> maxQueryLen, maxMatchLen, maxRequests, alphabetLen, and
nextBackoff's max -> ceiling. `real` -> `base` in the webui tests.
os.Setenv became t.Setenv, which restores on cleanup, so the paired
deferred Unsetenv calls went with it.
Note for future fan-outs: the agent worktrees branched from origin/main
(a7388a0), not from this branch, so every diff arrived based on a tree
without the phase 1 autofix. They were applied with `git apply --3way`
and the phase 1 changes to internal/memory/manager.go were verified to
survive — in particular the repaired `ctx, cancel =` assignment. A plain
`git apply` would have silently reverted it.
golangci-lint run --fix plus the formatters: errorlint, gocritic,
sloglint, usestdlibvars, usetesting, gci, gofumpt, goimports.
160 issues -> 130.
One autofix was wrong and had to be reverted by hand. gocritic rewrote
ctx, cancel = context.WithTimeout(ctx, m.prefetchTimeout)
to `:=` inside an if-block in internal/memory/manager.go. That does not
compile, which is the good outcome — had it compiled, the shadowed ctx
would have scoped the timeout to the if-block and the prefetch deadline
would silently never have applied. Restored the assignment and commented
why it must not be a declaration.
Worth recording: --fix is not a safe no-op. It broke the build on a
24-file change, and the failure mode it was one compiler error away from
was a silent behaviour change.
The repo had no .golangci.yml at all, so golangci-lint ran on defaults
only — errcheck, govet, ineffassign, staticcheck, unused. That is why it
reported "0 issues" on a 745-line file containing 21 struct types and a
180-line finalize() with a cognitive complexity of 106.
Adds a curated set on top of the standard linters: structure (cyclop,
dupl, funlen, gocognit, gocyclo, maintidx, nestif), architecture
(depguard, importas, interfacebloat), correctness (nilerr, bodyclose,
forcetypeassert, noctx, contextcheck, errorlint, sqlclosecheck, and
friends), and hygiene (gocritic, godox, sloglint, usestdlibvars).
Deliberately not `default: all`: the formatting-opinion linters (wsl_v5,
nlreturn, varnamelen) and the absolutist ones (exhaustruct, err113,
wrapcheck) would add hundreds of pure-opinion findings. A gate that cries
wolf gets disabled, and a disabled gate enforces nothing.
depguard now encodes the internal/indexing layering rule structurally:
that package is ported from tau and must stay refreshable by diff, so it
may not import internal/config. Until now that constraint was a comment,
which is to say it was advisory.
This surfaces 160 issues (81 outside tests), so the gate is RED until they
are cleared. That is intentional: the config is the work list. Notable is
nilerr — 11 sites returning nil on a path where err != nil, six of them in
internal/agentexec, which is the class of bug that reads as "the task
silently did nothing".
Verified with `golangci-lint config verify` against the v2 JSON schema.
Follow-up to c924281, which introduced two defects of its own.
1. indexing.Config was a private config island: index paths existed nowhere
in internal/config or config.example.toml, so they were undiscoverable
and unsettable by anyone reading the real configuration.
Now [indexing] in config.toml, defined in its own internal/config/
indexer.go rather than appended to the 21-struct config.go, and its
defaulting lives with it as IndexingConfig.withDefaults so finalize
delegates instead of growing. Paths default off work_dir, keeping the
two archied instances on one host from sharing an index. Documented in
config.example.toml.
internal/indexing keeps its own plain Config and does NOT import
internal/config, so it stays a straight diff against its tau original.
2. A failed index build was invisible. refreshAsync wrote the reason to a
database column with no reader and degraded to unindexed search in
silence — the failure mode that costs hours precisely because nothing
appears to be wrong. Every give-up path now logs, and a successful
build logs once.
The logger is resolved at the point of use, not in the constructor: a
Manager can be built as a struct literal (the ported tests do), and
constructor-only defaulting panicked on the build goroutine, where a panic
takes the daemon with it. Regression test covers the zero and nil Manager.