Commit Graph
498 Commits
Author SHA1 Message Date
sam 49a3d08cdf chore(beads): export issue state 2026-08-14 02:41:46 +10:00
sam 0d73f2fa5a feat(chat): show tool calls inline and stream replies into one message
Chat returned only the final answer, so a wrong tool choice, a
hallucinated action, or a footgun like `systemctl stop` against
`restart` was invisible from the conversation. Only text deltas were
threaded through the turn, and tool calls executed inside Generate with
nowhere to report.

Replace the delta callback with gateway.TurnStream, which carries text
fragments and completed tool calls on one ordered path from the model
loop to the channel. The sequence is the point: a tool line that
overtakes the sentence it interrupted describes a turn that never
happened. Text-only callers use gateway.DeltaFunc and are unaffected.

A tool is reported on its result, never on its call  --  the call part
carries no outcome yet, so reporting both would list every tool twice,
once with nothing to say.

Telegram renders it behind [chat.telegram] show_tool_calls, off by
default: this is debugging visibility, and it narrates every internal
step to provide it. The dashboard always shows it, being the operator's
own observability surface; its tool lines are live-only and are not
persisted with the conversation.

The Telegram live reply changes mechanism, and with it what a frame
MEANS. It used to stream through sendMessageDraft: drafts are ephemeral
30-second previews, so a tool call longer than that outlived the
preview, and successive frames were observed concatenated with their
cursors intact. It now sends one real message and edits it. An update
used to be "the next preview of the answer"; it is now "the whole
answer as it currently stands, replacing what is there". The cursor is
appended at render time and never stored, so exactly one exists and
always at the end, and a frame too long for one message is cut to its
tail rather than rejected outright.

A stopped or failed turn now edits the cursor away instead of leaving
it blinking on a message nothing will finish. That cleanup runs on a
live context because turnCtx is already dead, and it runs on both
failure branches: ai-sdk raises an aborted stream as ErrAborted with
ctx.Err() formatted in rather than wrapped, so errors.Is cannot be
trusted to tell a /stop from a fault.

Closes #467
2026-08-14 02:36:12 +10:00
sam 9ef6f41910 fix(agent): route git safe.directory setup through markWorktreeSafe
The dubious-ownership fix landed twice: markWorktreeSafe in gitsafe.go
and an inline exec.Command block in main.go, both configuring the same
safe.directory on every start. Two setup paths for one invariant means a
later change to either one silently disagrees with the other.

Keep the tested helper and drop the inline block. markWorktreeSafe also
skips the call when /data/worktree is not a mounted directory, so
running archie-agent directly on a host no longer writes to the
operator's own ~/.gitconfig for a path that was never mounted.

The new test parses main.go and fails on more than one setup path, so a
future re-addition of an inline block is caught rather than merged.

Refs #468
2026-08-14 02:35:49 +10:00
sam 62cf76ad40 feat(agent): mark the mounted worktree as a git safe directory 2026-08-14 01:59:56 +10:00
sam 255add82e0 chore: remove beads config file 2026-08-14 01:59:56 +10:00
sam 52da275f5d bd init: initialize beads issue tracking 2026-08-14 01:59:56 +10:00
sam d1ce92043d Merge pull request #465 from samcharles93/alert-autofix-5
Potential fix for code scanning alert no. 5: Open URL redirect
2026-08-12 19:22:11 +10:00
sam 9b52cc4923 fix(webui): preserve encoded redirect path characters 2026-08-12 19:19:48 +10:00
sam 2ed4e14127 Merge pull request #469 from samcharles93/fix/dubious-ownership-agent-container
fix(agent): resolve git dubious-ownership in sandbox containers
2026-08-12 16:13:05 +10:00
sam 4f4e151ff8 fix(agent): resolve git dubious-ownership in sandbox containers
Agent containers bind-mount the worktree from the host at
/data/worktree, where the owning UID differs from the container
user's UID. Git refuses to operate in such directories, so every
gate command that calls the Go toolchain (go build/test/vet) fails
with 'fatal: detected dubious ownership in repository' before any
real work begins.

