6d5fdd72a35fc245f107eba2fd3f7dca3dd1f2e5
100
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
479ed95a91 |
fix(config): close review blocker on the PATCH path; deep-copy snapshots; atomics for shared state
Second adversarial pass findings, fixed:
BLOCKER -- PATCH silently dropped every dotted key. The UI sends
dotted keys ('budgets.max_steps') but ApplyOverlayValues fed them
straight to yaml.Unmarshal, which cannot decode a dotted key as a
struct field and silently ignored it: 200 OK, zero effect, and the row
still persisted (poisoning later reloads with an unvalidated value).
The reload path worked only because overlay.Snapshot nests first. Fix:
applyDottedOverlay nests dotted keys via overlay.Nest before decode --
the same nesting Snapshot performs -- and is pinned by
TestApplyDottedOverlayNestsBeforeDecode, which fails against the old
behaviour.
MAJOR -- shallow copies let overlay decode mutate the published
snapshot. Holder.Get and *doc are shallow; yaml decodes maps in place,
so a crafted nested update (or a failed boot overlay apply) mutated
shared maps of the published config before validation. Fix: config.Clone
deep-copies every reference field (Models, Providers, Repos, Identities,
Dispatch.Labels, Agent.Env, Chat/Telegram slices, Tools.MCPServers,
Memory.ProviderConfig, WebFetch.Enabled pointer, Extra), used by the
PATCH path (next := d.Cfg.Get().Clone()) and by Loader.ApplyOverlay,
which now never mutates its input (clones Config and the provenance
chain internally), so boot and reload pass the base document directly
and a failed apply leaves it exactly as it was. Pinned by
TestConfigCloneDeepCopiesReferenceFields.
MAJOR -- data races on captured main.go variables. bootOverlayErr and
currentProvenance were plain values written by the SIGHUP goroutine and
the PATCH/Reset handlers and read by every GET /api/config; -race passed
only because no test exercised the composition root concurrently. Both
are now atomic.Pointer; the LastReload closure and the provenance
dedup read them atomically.
MINOR -- MaxConcurrency removed from the reloadable allowlist. The
dispatchers re-read it but the startup-built container pool captures it
(container/pool.go:94,163), so 'every consumer re-reads it' is false and
a change only partially applies. It now warns requires-restart; the
criterion comment on reloadableFields documents the pool capture.
MINOR -- ResetConfig now resolves and validates the target state BEFORE
deleting the row, so a broken file cannot leave the store and the
running config disagreeing; the provenance chain no longer grows
unboundedly (the runtime-overlay origin replaces, not appends).
Also: holder.go no longer references a file watcher that does not exist.
Verified: task check clean; -race clean on cmd/archied, webui, daemon,
config; new findings from the second adversarial pass are closed.
|
||
|
|
171e1b2686 |
feat(config): surface overlay state, shadowed keys, and per-row reset
Three gaps closed, all in the 'your change didn't take effect and nothing told you' family: 1. MaxRetries joins the reloadable allowlist, and the criterion is fixed on reloadableFields: a field is reloadable when EVERY consumer re-reads it. MaxRetries is the worked example -- its only consumer is the webui maxRetriesFor handler, which re-reads per request (api_tasks.go:380,383); nothing in the daemon reads it, so warning 'requires restart' was spurious. Chat.Telegram.TokenEnv is documented as the counter-example (webui reads it per request but a startup-built telegram bot consumes it, so it is not reloadable). Pinned by TestChangedNonReloadableFields alongside the comment. 2. Boot-time overlay degradation is now surfaced. config.ReloadStatus gains OverlayUnavailable; main.go records the reason when the overlay store cannot be opened or its values fail validation, and /api/config carries it (merged into LastReload). Cleared by a successful dashboard write or reset. The settings page renders a warning banner, so a daemon running on file config alone says so where the operator is looking, not only in logs. 3. Overlay-shadowed file edits are visible and recoverable. ConfigView.Overridden lists the dotted keys the runtime overlay currently sets, so the UI marks those rows (their file value is shadowed until reset). POST /api/config/reset exposes the store's Delete as a per-row reset: it deletes the row and republishes file + remaining overlay, which is also the answer to 'my file edit isn't taking effect'. The dashboard can now remove every override it can create. Verified: task check clean; -race clean on cmd/archied, webui, infrastructure/configuration; new handler tests cover the reset 200/400/503 paths and the overridden list. |
||
|
|
da2d93a830 |
feat(config): runtime config overlay store and PATCH /api/config
The second half of #348's storage layer: dashboard-edited overrides live in their own SQLite file, separate from the task and conversation stores so each file owns its user_version and migrator with no contention (configDBPath -> cfg.DBPath + "-config.sqlite", matching the taskDBPath / conversationDBPath convention). Store (internal/infrastructure/configuration/overlay): - config_overlay(key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at, updated_by), own migration, WAL. - Set refuses DeniedKeys (db_path, work_dir) at write time as well as at the API layer; the map is exported so the dashboard can show the reason instead of silently omitting the edit affordance. - Snapshot JSON-decodes each value and nests dotted keys ("budgets.max_steps" -> map[b][m]) ready to decode into Config. Loader (ApplyOverlay / ApplyOverlayValues): - Decodes a nested overlay map with the same field-level precedence as a file overlay, records the runtime-overlay origin, then applies defaults and validates. Used at boot, on SIGHUP reload (ReloadController gained an optional WithOverlay source) and by the PATCH path. Boot and reload: - A broken overlay (unopenable store, unreadable snapshot, values that fail validation) degrades to file config alone -- it must never brick the daemon. --no-config-overlay / ARCHIE_SKIP_CONFIG_OVERLAY=1 skips the store entirely; the flag is now a real gate, not a log-only stub. PATCH /api/config (webui): - handleConfigUpdate decodes {"updates": {dotted.key: value}}, calls the composition-wired UpdateConfig seam, and classifies errors via webui sentinels: ErrConfigUpdateInvalid -> 400 (denylisted key, failed validation, unparseable value), ErrConfigUpdateUnavailable -> 503 (overlay skipped by recovery flag), anything else -> 500. - The seam (main.go) applies updates to a COPY of the published config, validates the materialised result, persists to the overlay, then publishes through the same path as reload -- it never calls Set directly from the handler, since web.Cfg is the daemon's own Holder. - ConfigView gains Locked (dotted key -> reason) so the UI disables denylisted rows explicitly. Verified: task check clean; new tests cover the store round-trip, denied keys, loader overlay layering/validation/provenance, reload with and without overlay, and the PATCH handler's 200/400/503 paths. |
||
|
|
31fdbddd61 |
fix(config): complete the reloadable allowlist and pin it against ForTask
The allowlist drifted before the chunk shipped. ForTask (config.go:457-465) is the authoritative per-dispatch snapshot and carries Models, Budgets, Dispatch, DiffCapLines, Notify and Forge.Host -- I allowlisted only three. And the poll path reads cfg.Label and cfg.BotUser live per cycle (daemon.go:359,390 and :368,381) off the same per-poll config as Dispatch.Trigger. Five fields would have reported 'requires a restart' while actually taking effect immediately: the safe direction, but exactly the warning-fatigue failure that kills the feature (an operator who is told to restart for a label change that already applied learns the warning is noise). The fix is enforcement, not a bigger list: TestReloadableFieldsCoverForTaskSnapshot reflects over TaskConfig and fails if any field ForTask carries is not in the allowlist (Forge maps to the Forge.Host sub-field entry). A field added to ForTask later now fails the test instead of silently producing a wrong warning. Label and BotUser are not carried by ForTask -- they come off the poll path -- so they are allowlisted by hand with a comment, and the same test pins them explicitly. Also documents on webui.Server.Cfg that in production it is the daemon's OWN Holder (web.Cfg = d.Cfg), so Set publishes to the running daemon: a config-mutating handler must apply to a copy, validate the materialised config, persist, then Set -- never Set directly. task check clean. |
||
|
|
d8d4c93239 |
fix(config): share one config Holder between daemon and dashboard; re-apply model catalog on reload
Adversarial review findings (fresh reviewer, no memory of the code): 1. (major) web.Cfg was a second Holder the reload never swapped, so /api/config showed boot-time values forever after the first reload while the daemon ran the new config -- the exact 'code means something different from what it says' failure. web and d now share one Holder (web.Cfg = d.Cfg after construction), so a reload swaps both views atomically. 2. (minor) the model catalog merge ran once at boot; publishing the raw reloaded document dropped catalog-discovered providers from the running config even though the file was unchanged. The apply closure re-runs applyModelCatalog on the reloaded document before publishing (idempotent; a catalog that failed to load merges to identity). 3. (minor) changedNonReloadableFields parameter 'new' shadowed the predeclared identifier (predeclared lint finding). Renamed to 'next'; the finding is gone from the branch diff. Also: tightened --no-config-overlay help text to state the file -config-overlay still applies (it gates the future DB overlay only), and documented that the controller's apply callback must be non-nil. task check clean; -race clean on cmd/archied and internal/daemon. |
||
|
|
f544dd0978 |
feat(config): SIGHUP-triggered reload with requires-restart warnings
The daemon can now re-read its configuration on SIGHUP (or on a future in-process trigger) and republish it through the Holder, closing the first half of issue #348: 'config can change at runtime, safely, and can't brick the daemon.' Reload path: - cmd/archied/reload.go: ReloadController re-runs loader.Resolve on the same paths main.go passed at startup (Resolve is pure -- no reload state added to the loader). apply is called only with a Document that passed validation; a failed reload records the error and its timestamp and leaves the running config untouched. That Set-not-called-on-error property is the safety core and is pinned by TestReloadValidationFailureDoesNotApply. - SIGHUP listener in main.go runs reloadLoop(ctx, ch, controller, log); the loop is extracted as a testable seam (syscall.SIGHUP is Unix-only, fine given the Linux target). PollInterval is genuinely reloadable now, not just re-read: the three ticker sites (Run, per-identity goroutine, shared maintenance loop) re-read the interval each tick and Reset the ticker on change. A reloaded poll_interval takes effect on the next cycle. Diff-and-warn so an operator never has to read the source to know whether an edit took effect: changedNonReloadableFields compares the old and new snapshots against an allowlist of re-read fields (PollInterval, Repos, DiffCapLines, Budgets, Dispatch, and the Containers sub-fields VolumeTTL + MaxConcurrency). Anything else that changed logs Warn 'requires a restart'; a fully-applied reload logs Info. The allowlist is deliberate: a field added to Config later defaults to requires-restart, the safe direction. NATS split-brain closed: containerEnv now hands containers the endpoint the daemon's own client connected with at startup (Daemon.ConnectedNATS, captured at construction) instead of the live config, so a reloaded nats.url cannot point new containers at a server the daemon is not publishing on. A nats change is therefore classified requires-restart, and CLAUDE.md's 'hands its own nats.url verbatim' note is updated to the meaning it now has (same today, deliberately different after a reload). Validation guard: poll_interval <= 0 is rejected in validate.go beside the VolumeTTL guard. applyDefaults fills zero with 60s, so this fires on an explicit negative -- which would panic time.NewTicker/Reset at boot and, after the per-iteration reset, on a SIGHUP mid-run. Observability: config.ReloadStatus (last_error, last_error_at, last_reload_at) is recorded by the controller and surfaced in /api/config via Server.LastReload, so a stale running config is visible in the dashboard, not just the logs. Rendering waits for the UI step. Recovery hatch: --no-config-overlay flag plus ARCHIE_SKIP_CONFIG_OVERLAY=1 (configuration.SkipOverlay), logged at startup. No overlay source exists yet; the flag is the documented escape hatch the DB overlay (step 3 of #348) will consult. webui.Server.ConfigProvenance becomes atomic.Pointer so a reload can swap it via SetProvenance independently of Cfg; the accepted skew (new config alongside old provenance) is documented on the field. Verified: task check clean; -race on daemon, webui, cmd/archied, config, infrastructure/configuration. |
||
|
|
b6f0aea930 |
refactor(daemon,webui): make Daemon.Cfg and webui.Server.Cfg reload-safe
Daemon.Cfg, webui.Server.Cfg, and telegramSetup.Cfg were all held by value (or as a raw shared pointer in webui's case), so a future reload path could not swap the running configuration -- the consumers held frozen snapshots made at construction. This is the prerequisite for issue #348. Add config.Holder, a small RWMutex-backed snapshot holder: - Get returns a value copy under RLock; the copy shares its reference-type fields with the published snapshot, so a doc comment pins the immutability invariant (a published Config is immutable; reload constructs a fresh one). - Set replaces the snapshot under WLock. - Get is nil-safe; Set is not. Convert every consumer to read through the accessor. The convention 'cfg := h.Get() once per logical operation' is documented on the type so the next reader knows that inline d.Cfg.Get().Foo is a code smell (a Set could land between two consecutive Gets). Special cases: - webui.Server.Cfg: was *config.Config, a raw shared pointer read from handler goroutines. Convert to *config.Holder. The pre-existing 'cfg := s.Cfg' aliasing bug at api_config.go:295 (which was *trying* to copy but only copied the pointer) now becomes 'cfg := s.Cfg.Get()', which is the value copy the read-only view always wanted. - daemon_test.go: one test mutated d.Cfg.DiffCapLines in place, which the Holder forbids. Replace with the documented read-modify-write pattern (prev := d.Cfg.Get(); prev.X = Y; d.Cfg.Set(prev)). - telegramSetup.Cfg: matches the daemon's API for consistency even though setup runs before the daemon is alive. TaskContext.Cfg in internal/domain/workflow/workflow.go is deliberately NOT converted -- a task that starts under one config should finish under it, and a config changing between TDD and gate stages is a bug, not a feature. Snapshotted at dispatch, as before. Verified: go test ./... (61 packages), go vet, -race on internal/daemon and internal/config. |
||
|
|
61b4b7b0cf |
refactor(store): replace legacy persistence with SQLite
Task and event persistence now uses a dedicated SQLite sidecar derived from the configured state prefix, matching the independently persisted conversation store. The configured path now means a state-path prefix rather than a database file so fresh SQLite state never attempts to interpret the previous storage format. Remove the retired implementation and dependency completely, strengthen SQLite migrations and concurrency behavior, restore backend-neutral coverage, and align configuration, operational guidance, UI labels, and deployment documentation with the new storage and host-daemon topology. |
||
|
|
3afbab8201 | refactor(gateway): persist conversations in sqlite | ||
|
|
e4385ef266 |
feat(webui,gateway): add /api/tasks/{id}/logs endpoint and task_logs chat tool
Adds two read surfaces for per-task persisted log history so an operator
can answer "why did task N park?" without needing to watch docker ps in
real time — the deployment model documented in CLAUDE.md.
/api/tasks/{id}/logs — built on logging.Tail the same way /api/logs
already is, defaults attempt to the tasks current Attempt from the store.
task_logs chat tool — lets Archie read task logs from Telegram or webui
chat. Identity enforcement matches chatTaskListerAdapter: a model bound
to one identity cannot read another identitys logs, and forge tasks
(empty identity) are denied.
internal/logging: add TaskRegistry.Path() for read-side access without
threading baseDir separately through every caller.
Fixes from adversarial review: strict identity check (no empty-identity
bypass), non-null Entries when disabled, component doc accuracy, and
adapter tests covering the security boundary.
Ref: #455
|
||
|
|
951ddbc9f4 |
feat(daemon): consume agent system logs into per-task sinks and the dashboard feed
Closes the loop #451-#453 opened. archie-agent (#453) now publishes its own logs to agentexec.SubjectForSystem(taskID) over NATS, and a task log sink (#452) exists to persist them, but nothing on the daemon side subscribed, demuxed, or wrote anything -- the messages had nowhere to land. - agentexec: SubjectSystemWildcard + TaskIDFromSystemSubject, the inverse of SubjectForSystem, for a daemon subscribing to every task's system subject with one wildcard subscription. - logging: TaskRegistry manages one open TaskSink per running task attempt, mirroring every write onto the live dashboard Feed the same way a locally-written log would appear. Nil-receiver-safe, matching every other optional composition-wired Daemon field. - daemon: Daemon.process opens a task's log sink for its own duration (covering both the sandboxed-container and in-process dispatch paths uniformly) and closes it on every return path. - cmd/archied: constructs the registry, subscribes core NATS to SubjectSystemWildcard, and wires TaskLogs into both Daemon and webui.Server. - webui: archiving a task now removes its log directory too, so archived tasks' logs don't accumulate forever. Documented as a known, accepted race: a task can reach terminal status (satisfying ArchiveTask's precondition) before process() itself returns and closes the sink, so a very late system-log write can race an archive's Remove. Not corrupting -- the write lands on a soon-to-be-unlinked inode and is discarded -- and not worth fixing here: it would mean tying Close to the store transition instead of to process()'s return, a larger change than this issue's scope. Adversarial review (fresh subagent) found and fixed two real issues in the first draft: a doc comment accidentally spliced between two functions during an extraction meant to fix a lint regression, and a genuine test gap on openTaskLog (added, using TaskRegistry.Write's own true/false contract as the observable -- no Store/Forge/Trees fakes needed, since openTaskLog only touches TaskLogs and Log). |
||
|
|
53da52ecd1 |
feat(agentexec): publish agent-side logs to the task's system subject
Part of #453 (task-observability epic #450). archie-agent logged to os.Stderr only, and its container is created with AutoRemove: true (internal/container/pool.go), so all of it disappeared the moment a task's container exited -- there was no way to see why, say, a gate command failed inside one. Adds agentexec.SystemLogHandler: a slog.Handler that tees to whatever it wraps (kept for an operator attached to a live container) and additionally publishes each record, JSON-encoded as a logging.Entry, to SubjectForSystem(taskID) -- a subject that already existed, documented for exactly this ("log dumps, health... observability"), with zero publishers anywhere in the codebase. cmd/archie-agent/main.go wires it in only when this container was spawned for one specific task (bootTaskID / .git/task.json present); shared queue-group mode serves many unrelated tasks per process, so there's no single task subject to ship to and keeps the stderr-only logger. Building this surfaced a real pre-existing bug: FeedHandler's attr flattening applied the group chain active at Handle-time to *all* accumulated attrs, including ones added via WithAttrs before a later WithGroup call -- nesting them under a group they were never actually inside, contrary to slog's own documented Handler contract. It went unnoticed because nothing in the codebase called WithGroup until this change needed to. Extracting the shared flattening logic into exported FlattenAttrs/PrefixAttrs (so SystemLogHandler doesn't duplicate it) is what surfaced it; fixed in the same change since I was the one making it public API. Docs on the wire format's own trap for the daemon-side consumer (#454, not yet written): the published bytes are a marshaled logging.Entry, meant for json.Unmarshal, not logging.decode() -- decode() parses raw slog JSON *log lines* off disk, a different and incompatible shape. See the doc comment on SystemLogHandler. |
||
|
|
4131f05036 |
feat(webui,gateway): wire config, channel, log-feed, and work-intake seams
Composition root work tying the config resolver, channel manager, log feed, and executable workflow registry into the running daemon and dashboard server: web.Channels/LogFeed/Workflows/ConfigProvenance, channel-reload wiring, TaskStopper for the Stop action, and SpawnRequest.Body/WorkRequests threading dashboard "Start work" requests through the same admission path chat uses. Touches all three features at once because this is where they're composed, not owned by any single one. Refs #53, #54, #55 |
||
|
|
0d500a4ca9 |
feat(webui): lifecycle-safe task controls with atomic retry and archive
Add cancel/stop/approve/reject/retry/abandon/archive to the dashboard task action matrix, each guarded by an optimistic status check against the store. Retry accounting (RetryCount, max_retries) is now atomic with the status transition instead of a separate write. Archive removes a terminal task's local record with a fail-safe audit event first. Add always-labelled responsive navigation, mobile Jump-to search, and versioned Setup-complete dismissal. Fixes #53 |
||
|
|
b876fc80cc | feat(gateway): make chat turns durable and idempotent | ||
|
|
6aa3772ce9 |
feat(gateway): tool-approval gate, session tools for chat, and /delete command
Adds a human-consent gate for tools marked RequiresApproval, exposes
session management as LLM-invokable chat tools, and gives the operator
/delete to retire conversations permanently.
**Tool-approval gate (internal/tools, internal/agentexec)**
- ApprovalRequester contract lives in internal/tools (not gateway) so
agentexec can import it without pulling in the chat-adapter stack.
- ToolSetOptions.Approval wires the approver through to toolExecute.
- BuildToolSetFrom omits RequiresApproval tools when no approver is
configured; dispatch paths (invokeTool, tool_call bridge) refuse
them too, so the invariant holds at every indirection.
- The gate fails closed: only Approved/PermanentlyApproved pass;
an unknown decision value from a faulty approver does not execute.
- Tool-level timeout (2 min) returns a plain error, not a context
cancellation, so the model can report "approval timed out" instead
of the turn aborting.
- BuildApprovalDescription callback lets a tool surface the specific
resource being acted on ("Delete session \"abc123\"") rather than
showing a static tool description.
**Session tools (internal/gateware/session_tools.go)**
- session_list (idempotent), session_resume (mutating), session_title
(mutating), session_delete (mutating + RequiresApproval).
- Scoped to the current platform + channel: GetByChannel replaces
List() so a model in chat A cannot list or manipulate chat B.
- session_title validates the session belongs to this channel before
writing; session_resume/session_delete resolve refs against the
channel-scoped list.
- Shared limit helper extracted to tools.ListLimit.
**Telegram approval adapter (internal/channels/telegram/approval.go)**
- telegramApprover implements ApprovalRequester via the three-button
inline keyboard (Approve/Permanent/Deny). 2-min token expiry.
- Own map + mutex + "approval:" callback prefix — separate from the
dangerous-command system.
- Permanent approval uses exact-match (not prefix) lookup keyed by
action + resource description, so permanently approving "delete
session abc123" only covers that one session, not every call to
session_delete for 24h.
**Session lifecycle**
- /delete <session-id>: removes a session and its history. Refuses
prefixes shorter than 4 chars even when unique. Exact ID wins over
an ambiguous prefix. sessionTracker.forget sweeps every channel+
thread pointing at the deleted session.
- Extracted resolveSessionRef and shortSessionID for /resume and
/delete to share.
**Wiring**
- submitTurn builds the approver onto ctx before the LLM turn.
- chatGenerateOptions reads approver from ctx, passes it through
ToolSetOptions.
- SessionTools built per turn on the current message, combined with
taskTools into a single toolset.
|
||
|
|
1081a6c3ed |
feat(daemon): identity-scoped isolation + gateway session titles and /delete
Multi-identity daemon isolation: - Split runIdentities into per-identity poll loops plus one shared maintenance-and-drain loop, so reconcilePRs and storage cleanup run in multi-identity mode and the global max_concurrency / per-repo serialization holds across identities. - Make the poll path identity-aware: each identity polls with its own forge client, bot user, label, trigger, and ack reaction. - Make allowConcurrentFor task-based and identity-aware via repoFor. - Roll back storage mounts when container acquisition fails; log Store.Update failures after branch set. Container-mode RPC identity routing: - forgerpc/worktreerpc gain identity-scoped subjects (SubjectFor, RegisterFor) and identity-carrying clients. - registerTaskRPCServers registers one server pair per identity (plus root), so a container-mode task owned by a non-root identity is served by its own forge client and worktree manager. Gateway/Telegram: - LLM-proposed session titles generated in the background after turns (TitleGenerator + chatTitleGenerator), persisted by the gateway. - /delete session command with prefix guard and tracker forget. - Shared session display helpers (shortSessionID, sessionDisplayTitle, resolveSessionRef). |
||
|
|
7e896c9411 | refactor: migration of workflow into it's own domain | ||
|
|
308666b410 |
chore: remove legacy terminology and dead code
- Reword docs and comments to drop vague "legacy" qualifiers where they no longer describe deprecation status - Remove unused code: RecentEvents, MessageEvent.ToLegacy, index setState, stderr redaction tool, telegramOnlyCommands - Delete or comment out tests covering removed or superseded behavior |
||
|
|
e10cbbc92c | refactor: pre-cleanup. | ||
|
|
36d00963a5 |
feat(curator): trigger accounting — primary-input wake path (archie-core-035)
A completed chat turn is published as turn_completed from the single responder choke point shared by the telegram and web gateways (redeliveries return earlier and never emit). The runtime wake path forwards ONLY primary-input kinds to input-driven curators; curator- produced activity (curator_run/action/error and any future derived kinds) never appears on that path, so a curator that writes memories cannot schedule itself again — the feedback-loop guard, with the rationale recorded in the regression test so it is not removed as redundant. The bus subscription is bounded and dropping, so the wake path can never backpressure the chat publisher; a dropped event only delays a run to the next check-in. |
||
|
|
4ece064026 |
feat(curator): engine family contract, registry, and runtime (archie-core-rfp, archie-core-89x)
internal/curator is a conforming engine family per the strict plugin engine rule: typed CuratorEngine contract (Lifecycle + domain ops), owning Registry (registration, discovery, start/health/stop with failure isolation, reverse-order shutdown, ctx-bounded stop), and a narrow typed Registrar — each curator receives a capability-filtered view of the host at Bind, never the daemon. Runtime: one loop per curator on an injectable clock (fake-clock testable), best-effort wake nudges with the trigger decision kept in Check (a dropped nudge only delays to the next check-in, never corrupts accounting), per-pass timeout and a max-concurrent-passes slot so curator bursts cannot starve chat turns, per-pass panic recovery, and bounded shutdown even when a pass ignores cancellation. curator_run / curator_action / curator_error ride the in-process event bus so activity stays attributable. Wired in cmd/archied/main.go (constructed beside memory, Start after daemon startup, shutdown ordered before memory/LLM teardown) and exposed as daemon.Daemon.Curators. |
||
|
|
68ba3456ee |
feat(webui): chat from the dashboard
Brings the chat surface to the Web UI: /api/chat with its own handlers and tests, a self-contained ui/src/chat feature folder, and the shared plumbing to reach the same router Telegram uses. Includes a dangerous-command approval path (internal/gateway/dangerous.go, internal/webui/dangerous.go, and the Telegram counterpart) so /rollback and /stop are gated the same way on both surfaces, persona handling for web sessions, and release-update formatting split out of the Telegram service so both can render it. web_parity_test.go pins that the two surfaces expose the same commands. Authored in a parallel session; committed here so it lands with the rest rather than sitting uncommitted while other work builds on top of it. task check passes with it in place. Screenshots used while building are gitignored (*.png) rather than committed, matching the call made on the earlier design reference. |
||
|
|
fa6f4aef5f |
fix(gateway,daemon): repair regressions found by the adversarial review
Six defects, four of them introduced by the fixes in |
||
|
|
1f2e7a42eb |
refactor: one definition of what approving or declining a task means
The dashboard and chat both let an operator approve or refuse work, and they had drifted. Declining from the dashboard left the task closed_wont_do; cancelling the same task from chat left it rejected. Two operators looking at one queue saw different states for the same decision, and "rejected" -- which reconcilePRs also uses for a pull request closed without merging -- stopped meaning one thing. internal/gateway deliberately does not import internal/store, so it kept a hand-synced copy of the status strings with a comment asking future editors to keep them aligned. That is the same defect one level down, and it is how the drift happened. internal/taskstate is a leaf package with no dependencies holding the lifecycle vocabulary and the rules for operator actions. gateway, store and the dashboard all import it, so gateway stays decoupled from store without a copy, and CheckApprove/CheckRetry/CheckDecline have one implementation. Declined is named for what it is -- a human said no -- and stays distinct from Rejected, which is something archie observed. Chat cancel now records Declined. That is the behaviour change: same decision, same state, whichever surface the operator used. Rules were preserved rather than tidied while unifying. A parked task still cannot be declined, which both surfaces already refused, even though "not terminal" would have allowed it -- widening a rule under cover of a refactor is how you ship a change nobody reviewed. The comment says where to change it if that is ever wanted. TestDashboardAndChatAgreeOnTerminalStates drives both real surfaces against one store, so this cannot drift apart again without a red test. Also removes a second rule for the dash-top-standalone class: renderSetup already reconciles it from the data at the top of every call, and a later branch cleared it again. Harmless, but it reads as two sources of truth for one bit of layout state. |
||
|
|
170fe0250b |
fix: close the duplicate-work loop and the dead paths around it
Applies the four-reviewer pass over the forge/dashboard-actions work. The through-line is that several capabilities were wired but inert, and one of them could cost real work. DUPLICATE WORK. "Closes #N" was dropped from PR bodies in favour of LinkBranch, which is sidebar linkage on Gitea and a no-op stub on GitHub -- neither closes anything, and nothing else did either. So a merged task left its issue open, labelled and assigned; the next poll re-enqueued it, and once the dashboard's Clear removed the task row that became a second implementation and a second PR for work already merged. reconcilePRs now closes the issue on merge, and a rejected task closes its issue too. A PR closed without merging deliberately leaves the issue open: that usually means "try again". MAX RETRIES. Configured, defaulted and reported by /api/config, and enforced nowhere -- markDead was unreachable and EffectiveMaxRetries had no callers, so the dashboard's retry incremented retry_count forever. The retry action now retires a task to dead at the cap. DEAD ON ARRIVAL. Tasks() never selected plan or source, so the "Decision required" panel could not render and chat tasks -- whose issue number is synthetic -- linked to forge issues that do not exist. COSMETIC FAILURE, FATAL RESULT. OpenPR failed the whole stage when LinkBranch errored, so the pull request was never opened and the task parked; a retry re-links the same branch, which Gitea answers with a conflict, so every retry parked again. It is best-effort now. INVISIBLE ACTIONS. Approve/retry/reject wrote store rows and nothing else, so the timeline and activity stream never showed that a human had intervened. They emit events now. Also: store write failures answer 500 rather than 409; the dashboard surfaces the server's actual reason instead of "409 Conflict"; action buttons stop propagation (acting on a task no longer also expands it), disable in flight, keep per-task errors instead of one shared string, and confirm before rejecting. Removed: the maybeRetryParked shim and markDead with their now-vacuous tests, WaitingTasks (no consumers; its tests were rewritten to assert the same routing through TaskByID), write-only Daemon.Runtime, and dir/dirs response bloat from /api/skills. skillSource checked workDir before sharedDir, mislabelling every shared skill when the two are equal. DefaultRoots now dedupes roots differing only by a trailing separator. The air build rule claiming to keep ui/dist current never ran -- it required one file to satisfy include_dir and include_file together, and ui/ is excluded from the walk. Deleted with the comment that promised it. task test:ui joins task check and CI; it ran nowhere before, so the dashboard suite could rot silently. Docs corrected where they described behaviour that no longer exists: parks no longer comment on the issue, state labels no longer drive retries, and forgerpc's doc claimed four proxied methods while listing three of five. |
||
|
|
a2b2dc9ef2 |
fix(tools): let an optional provider fail without taking the daemon down
provider.Registry.Start was atomic for every provider: one failure unregistered every other provider including the builtins, returned an error up through the capability host, and exited archied. Under Restart=on-failure that is a crash loop. Observed on carina 2026-07-30 -- mcp.desktop-commander could not start because the runtime image was missing unzip, and the daemon restarted continuously, losing chat, the gateway and every builtin tool over one third-party npm package. Atomicity is right for a provider archied requires. It is wrong for an external MCP server pulled from a registry at runtime, which is exactly the category allowed to be absent -- the same reasoning already applied to the forge, and to containers. RegisterOptional marks a provider the daemon can run without. Its failure to start, discover or index stops only itself and excludes it; Register keeps today's rollback. Required/optional is a deployment fact rather than a property of the code, so the registrar states it instead of the engine declaring it in its own manifest -- which also keeps plugin.Manifest metadata-only, per the plugin engine rule. A skipped provider's dependents cannot run either: an optional dependent is skipped with the reason, a required one is a hard failure, since it declared it cannot work without something now absent. Degradation is reported, not silent -- Health goes degraded naming each provider and cause, Skipped() exposes the set, and the daemon logs one error line per exclusion. Silence is how this went unnoticed until the crash loop. A provider that half-started before failing is still stopped, so no child process is left behind. The regression test drives the real capability host, the path main.go calls: with desktop-commander registered as required it fails with the verbatim carina error, and as optional the daemon starts with its builtins intact. Closes archie-core-ky6 |
||
|
|
f64353f0b5 |
fix(gateway): do not answer a redelivered message twice
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 |
||
|
|
0d4d045050 |
fix(memory): fall back to the default directory instead of exiting
|
||
|
|
4d44ef76f5 |
feat(webui): rebuild the dashboard
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. |
||
|
|
449c925f29 |
feat(logging): optional rotating log file
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. |
||
|
|
3ae59c99c0 | fix(secrets): wire provider credentials through engines | ||
|
|
2307c8c81a | feat: unify provider and model selection | ||
|
|
6c32550345 |
chore: replace personal owner names in tests and config with generic values
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 |
||
|
|
bc5d8dcdc9 |
test: drop tests that grep source text instead of behaviour
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. |
||
|
|
4c0a06df6d |
fix(container): write the task boot brief under .git
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. |
||
|
|
75e58ef595 |
fix(archied): disable the forge on a missing credential, not the daemon
An unresolvable forge token aborted startup with exit 1, denying the operator chat, the gateway and every other subsystem over a capability they may not use -- and under the installed unit (Restart=on-failure, RestartSec=5s) it crash-looped where the error was never read. Forge setup moves into resolveForge, shared by the primary forge and each configured identity, and degrades to NoopForge with a warning. Malformed config still fails fast in validation. The systemd unit gains StartLimitIntervalSec/StartLimitBurst as a backstop for other failures. |
||
|
|
6be754787d | polish: add install.sh, XDG setup, deployments/ examples, and github-token docs\n\n- Add install.sh following XDG Base Directory specification (~/.config/archie, ~/.local/share/archie, ~/.local/bin)\n- Add interactive setup for code forge (GitHub / Gitea / Standalone) and LLM provider selection (Ollama model picker / Cloud keys)\n- Implement NoopForge in internal/forge/noop.go for running Archie in standalone mode without a forge\n- Enable loginctl user linger and systemd user unit setup in install.sh\n- Add docs/github-token.md with step-by-step guidance for Classic PAT generation\n- Add top-level deployments/ directory with scenario templates (single-forge GitHub, multi-forge GitHub+Gitea, local Ollama standalone, systemd runbook) | ||
|
|
d3dd06d48f |
Merge remote-tracking branch 'origin/feat/75-add-mcp-client-capabilities-to-archied-and-archie-agent'
# Conflicts: # cmd/archie-agent/main.go # cmd/archied/main.go # cmd/archied/main_test.go # internal/agentexec/nats.go # internal/config/config.go # internal/tools/budget_test.go # internal/tools/dispatch_test.go # internal/tools/mcp/transport_sse.go |
||
|
|
e7d39254e7 |
feat: make /stop reach running agent tasks
/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.
|
||
|
|
561e56b70a |
feat: make /stop cancel the running chat turn
/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. |
||
|
|
e03cef17c9 |
feat(tools): lift tau's file and shell tools into the tool registry
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.
|
||
|
|
bf5a7618e6 |
fix(chat): operator name from config, session wiring, prompt rules
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.
|
||
|
|
9d5040fd65 |
refactor: add internal/eventbus as the broker-neutral messaging contract
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.
|
||
|
|
c66c0a2a38 |
refactor(config): move loading into infrastructure/configuration
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.
|
||
|
|
a8efbf5046 |
refactor: route tasks on a typed kind, not forge labels
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
|
||
|
|
2d082eef89 | Merge branch 'crew/lint6' | ||
|
|
492ca209f9 |
refactor(nats): rebuild as infrastructure/eventbus/nats with real boundaries
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. |
||
|
|
712388dc6c |
fix: Phase 4 structural refactor — reduce lint findings from 28 to 5
cyclop (5→0): extract subcommand/case bodies in codesearch, subprocess, Telegram, indexing funlen (5→3): extract memory action handlers, tool provider startup gocognit (7→2): extract config finalize/loadDirInto helpers, release announcer, capture tool validation, Telegram gateway (200→108), archie-agent main loop (35→0) nestif (8→0): extract identity validation, container validation, conf.d scanning, email multipart parsing, Telegram model/update parsing, build-no-changes closure interfacebloat (3→0): split Forge/IssueForge/PRForge/RepoForge, SessionStore/SessionLifecycle/MessageHistory, TaskStore/TaskLifecycle/TaskQueries/TaskEvents Remaining: daemon process, workflow Feasibility/TDD/AgentStage, archied main.go run (108→30 remaining). These require deeper refactoring best done per-function in follow-up beads. Updated contract tests and archied wiring tests to check both main.go and the new telegram_setup.go. |
||
|
|
a66da97ab7 |
gateway: implement session lifecycle and context commands (archie-core-alm.5)
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. |