/branch copies the parent's history into the child. Because the store
honours an incoming MessageID -- which is what lets a read-modify-write
preserve identities -- the copies kept the parent's canonical IDs, so
two sessions claimed one identity and branch-point correlation was
ambiguous. Two branches from one parent made it three. It also broke
dedup in the child: an inherited message carried an ID derived from the
parent's session, so redelivering it appended (confirmed on both
backends: 3 messages became 4).
newMessageID's doc already claimed the opposite behaviour, and the
Message.MessageID doc said it was "ignored on write" -- which is exactly
the misreading that produced this. Both now describe what the code does,
including the obligation on a caller copying messages between sessions.
Also removes a doc comment describing msgID and its disambiguating
counter, deleted in 0814f7b, which had come to sit above
messageIDNamespace describing the opposite of the current design; and
corrects the Telegram comment still claiming a redelivered update
"updates the stored turn", the behaviour the immutability fix removed.
Refs archie-core-la1
Making the store idempotent stopped redelivery duplicating the inbound
record, but nothing consulted that result: respond() saved the message,
ignored the fact that nothing had changed, and called the model anyway.
The cost was a second billed turn, any tool side effects run a second
time, and a second assistant reply appended -- replies carry no upstream
reference, so they always get a fresh identity and always append. The
stated problem, "a re-delivered update appends a duplicate turn", was
only half fixed.
PriorReply answers "have I already replied to this?" from the history
the caller has already loaded, and the chat path replays that answer
instead of regenerating it. A message with nothing after it was never
answered -- the turn may have died partway -- so that still runs, since
the user is owed a reply.
CanonicalMessageID exposes the store's own derivation rather than
letting the caller reimplement it, since a lookup that silently never
matches is indistinguishable from a message never seen.
Refs archie-core-i6q
applyCompress reads the history, computes a summary, then replaces it.
ReplaceMessages removed everything outside the replacement set, so a
chat turn saved in that window was deleted without ever having been
read, let alone summarised. Confirmed on both backends. It is
unrecoverable loss, and it sits outside the write-then-delete guarantee
because the window is in the caller, not the store.
ReplaceMessages now takes the messages the caller is superseding instead
of inferring them from the complement of the replacement. A caller
computes a replacement from a history it read; anything that arrives
afterwards is not part of that, and is now left alone. IDs in both lists
are still kept, so read-modify-write callers are unaffected.
The test fake's ReplaceMessages was a slice assignment, which could not
observe ordering or identity at all -- it now mirrors the real stores.
Refs archie-core-6e0
resolve saved a newly created session to the store and only then asked
the cache who had won a concurrent race. The loser had already persisted
a session that nothing pointed at: unreachable, but still listed by
/topic and /sessions as "(untitled)", and -- now that resolution goes by
recency -- resurrectable on a later restart. Confirmed by forcing the
interleaving: the store held 2 sessions where it should hold 1.
The claim now happens under the same double-check, ahead of the store
write, so only the winner writes. A failed Save releases the claim, or
the cache would point every later message in that chat at a session that
was never stored.
Refs archie-core-x35
handleTopic "off" copied the thread's active session onto the flat key
via setActive(getActive(...)). With nothing cached for that thread it
copied the empty string, and resolve treats map presence as
authoritative -- so it returned "" from then on, permanently, since
cacheActive also returned the empty existing value. Every later message
in that chat persisted under session "", history was shared with any
other poisoned chat, and the turn-lane key became "" so /stop in one
chat cancelled a turn in another.
Reachable as a first message on the webhook and email channels, which
call Route directly without resolving a session first.
setActive now rejects an empty session ID, so no caller can poison the
map whatever it computes, and resolve and cacheActive treat an empty
cached value as a miss so an existing entry repairs itself.
The get-then-set was also two critical sections, silently clobbering a
concurrent /resume or /branch with the value read before the switch.
flattenTopic does it in one.
Refs archie-core-jex
resolve's comment claimed to find "the most recent session matching this
thread and bot" and took whichever the store returned first. On the
NellDB store that is document order -- by session ID -- so it was
effectively arbitrary. The tracker cache is in-memory, so every restart
re-resolves from the store, and the operator could be dropped back into
a session they had left with /new, answering against pre-/new history.
Probed over 10 restarts, 4 landed in the older session. LastActiveAt was
populated on every record and never read.
resolve now picks by LastActiveAt, which also makes it independent of
the two backends disagreeing: SQLite's GetByChannel orders created_at
DESC and NellDB's did not, and the conformance suite did not pin it.
listAllLocked reversed document order and passed that off as recency,
so List -- documented newest-first, and what /sessions and the dashboard
render -- returned reverse-lexicographic order. It now sorts on
LastActiveAt, falling back to CreatedAt for records never touched.
Refs archie-core-7s3
Two defects, both confirmed on the NellDB and SQLite backends.
IDENTITY. applyCompress rebuilt the protected head and tail as bare
Message{From, Text}, so every message that survived a compression was
deleted and re-inserted with a fresh canonical MessageID, no SourceID
and a timestamp of now. A rebuilt message is a different message: after
one compression, redelivery deduplication was broken for the rest of the
session's life, so a Telegram backlog replay after a restart appended
every surviving message a second time -- 24 became 25 on a redelivery
that was a correct no-op beforehand. That made the dedup guarantee
survive only until the first /compress, and violated
messaging-and-work-intake.md:88-90 and 112-114.
CompressHistory now reports which input messages it protected and the
write-back carries those originals through untouched, so only the
summary is a new record. The summary is attributed to the bot rather
than falling through to "user": CompressHistory emits it with role
"system", which has no representation in the store, so the model was
replaying "[Earlier conversation has been summarised...]" as if the
human had typed it.
DISPATCH. Three ways to rewrite a history the operator did not ask to
rewrite, or to fail to rewrite one they did:
- Bare /compress took the preview branch, and the preview closes with
"Run /compress to apply" -- the documented way to compress could never
compress, and the failure-safe path was unreachable.
- /compress focus <topic> discarded the topic and ran a full default
compression. Nothing implements focused summarisation; it now says so
instead of doing something else irreversibly.
- /compress here (no count) and any typo fell through to a full
compression. Both now print usage.
compressPreview also read a fixed 200-message window while reporting the
real count, so the two numbers in one sentence described different
conversations and it advised against compressions that were needed.
Refs archie-core-cz8, archie-core-8k8, archie-core-le6
d615de5 made an unusable memory directory fatal. That was the wrong
call and contradicts the forge and container paths: memory is one
capability among many, and refusing to start over a path denies the
operator chat, the dashboard and everything else -- then crash-loops
under Restart=on-failure with the real error scrolling past unread.
builtin.New now reports an unusable directory through IsAvailable and
Err rather than failing, so the caller decides. The daemon warns and
falls back to the location an unset work_dir would have produced, which
is where someone who copied a config from another host will look. If
that is unusable too it says what the operator loses -- no recollection
between conversations, and failing writes -- and carries on.
The provider stays readable while degraded, so a bad path reads as an
empty memory rather than breaking mid-conversation, and the dashboard's
memory page already renders IsAvailable so this is visible there.
Also fixes a defect the fallback test caught: an empty work_dir made
filepath.Join produce the relative path "memory", which MkdirAll
creates wherever the daemon was started from -- succeeding, and putting
memory somewhere nobody would look.
Refs archie-core-rml
Both stores treat a missing file as an empty document, so a memory
directory that does not exist looked exactly like a memory with nothing
in it yet. archied logged "memory manager started" and ran with no
memory at all; the failure would have surfaced at the agent's first
write, as a tool error mid-conversation, long after startup said it was
fine.
Found live: a config copied from carina kept work_dir=/var/lib/archie
/work, a container path with no counterpart on the host.
New now establishes the directory and reports a path it cannot use, so
the existing error path exits at startup where an operator can see it.
Refs archie-core-rml
The old UI was a single 200-line Go file serving one hand-written HTML
page of task rows. It showed that archied was running and almost nothing
about what it was doing -- skills, workflows, memory, channels, logs and
configuration were all invisible unless you read the source or the
config file.
The dashboard now covers each of those as its own section, built as a
Vite app under ui/ at the repo root: it is a separate artefact from the
Go daemon, not an internal package of it. dist/ is committed so building
archied never needs a Node toolchain, and the !no_ui build tag keeps an
embed-free build available.
Both sides are split by concern rather than by layer -- one Go file per
API area, one folder per UI section with its own CSS -- so a change to
logs cannot disturb tasks.
Pages report consequences, not just state: an empty memory page says
Archie starts every conversation with no recollection of earlier ones,
and the setup checklist names what is missing in plain language instead
of showing a grid of zeroes. Nothing greets by a hardcoded name; the
operator comes from [chat], which is deployment data.
Auth is exposure control, not capability control -- the agent already
holds this user's authority through its own tools. So a loopback bind
needs no token, and only a reachable bind mints one and logs a URL,
which means an instance cannot be exposed merely by omitting config.
Container startup now degrades instead of aborting, for the reason
resolveForge already does: a missing agent image should not deny the
operator chat and the dashboard, and under Restart=on-failure it turns a
recoverable problem into a crash loop with the real error scrolling past.
`task dev` runs the daemon under air and the Vite server together in one
terminal.
Under systemd, journald held the only copy of archied's output, and
running it by hand left no record at all -- so "where are the logs?" had
no good answer, and the dashboard had no history to show from before it
connected. [log] adds a file destination alongside stderr, with
size-based rotation and retention done in-package rather than pulling in
a dependency for a few hundred lines.
A file that cannot be opened is reported and the daemon continues on
stderr: losing the durable copy is not worth refusing to start over.
reader.go owns the on-disk format so nothing else has to parse it, and
bounds every read -- tailing keeps the newest entries within a fixed
scan window, so pointing it at a large file cannot exhaust memory.
go-telegram/bot retries a 429 immediately and only then grows its own
backoff, so a rate-limited daemon kept hammering getUpdates and stayed
limited. The pipeline error handler now reads Telegram's own RetryAfter
and waits it out, capped at a minute so a hostile value cannot park the
loop indefinitely, and cancellable so shutdown is not held up.
Three defects shared one root cause -- messages had no identity of their
own, so the store could not tell a redelivery from a new message:
- SaveMessages destroyed history. Writing a batch replaced records that
a concurrent write had already stored, and earlier messages vanished.
- A redelivered channel message overwrote the stored one, contradicting
the append-only sequence in docs/architecture/messaging-and-work-intake
.md:112-114.
- /compress stranded whatever exceeded one page: deleting 1200 reported
1000 deleted and left 200 behind.
Messages now carry an application-generated MessageID, derived from
(session, source id) so a redelivery lands on the same record, and
stored records are immutable -- a repeat write is a no-op rather than an
overwrite. SourceID keeps the channel-native id for correlation without
being load-bearing. _ts is written as Unix milliseconds and clamped
monotonic per session: Telegram dates are whole seconds, so replies
arriving inside the same second would otherwise order arbitrarily.
Deletes page with a cursor instead of assuming one page holds everything.
Adds a SQLite session store behind the same interface, per
docs/architecture/messaging-and-work-intake.md:107. A shared conformance
suite runs all 19 groups against both implementations, so the two cannot
drift while the NellDB path is still the one wired up.
Task carried no created/updated times, so the dashboard had nothing to
sort or age a queue by. Both columns already existed in the schema and
are now scanned through; SQLite returns them as strings in several
shapes, so sqliteTime does the parsing in one place rather than at each
of the five call sites.
WorkflowStat, StageStat and DayTokens had no JSON tags at all, so
/api/summary answered {"Day":...,"Tokens":...} while the dashboard read
d.tokens -- every sparkline would have plotted zero.
The rg package carried three platform binaries (14MB) inside the Go
binary and extracted the matching one to a temp file on every single
run, so a long-lived daemon left a trail of copies behind and paid the
write on each grep. Nothing depended on ripgrep's own output format.
grep now uses the Go implementation unconditionally.
- Add Message.At timestamp as the ordering key, stamped at save when zero
- Store each session's messages in its own collection with time-ordered IDs
- Fix bulk saves overwriting history and sequence reuse after deletes
- Walk past NellDB's internal scan limit for history and deletes
- Add paged SearchMessages (MessageQuery/MessagePage) with truncation reporting
- Drop a session's message collection when the session is deleted
SaveConfig's hermesHome parameter and HERMES_HOME references in comments
were copied from another project. The interface and its callers are
entirely internal to archie-core (no external call sites exist outside
tests), so renaming them is safe.
hermesHome -> dataHome
HERMES_HOME -> data directory
/tmp/hermes -> /tmp/archie-test
Test fixtures used 'sam', 'samcharles93', and 'sam/<repo>' as owner
names. These are personal and machine-specific — the repo should use
generic placeholders like 'acme' (matching the existing convention in
worktree_test.go).
config.example.toml: samcharles93 -> your-github-username
Test owner: sam -> acme
Repo refs: sam/archie-core -> acme/archie-core, etc.
Example skills: sam -> acme
After the daemon was down ~9 hours it booted and answered every message
sent while it was gone -- 8 stale messages, 8 LLM turns, one burst.
Telegram holds undelivered updates for 24h and replays them on the first
getUpdates. launch()'s webhook branch already passes DropPendingUpdates;
the long-polling fallback had no equivalent, and polling is what this
deployment uses. deleteWebhook carries the flag even when no webhook is
registered -- the same call python-telegram-bot makes when it starts
polling -- and it doubles as a guard against a stale webhook, which
would otherwise fail getUpdates with 409.
Bounded by a 10s deadline so an unreachable Telegram cannot hold up
gateway startup.
These asserted on file contents rather than what the code does:
Dockerfile strings, deploy.yml YAML, CHANGELOG headings, and greps of
main.go for identifiers. Two also referenced config.docker.toml and
docker-compose.yml, which were never committed, so they could not pass
at all.
The worst compared strings.Index byte offsets in main.go to assert
startup ordering -- it would pass on code that never runs and fail on
a correct refactor that moved a line.
WriteTaskJSON wrote task.json to the worktree root -- the same worktree
the agent commits from. CommitAll stages with go-git's All option, and
go-git's Add does not honour .gitignore or .git/info/exclude, so the
brief was swept into the agent's commit and pushed onto every task
branch. That is how a task.json for issue #57 ended up committed in
the repo root.
This is the identical failure the prepared sentinel hit; worktree.go
already documents the fix. Nothing under .git can ever be tracked, so
put the brief there rather than papering over it with an exclude.
The revert in ed61ce3 removed handleSensors but left the route
registration pointing at it, so cmd/archied did not compile. The
sensors package itself was left behind fully orphaned -- nothing in
the repo referenced it. There is no sensor monitoring in this app.
Groundwork for archied setup owning config generation (archie-core-ewk),
so install.sh stops emitting a second copy of the config that drifts from
the example operators actually read.
configtemplate lives at the module root because go:embed cannot reach
outside its own directory and config.example.toml is kept at the root
where it is easy to hand-edit. tomlwrite applies setup answers to that
template in place, preserving the comments that make the generated file
readable - BurntSushi/toml round-trips values but not comments, so
re-encoding a decoded document would strip them.
The nestif extraction in 712388d pulled --provider handling out of
parseModelRest into a helper that took modelParts by pointer and
appended every surviving field to it. The caller's own loop appended
the same fields again, so every model name was doubled: /model gpt-5.6
asked the router for "gpt-5.6 gpt-5.6" and SetActiveModel rejected it
as unknown. The index loop becoming a range loop also stopped the
space-separated "--provider openai" value being consumed with its flag,
so it landed in the name too. Direct model switching over Telegram was
broken for everything but --refresh and provider-only switches.
splitProviderFlag is now the sole accumulator and returns the surviving
fields, so the shared-slice shape that allowed the double append cannot
recur (archie-core-0d6).
Found while auditing the remaining hunks of 6108fc5 (archie-core-ifi):
the naked return in the same function could not be regression-tested
until the function produced correct values. That audit is complete and
the other seven hunks are behaviour-neutral. Notably shell.go's
errorlint rewrite is not a repeat of the grep failure - it had no
companion exit-code condition to drop, and the ctx.Err() timeout check
already runs first - and find.go's errors.Is rewrite is safe because
errors.Is(err, nil) is false for any non-nil err.
Tests cover the return order of parseModelRest (two strings and three
bools, so a transposed pair compiles silently), the field count of the
model name, and shell's exit-code branch, which had no coverage at all.
The find fallback's habit of reporting a cancelled walk as "no matches
found" is filed as archie-core-ts9.
An errorlint autofix rewrote the ExitError check to match any exit
code, so a search that never ran (bad pattern, unreadable path) was
reported as "no matches found". Keep errors.As, restore the exit-code
check, and add a regression test.
The communication rules were entirely prohibitions, with nothing
licensing warmth. On a social turn there is no answer to lead with, so
"lead with the answer, keep it short" collapsed into a demand that the
user justify getting in touch: "are you there?" drew "I'm here. What do
you need?"
/stop cancelled the chat turn but could not touch a task the daemon was
executing, and /cancel refused outright:
case statusRunning:
return fmt.Errorf("task is actively running; cannot cancel
until it reaches a waiting state")
So the one case worth interrupting was the one case neither command
would touch.
The daemon now holds a cancel function for every executing task,
registered in process() -- the single point every dispatch path reaches
-- so a task is stoppable for its whole life, including the slow clone,
worktree prepare and image pull that is exactly when someone realises
they asked for the wrong thing.
- /cancel <id> interrupts the work first, then records the terminal
state. That order matters: writing the state while the task still runs
invites it to write its own afterwards and win. A task the store calls
running that nothing is executing (crashed daemon) still gets its state
recorded, which is what unsticks it.
- bare /stop now stops the reply, the queue behind it, and every running
task for the identity, reporting which of those it actually did.
Nobody reaching for the brake should have to look up a task ID first.
- StopRunning deliberately writes no terminal state: a stopped task
unwinds to parked, which is resumable. Forcing rejected would discard
work worth keeping.
- Without a runtime wired, cancelling a running task is still refused --
recording it as cancelled while it carries on would be a lie.
Container teardown detaches from the task context. Release runs on the
way out, and the main reason a task is on its way out is cancellation --
at which point the graceful ContainerStop failed instantly and the
container was left to the forced remove. Cleanup gets its own deadline.
process() gained two statements and crossed the funlen limit, so the
container setup block is extracted rather than suppressed.
Add internal/tools/command: an always-on floor under the shell tool,
enforced in the provider adapter so the lifted tau files stay diffable.
This is not a security boundary and does not pretend to be one. Anything
with a shell has countless ways past a rule list. What it buys is that
the failures with no recovery -- where you cannot intervene afterwards
because the machine, the filesystem, or the gateway itself is gone --
are not reachable by an ordinary mistake.
Rules: recursive delete of / and system directories, mkfs, raw block
device writes, fork bombs, kill -1, shutdown/reboot/init/systemctl
power, and sudo -S with no SUDO_PASSWORD configured. Two more are
archie's own: an agent must not stop the daemon that hosts /stop
(pkill/systemctl/docker), nor start a second one outside the supervisor.
The parsing is the actual work. Patterns are anchored to command
position, so `git commit -m "revert the rm -rf / change"` and
`echo "rm -rf /"` are ordinary commands, while `echo x; rm -rf /` and
`$(rm -rf /)` are not. Quoting, separators, ${VAR} braces, environment
assignments and privilege wrappers are all parsed rather than matched.
Probing the first version found two bypasses that made every rule
optional, both of which a model writes unprompted rather than only an
attacker: `bash -c "rm -rf /"` and `xargs rm -rf /` hide the command in
an argument. Segments are now followed into shell -c payloads, eval, and
command wrappers (xargs, timeout, nice, env, nohup, ...), bounded by a
nesting limit. Tests cover both directions -- the refusals and, at equal
length, the ordinary commands that must not trip them.
shell.go relied on exec.CommandContext's default cancellation, which
kills only the process it started. A shell's real work is a child of
that shell, so cancelling `go test ./...` reaped the shell and left the
test binary running, and `nohup x &` was never touched at all.
That made /stop a lie for the case it exists to cover: the turn
unwound, the user was told it stopped, and the command carried on.
Worse than expected, and caught by writing the test first: without a
process group the tool does not merely fail to kill the command, it
hangs. The backgrounded grandchild inherits stdout, so cmd.Wait blocks
until the shell timeout regardless of cancellation. Verified by
reverting the fix -- the new test fails on a 30s hang, not on the
survival assertion.
Run the command as its own process group, signal the group on
cancellation, and bound Wait with WaitDelay so an inherited pipe cannot
hold the turn open. setProcessGroup/signalProcessGroup were already
present in the lifted set, used by tau's agent.go but not its shell
tool; this extends them to the shell and clears the unused-code lint
that was flagging them.
Recorded as a mutation in shell.go's provenance header.
/stop could not reach a running turn, and the reason was worse than a
missing cancel. go-telegram/bot runs one update worker that calls
handlers synchronously (defaultWorkers = 1, never overridden), and the
chat turn ran on it. While a turn streamed -- or sat in a shell tool --
the worker was blocked and /stop sat unread in the update channel until
the turn it was meant to kill had already finished.
Add gateway.Turns: a per-session serial lane that turns are submitted to
and that the event loop never waits on. The worker is free again in
microseconds, so /stop is serviced immediately; ordering comes from the
lane being serial rather than from the loop being blocked.
- Bare /stop cancels the running turn and clears the backlog behind it,
with no approval step. Approval guards destructive commands, and
gating the brake behind a confirmation defeats it. /stop <name> keeps
the existing process-termination behaviour and its approval.
- Cancellation propagates through the turn context, so it reaches the
model stream and any tool underneath -- a shell command built with
exec.CommandContext dies with the turn.
- Queues are unbounded and never shed. A dropped message is a silent
failure that surfaces later as an agent that ignored something.
- Turns are recovered per-lane: the channel's panic middleware wraps the
event-loop goroutine, which no longer runs the turn.
Also raise the chat step budget. It was hardcoded at 8 -- roughly one
read, one grep and two edits -- so turns hit the cap and stopped
mid-task with no indication they had been cut off. It is now
chat.max_steps, defaulting to 100. Interruption is /stop's job.
The chat agent had two tools -- memory_edit and skill_activate -- so it
could not read a file, search a tree or run a command. ai-sdk's runtime
already drives a tool loop for it (MaxSteps 8, toolExecute wired as the
executor), so the loop was never the missing piece: the registry was empty
of anything useful.
Lifted from tau internal/agent/tools at commit f5289ea, per the recorded
copy-and-mutate strategy: every file carries a provenance header naming its
tau source path, the commit, and the mutations made, so refreshing from
upstream is a diff rather than archaeology.
internal/tools/builtin/ the lifted tools, ~3.1k lines
internal/tools/provider/builtin/ the adapter to tools.ToolEntry
Six tools: read, write, edit, shell, grep, find. Tau's own tests came with
them and pass unmodified, which is the evidence that the lift is faithful.
Deliberately not lifted:
- agent.go (1214 lines): subagent spawning, and the only real coupling in
the package -- 10 tau packages including chat, sessions, store and
registry. Nothing the chat agent needs to do work.
- skill.go: depends on tau's skills package; archie has internal/skill and
already exposes skill_activate.
- docs.go: serves tau's own embedded documentation via tau/docs.
Not lifting the coordinator either. It is tau's agent loop (6.4k lines over
ten packages) and archie already has one in the ai-sdk runtime; porting it
would leave two loops competing. Its cancellation and tool events are worth
having, but they are a few hundred lines built against the existing path
rather than six thousand lifted onto a second one.
The adapter bridges two shape differences: archie hands handlers decoded
arguments where tau's executor takes raw JSON, and tau reports tool-level
failure in Result.IsError rather than as an error -- surfaced as a real
error so the runtime and the guardrail engine both see it. Tools are
classified idempotent or mutating for guardrails and budgets; that is
categorisation, not a jail.
chat.workspace roots the tools and defaults to empty, which registers none
of them. They read, write and execute, so the directory has to be a
deliberate choice rather than whatever the daemon started in -- in the
container that is /.
Verified: go build, go vet, gofmt clean; full suite passes.
Three defects found from a real Telegram transcript.
1. The operator's name was compiled into the prompt.
internal/gateway/persona.go and prompt.go both hardcoded "Sam's" into the
default persona and the fallback prompt. The persona renders first into
every system prompt, so a personal name was sent to the model provider on
every turn, and any other deployment got an assistant that believed it
worked for someone else. There was nowhere to put it: Repo.Owner is a repo
owner and config.Config had no operator concept.
ChatConfig.Operator now carries it, rendered in the prompt's <env> block as
runtime metadata and omitted entirely when unset. config.example.toml
documents that setting it sends the name to the model provider.
2. /new claimed to clear history that it had not cleared.
The chat responder keyed history by channel id through a local sessionKey
helper, while the session commands operate on tracked session ids.
sessionTracker.resolve mints deterministic ids so the two agree -- until
/new, /branch or /resume assigns a generated id, after which they address
different histories permanently. /new reported "Conversation history has
been cleared" while the next turn still saw everything, and /undo,
/compress, /resume and /sessions acted on a namespace the conversation
never read.
gateway.Router.ResolveSessionKey already existed for this, and
session_commands.go:104 said outright that main.go should call it instead of
its inline helper. It never got wired. The responder now resolves through
the router and the dead helper is deleted so it cannot come back.
buildTelegramRouter constructs the router before the responder so the
dependency is visible rather than captured by reference.
3. Prompt rules for two behaviours the transcript showed.
The agent offered to accept shell access it has no tool to use, which is
both unhonourable and a request for the user's secrets. It also opened
mid-conversation replies with a greeting, and described its own manner
("no fluff") in stock phrasing. Added core rule 7 and three communication
rules covering greetings, self-description and register.
Note the memory claim in that transcript was NOT a fabrication: the
memory_edit tool's own description names MEMORY.md and USER.md, and tool
descriptions are part of the prompt.
Also added chat-turn logging (session id, channel, thread, history depth).
Chat turns were entirely unlogged, so a report of lost context had no
evidence to check: 76 log lines covered two days and none of them was a
conversation. A separate report of mid-conversation amnesia remains
undiagnosed -- single process, 43h uptime, compression untriggered at three
messages -- and this is what makes it diagnosable next time.
Regression tests: prompt renders/omits the operator and carries no personal
name; the responder resolves via ResolveSessionKey and defines no local
session key helper.
Verified: go build, go vet, gofmt clean; full suite passes.
dependencies-and-contracts.md rule 1 says domains must not import
internal/infrastructure. internal/daemon and internal/agentexec both did,
and for exactly the thing the doc carves out: "internal/eventbus is an
approved shared application contract ... it MUST remain broker-neutral."
The Publisher/Consumer/Requester interfaces existed but lived inside the
NATS package, so a caller could depend on the behaviour yet still had to
import the implementation to name it. They now live in internal/eventbus,
and nats.Client asserts against eventbus.Bus.
The larger violation was ownership of meaning. The doc says "message schemas
stay with their owning domains; the event bus transports messages, it does
not own their meaning." The bus exported TaskEnvelope and a PublishTask
method, so the transport knew what a unit of work was, and it exported the
archie.agent.* subject helpers, so it also owned the agent protocol.
- TaskEnvelope, its routing Kind, the label vocabulary and the task
subjects move to internal/domain/workintake, which encodes and decodes
its own bytes. This starts internal/domain/ per organisation.md.
- The agent request/response/system subjects move to internal/agentexec,
which defines what those messages mean.
- internal/workflow keeps only the kind-to-registry mapping; the label
table stays single and lives with the domain that reads forge issues.
- The bus now carries opaque payloads on plain-string subjects.
Consumers declare the smallest interface they need rather than taking the
whole Bus: daemon.TaskBus is publish-unique/fetch/request, agentexec.
RequestBus is publish-request/reply-inbox, and archie-agent's stageBus is
fetch/respond. None can reach what it does not use.
Two defects this surfaced:
- archie-agent declared its own JetStream stream with a second copy of the
name, subjects, retention, dedup window, MaxDeliver and TTLs that
nats.Connect already sets -- two definitions of one stream, free to
diverge. Config now takes Subjects and FilterSubject from composition,
which is what let the agent use the shared client and delete its
hand-rolled setup.
- Replying to a request needs core NATS, not the JetStream publish path:
a reply inbox is ephemeral and belongs to no stream, so a durable
publish to it fails. The old code hid this by using the raw connection.
The contract now distinguishes Respond from Publish. The agentexec
round-trip test caught it after I had made the same mistake in
archie-agent.
Also translated the SDK's ErrNoResponders into eventbus.ErrNoResponders, so
the daemon's taskrun retry no longer imports the NATS SDK to name a
transient condition. The SDK is now confined to the nats package, the *rpc
packages (themselves NATS infrastructure), and cmd/*.
The agentexec test fake previously hand-rolled a JetStream consumer; it now
drains the client's own consumer, which is both closer to production and
avoids conflicting consumers on a work-queue stream.
Verified: go build, go vet, gofmt clean; full test suite passes.
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.