Add 'git config --global --add safe.directory /data/worktree' at
archie-agent startup so all subsequent git-spawned operations
(baseline gate, build gate, agent shell tool invocations) work
correctly. Logs a warning if git is unavailable rather than
failing — the agent remains usable for repos with no gate config.
2026-08-12 14:37:37 +10:00
sam 4e0eade43f Merge pull request #466 from samcharles93/fix/github-create-issue
forge/github: implement CreateIssue to un-stub the method
2026-08-12 13:50:20 +10:00
sam a56f95d967 forge/github: implement CreateIssue to un-stub the method
Replaces the 'not yet implemented' stub with a real call to
go-github's Issues.Create, mapping title, body, and labels.
2026-08-12 13:49:20 +10:00
samandCopilot Autofix powered by AI 0ba27935bd Potential fix for code scanning alert no. 5: Open URL redirect
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-08-12 11:40:21 +10:00
sam 367637d174 fix(webui): cap and centre the Configuration page instead of its lists
The page ran the full width of the shell, so a card was roughly 1300px
of which the content used the left third. Every previous attempt fought
that inside the card by capping or shrinking .kv-list, which only moved
the imbalance around: the lists changed width but the Repositories and
Providers tables stayed stretched just as far, and shrinking the lists
broke the row separators and the alignment of the Edit column.

Constrain the page container instead. One max-width and auto margins on
the view fixes every child at once, so cards, key/value lists and tables
all sit on the same readable measure and the leftover space falls
outside the cards where it reads as margin rather than as a hole.

Scoped to this page as .cfg-page rather than added to .page-head, which
every other view shares; widening that is a separate decision.

This is what `margin: 0 auto` was for. Applying it to .kv-list, which is
what I tried first, really would have misaligned each list against its
own card heading and against the table beneath it, and I used that to
rule the approach out rather than to move it up a level.
2026-08-10 03:18:17 +10:00
sam f2eaba2fe1 fix(webui): keep Configuration rows full width, hug only the label column
Sizing the whole list with width: fit-content fixed the label-to-value
distance by breaking the row: every list ended at a different width, the
separators stopped part-way across the card, and no two Edit buttons
shared a column.

Those are two different knobs and only one of them was ever the bug.
How far the value sits from its label is set by the label track; how
wide the row is is set by the container. Hug the first, leave the second
alone: the label column is max-content so the value starts immediately
after the longest label, the value column takes the slack, and the
actions column is pinned right. The row spans the card again, so the
separators run full width and every Edit lands in one column, while the
label-to-value distance stays as short as it was.

Verified against the built stylesheet in the dark theme at 1440px:
label and value adjacent, locked reasons on their own line, actions
aligned across sibling lists.
2026-08-10 03:11:58 +10:00
sam 7b07033d7c fix(webui): size Configuration key/value lists to their own content
The rewrite capped .kv-list at 72rem and left it anchored to the card's
left edge, so on a wide screen the rows stopped well short of the card
and the action column floated in the middle of the dead space rather
than sitting near the value it belongs to.

Any fixed cap is a guess that is wrong at some viewport: too wide and
the actions drift away from the value, too narrow and paths truncate
for no reason. Size the list to its children instead --
width: fit-content, bounded by max-width: 100% so a pathological value
clamps and lets the ellipsis take over.

Not centred with margin: 0 auto. These lists share cards with
full-width tables (Models & providers has both), so centring would
misalign every list against its own card heading and against the table
directly beneath it.

Sizing to content required moving the columns off the row and onto the
list. Each .kv was previously its own grid, so no row could size a
column against any other row, and a max-content label track would have
ended at a different x on every line. The list now declares the tracks
and each row adopts them with grid-template-columns: subgrid, giving
one shared label column sized to the longest label and no wider. A
@supports fallback keeps the previous bounded-column behaviour where
subgrid is unavailable, and the narrow-viewport rules drop out of
subgrid because a shared label column is the wrong shape once the row
stacks.

Verified by rendering the built stylesheet against representative
markup rather than by inspection: label and value adjacent, notes on
their own line, actions in a reserved column, no dead space.
2026-08-10 03:07:47 +10:00
sam fb7fba4232 fix(webui): rebuild the Configuration page layout so values stop colliding
The page had three compounding layout faults, all visible on a wide
screen and all still present after the earlier spacing pass:

  1. .cfg-row used justify-content: space-between on a full-width card,
     so the label sat at the far left and its value at the far right with
     roughly a thousand pixels between them. Reading one pair meant
     tracking across the viewport. The earlier "tighten KV row spacing"
     change reduced vertical padding only, which is why the complaint it
     was meant to answer survived it.
  2. .cfg-value had no min-width: 0, so a long value could not shrink
     inside its flex parent. It overflowed into the Edit button, which is
     why 400 rendered as "40" and 100000000 was clipped mid-number.
  3. The locked-row reason was a flex sibling of that overflowing value,
     so it ran onto the end of the path with no separation, rendering
     ".../archie/work" and "pins the daemon's working layout" as one
     unbroken string.

Replace the flex row with a three-column grid: label, value, actions.
Label and value are adjacent and left-aligned so the eye travels a fixed
short distance at any viewport width; the value column is minmax(0, 1fr)
so it can actually shrink, truncating with an ellipsis and keeping the
full text in a title attribute; actions occupy a reserved column that
nothing can overlap. Secondary text (locked reason, override marker,
validation error) gets its own grid row instead of sharing the value
line. Narrow viewports stack label over value rather than truncating
both to a few characters.

Extract the row renderer into settings/config-row.js. settings.js
imports its own stylesheet, which the node test shim cannot parse, so
the rendering logic was untestable where it sat; this mirrors
tasks/task-row.js. Seven tests now cover the two collision bugs
structurally, asserting on per-child text rather than the row's
flattened string so a future layout change cannot pass by merging the
fields back into one node.

Also stop sharing .cfg-rows with the Workflows "Start work" form. A
class owned by the Configuration page meant restyling Configuration
could silently restyle that form; it is now .wf-form, owned by the
feature that uses it.
2026-08-10 03:00:56 +10:00
sam 7ee68d080a feat(archied): add -version so the installed build can be read from a shell
gatewayVersion and runtimeVersion were reachable only through the chat
/version command, which needs a running daemon and a configured channel.
An update-check adapter has to answer "what is installed?" before it can
compare against what is available, and had no way to ask.

Prints one "name version" pair per line so a shell adapter can parse it
without a JSON dependency.
2026-08-10 02:48:59 +10:00
sam 94adedc2d7 fix(build): stamp versions in task build, not only in the Docker image
Version stamping lived solely in Dockerfile.archied's -ldflags, so any
build from source reported gatewayVersion/runtimeVersion as "dev". That
covers every host deployment: carina builds the binaries with go build
and runs them under systemd, never touching the image, so /version there
answered "Archie Gateway: dev Runtime: dev" for a tagged release.

Derive the same -X values from the release tags. git describe without
--abbrev=0 gives 1.7.0-2-gbb54786 when HEAD has moved past the tag,
which is the honest answer for a mid-cycle build rather than claiming
the release itself.

archie-agent has no version variable, so only archied is stamped.
2026-08-10 02:42:24 +10:00
sam fcfe5cf264 fix(deploy): wire ExecReload so SIGHUP config reload works under systemd
archied v1.7.0 reloads its configuration on SIGHUP, but neither the unit
written by install.sh nor the one in the systemd runbook declared
ExecReload. 'systemctl --user reload archied' therefore failed, and the
only way to reach the new reload path was to know about
'systemctl --user kill -s HUP'.

The feature shipped with no supported trigger in the documented
deployment shape. Existing installs need the same line added, either by
re-running install.sh or via a drop-in.
2026-08-10 02:31:59 +10:00
sam 8e8c22be61 fix: docker-compose corrected image path 2026-08-10 02:28:48 +10:00
sam f03e927fe4 ci: strip the v prefix when matching release tags to changelog sections
deploy / gate (push) Failing after 2m15s
deploy / build-and-push (push) Skipped
The gate derived the version with ${tag#archied/}, which leaves "v1.7.0",
then looked for a "## [v1.7.0]" heading. Changelog sections carry no v --
tools/release.sh writes and validates "## [1.7.0]" -- so the gate could
never match and every tagged release failed before the images were built.

This is the gate's first tagged run: it landed in dd9bddc, after the
archied/v1.6.0 tag, so nothing had exercised this branch until v1.7.0.
2026-08-10 02:22:50 +10:00
sam 6d5fdd72a3 chore(release): archied v1.7.0 archie v1.4.0 2026-08-10 02:13:39 +10:00
sam 5104c50953 Merge pull request #464 from samcharles93/feat/348-config-editing
Feat/348 config editing
2026-08-10 02:04:55 +10:00
sam a92d77696c Merge branch 'main' into feat/348-config-editing 2026-08-10 02:04:45 +10:00
sam c06dd9c668 fix(gateway): harden session recovery paths
Repair future-dated conversation history on SQLite open and cap newly supplied timestamps so one bad platform clock cannot pin a session indefinitely.

Make message and turn identifiers injective while preserving legacy redelivery and crash-recovery compatibility, retire idle turn lanes safely, and pin the existing compression and partial-undo behavior with focused regressions.
2026-08-10 02:03:19 +10:00
sam 664197b43b fix(webui): tighten configuration KV row spacing
Each row in the read-only configuration view was ~45px tall but the
text was only ~20px — empty space outweighed content by ~2:1, making
the page hard to scan. The combined effect of `gap: var(--sp-2)` on
the flex container and `padding: var(--sp-2) 0` on each row doubled
the breathing room. Tables on the same page (Repositories, Providers)
already use the target density; configuration rows now match them.

Scope the override to `.cfg-section` descendants because the
Workflows "Start work" form reuses `.cfg-rows` for its input fields
(form.cfg-rows, no .cfg-row children) and would otherwise lose its
8px inter-field gap. The form is unaffected: the override only
matches when an ancestor carries .cfg-section.

Rows go from ~45px to ~25px, with the border carrying the visual
rhythm instead of doubled padding.
2026-08-10 02:01:32 +10:00
sam 99fb1102cc docs(architecture): mark the config-overlay subset implemented on safe-change-and-recovery 2026-08-10 01:46:18 +10:00
sam 5343c68160 docs(architecture): record the implemented config reload and runtime overlay
Per the sequencing call (adversarial pass first, docs last), the docs
now reflect the design the reviews confirmed.

configuration.md:
- Mutation ledger gains rows for SIGHUP reload, dashboard PATCH,
  dashboard reset, and the runtime overlay store, each mapping to the
  universal change protocol with what is and is not yet implemented.
- New section 'Implemented runtime reload and config overlay (2026-08)':
  the Holder published-snapshot model, the reloadable-field criterion
  (a field is reloadable when EVERY consumer re-reads it), SIGHUP
  reload semantics, the overlay store (separate -config.sqlite, dotted
  keys, denylist, bootstrap degrade), and the PATCH/reset paths.

safe-change-and-recovery.md:
- New section 'Runtime config overlay: degrade paths and recovery'
  tabulating the three boot degrade paths and the reload degrade, all
  verified by the adversarial passes, plus the three documented
  recoveries (--no-config-overlay flag, rm the overlay file, dashboard
  reset). Status line notes the overlay subset is implemented while
  the full runtime-supervision protocol remains under design.

No new documents, per the constraint.
2026-08-10 01:45:44 +10:00
sam 3802ed473d fix(config): preserve nil slices in Clone to avoid spurious reload warnings
Clone normalized nil slices to empty non-nil (make([]T, 0)), so after a
dashboard PATCH the cloned published config carried [] where the file
decodes to nil -- a subsequent SIGHUP reload's diff-and-warn compared
old [] against fresh nil and reported 'Repos changed; requires a
restart' for a field that had not changed at all. The exact warning
fatigue the allowlist exists to prevent. cloneRepos/cloneIdentities/
cloneMCPServers/cloneStringSlices now return nil for nil input (the
append-based copies already preserved nilness).
2026-08-10 01:41:20 +10:00
sam 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.
2026-08-10 01:23:34 +10:00
sam 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.
2026-08-10 01:09:05 +10:00
sam fa8a0d6d02 feat(webui): inline config editing on the Configuration page
The dashboard's Configuration page can now change runtime-tunable
settings without hand-editing TOML (issue #348). Scalar rows get an
Edit affordance; Save PATCHes the dotted key to /api/config, which
validates the materialised config before persisting to the runtime
overlay and republishing.

Per the design constraints:
- Structured values (repositories, models, providers -- arrays and
  maps) render read-only with no edit affordance; they are not
  faked as editable.
- Denylisted keys (db_path, work_dir) render explicitly disabled with
  the server's reason from the ConfigView.locked map, instead of a row
  that silently lacks an Edit button.
- Bool fields edit via a select, ints parse client-side so a typo
  fails before a round trip, durations and strings pass through to
  the server which validates them. The server's error text is shown
  inline on a rejected save (validation failure, denylist, disabled
  overlay).
- Enter saves, Escape cancels, Cancel restores the row.

api.configUpdate PATCHes /api/config with {updates: {dotted.key: v}}.

Verified: task check clean; 23 node tests pass; dist rebuilt and
committed in the same change.
2026-08-10 00:57:05 +10:00
sam 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.
2026-08-10 00:54:23 +10:00
sam 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.
2026-08-10 00:47:30 +10:00
sam 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.
2026-08-10 00:30:26 +10:00
sam 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.
2026-08-10 00:19:46 +10:00
sam 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.
2026-08-09 23:29:52 +10:00
sam 283e85ba7a Merge pull request #463 from samcharles93/fix/gateway-session-defects
fix(gateway): harden session recovery paths
2026-08-09 23:24:05 +10:00
sam 1f71489f0a fix(gateway): harden session recovery paths
Repair future-dated conversation history on SQLite open and cap newly supplied timestamps so one bad platform clock cannot pin a session indefinitely.

Make message and turn identifiers injective while preserving legacy redelivery and crash-recovery compatibility, retire idle turn lanes safely, and pin the existing compression and partial-undo behavior with focused regressions.
2026-08-09 23:18:55 +10:00
sam 4204005ca3 fix(webui): tighten configuration KV row spacing
Each row in the read-only configuration view was ~45px tall but the
text was only ~20px — empty space outweighed content by ~2:1, making
the page hard to scan. The combined effect of `gap: var(--sp-2)` on
the flex container and `padding: var(--sp-2) 0` on each row doubled
the breathing room. Tables on the same page (Repositories, Providers)
already use the target density; configuration rows now match them.

Scope the override to `.cfg-section` descendants because the
Workflows "Start work" form reuses `.cfg-rows` for its input fields
(form.cfg-rows, no .cfg-row children) and would otherwise lose its
8px inter-field gap. The form is unaffected: the override only
matches when an ancestor carries .cfg-section.

Rows go from ~45px to ~25px, with the border carrying the visual
rhythm instead of doubled padding.
2026-08-09 23:18:02 +10:00
sam 79256fc9fd Merge pull request #462 from samcharles93/refactor/sqlite-task-store
refactor(store): replace legacy persistence with SQLite
2026-08-09 22:30:44 +10:00
sam 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.
2026-08-09 22:27:25 +10:00
sam 3afbab8201 refactor(gateway): persist conversations in sqlite 2026-08-09 19:47:33 +10:00
sam 95c5d59e7c docs(architecture): mark observability design as implemented 2026-08-09 19:29:33 +10:00
sam aef7d48df2 Merge pull request #461 from samcharles93/feat/455-task-logs-api-and-chat-tool
feat(webui,gateway): add /api/tasks/{id}/logs endpoint and task_logs chat tool
2026-08-09 19:16:43 +10:00
sam 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
2026-08-09 19:14:35 +10:00
sam 548f0601d3 Merge pull request #460 from samcharles93/fix/454-daemon-log-consumer
feat(daemon): consume agent system logs into per-task sinks and the dashboard feed
2026-08-09 18:49:34 +10:00
sam 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).
2026-08-09 18:42:54 +10:00
sam fab8a66486 Merge pull request #457 from samcharles93/fix/452-task-log-sink
feat(logging): add a per-task log sink
2026-08-09 18:17:24 +10:00