refactor: pre-cleanup.
This commit is contained in:
1 parent
0ceab9d897
commit
e10cbbc92c
53 files changed
+3596
-648
No files matched your search
@@ -274,3 +274,31 @@
|
||||
{"id":"int-0aa90a55daf825cb879d1f9e5994d1e3","kind":"field_change","created_at":"2026-08-05T00:42:41.164725606Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.13","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added a contextual Web Chat session-actions menu for retry, undo, rename, branch, and compression preview. Actions dispatch shared gateway commands and refresh the active session/history. Playwright MCP verified the menu and /undo dispatch; npm tests/build and full task check pass."}}
|
||||
{"id":"int-372ffda198062c9e0fbe7227f944455e","kind":"field_change","created_at":"2026-08-05T00:44:40.646054541Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.14","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Aligned command discovery without weakening the intentional dangerous-command hiding rule: /start is now in the shared gateway catalog and Telegram menu; Web slash completion inherits it. Focused and full task-check suites pass."}}
|
||||
{"id":"int-5f9f3d143801b3cff4f9b81e6f4183dd","kind":"field_change","created_at":"2026-08-05T00:49:48.079957662Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.15","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented server-side Web turn cancellation, authenticated cancel endpoint, immediate session event, UI Stop wiring, API test; task check and UI tests/build pass."}}
|
||||
{"id":"int-f88b0cf8d1dc0762f57c600400786f58","kind":"field_change","created_at":"2026-08-05T01:01:36.902978334Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.16","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Markdown is now a dedicated tested renderer and Chat markup/view/state are split into dedicated source files; Playwright and task check pass."}}
|
||||
{"id":"int-553fa90f40f535e02818c79eb5cc966d","kind":"field_change","created_at":"2026-08-05T01:01:37.127559733Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.17","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Markdown is now a dedicated tested renderer and Chat markup/view/state are split into dedicated source files; Playwright and task check pass."}}
|
||||
{"id":"int-ea20588b819e2907c7b8adb63e8f4f9f","kind":"field_change","created_at":"2026-08-05T01:05:24.113971725Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.17","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Split chat.html, chat.css, markdown.js, chat-view.js, chat-render.js, chat-state.js, chat-catalog.js, and chat-panels.js; browser and full gate pass."}}
|
||||
{"id":"int-25a7a3e0b1d07e6e55bd9f4a5111f683","kind":"field_change","created_at":"2026-08-05T01:13:00.221558079Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.5","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added explicit task timeline controls with keyboard operation, accessible state/relationships, focus styling, DOM regression coverage, Playwright verification, and task check."}}
|
||||
{"id":"int-2110034178629d2fc64fdbc3872e1dbf","kind":"field_change","created_at":"2026-08-05T01:20:16.450475463Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.18","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Web Chat now replaces the live assistant bubble with the safe Markdown renderer on every streamed delta; unit coverage, Playwright verification, npm tests, build, and task check pass."}}
|
||||
{"id":"int-7b1c4881d61026eb5259af44cfffaaa0","kind":"field_change","created_at":"2026-08-05T01:46:35.622632267Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.19","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added typed-nil Web Chat update endpoint regression test; it currently fails with the observed nil-pointer panic as intended."}}
|
||||
{"id":"int-7b90bba1ba3aef3019f4ffe32aa61df5","kind":"field_change","created_at":"2026-08-05T01:52:33.010867085Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.20","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Fixed typed-nil update service handling in Web Chat and releaseupdate, added nil-service coverage, and passed affected-package tests, race tests, vet, and builds. Full task check remains blocked by unrelated internal/tools/builtin/TestFindFallback_CancelledWalkReportsError."}}
|
||||
{"id":"int-03f8b60d93b113c6e5e82682d3608a46","kind":"field_change","created_at":"2026-08-05T01:53:08.810860407Z","actor":"Sam Catlow","issue_id":"archie-core-ts9","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Fixed the cancellation guard; runFindGoFallback now returns an error result when ctx.Err() fires instead of falling through to 'no matches found'. Test + fix in 6d47fb3."}}
|
||||
{"id":"int-b30bfd157cd704a8d9e677fb537fce64","kind":"field_change","created_at":"2026-08-05T01:55:45.419121893Z","actor":"Sam Catlow","issue_id":"archie-core-3fb","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Push now checks the worktree's origin remote for an HTTP(S) scheme and fails immediately naming the missing forge.token config, instead of letting go-git fail late with a bare transport error. Local transports unaffected. 69bc618."}}
|
||||
{"id":"int-448e0c65b5d5f87507fcf725c2f77d43","kind":"field_change","created_at":"2026-08-05T01:57:20.927553571Z","actor":"Sam Catlow","issue_id":"archie-core-bfw","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Removed --force and its help line rather than fake an up-to-date check go build's own cache already makes unnecessary. 625e0ba."}}
|
||||
{"id":"int-b3ed851e1514fb2bdfd08047f847440c","kind":"field_change","created_at":"2026-08-05T01:57:21.771300149Z","actor":"Sam Catlow","issue_id":"archie-core-c6o","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added a default case: unknown options now print a diagnostic naming the flag and exit 1, per the agreed (a) option. 625e0ba."}}
|
||||
{"id":"int-c1fe6d38b84f3a32e5ff142fef85a196","kind":"field_change","created_at":"2026-08-05T01:57:22.198712359Z","actor":"Sam Catlow","issue_id":"archie-core-utt","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Detection now requires positive Linger=yes and falls through to enable-linger (idempotent) on any other outcome, including a failed/empty loginctl call; uses $(id -un) instead of $USER. 625e0ba."}}
|
||||
{"id":"int-994d988e7e0b0b0ca18c9dc95697d537","kind":"field_change","created_at":"2026-08-05T02:44:49.686671248Z","actor":"Sam Catlow","issue_id":"archie-core-ewk.1","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Exported Validate(cfg *config.Config) error wrapping the unexported validate; Loader.finalize now calls it. Documented that it doesn't apply defaults, so setup should render+reload through a Loader rather than call Validate on a hand-built config directly. 82fd015."}}
|
||||
{"id":"int-77aba9bbe52b8e697c888fee3f452198","kind":"field_change","created_at":"2026-08-05T02:47:24.466276431Z","actor":"Sam Catlow","issue_id":"archie-core-via","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Defined Prompter (Select/ReadLine/ReadSecret/Confirm, all context-aware) in internal/infrastructure/configuration/setup, and a real TTY-gated implementation in internal/infrastructure/terminalprompt. Construction refuses a non-terminal input with a clear message rather than a degraded fallback. b04733c."}}
|
||||
{"id":"int-ae335a9efd6546eafb010a5e4ab24406","kind":"field_change","created_at":"2026-08-05T02:58:58.454077695Z","actor":"Sam Catlow","issue_id":"archie-core-cbk","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Implemented Run in internal/infrastructure/configuration/setup: operator, provider, models, forge, chat(telegram) steps, returning tomlwrite edits (not a parallel config.Config). Tested by rendering+loading through a real Loader. Found and fixed two boot-time landmines in config.example.toml along the way ([providers.openai] bws default, [[repos]] placeholder). 56d684a."}}
|
||||
{"id":"int-199608b5a75e0656f5588a9e9769f035","kind":"field_change","created_at":"2026-08-05T04:23:35.480944746Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.3","extra":{"field":"status","new_value":"open","old_value":"closed"}}
|
||||
{"id":"int-807c0bfa32b573810961a590e666e96f","kind":"field_change","created_at":"2026-08-05T04:23:35.655154884Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.5","extra":{"field":"status","new_value":"open","old_value":"closed"}}
|
||||
{"id":"int-a35915621451865f63e3dc02a85f663d","kind":"field_change","created_at":"2026-08-05T04:23:35.833440967Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.7","extra":{"field":"status","new_value":"open","old_value":"closed"}}
|
||||
{"id":"int-c009a300902078abd705e1703b0cf732","kind":"field_change","created_at":"2026-08-05T04:23:36.015993075Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.14","extra":{"field":"status","new_value":"open","old_value":"closed"}}
|
||||
{"id":"int-54f7fd84050f409c89d45c4ce5c86533","kind":"field_change","created_at":"2026-08-05T04:23:36.211080415Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.25","extra":{"field":"status","new_value":"open","old_value":"closed"}}
|
||||
{"id":"int-1e1d209179d47901b9a76713c9d6877c","kind":"field_change","created_at":"2026-08-05T04:23:36.427302171Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.24","extra":{"field":"status","new_value":"open","old_value":"closed"}}
|
||||
{"id":"int-b8c4b80e05b0760cc5ddfa690f4bddfa","kind":"field_change","created_at":"2026-08-05T04:23:36.636676694Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.26","extra":{"field":"status","new_value":"open","old_value":"closed"}}
|
||||
{"id":"int-2e92c16044f0b5c1ff964b26e9abf779","kind":"field_change","created_at":"2026-08-05T04:23:36.804448838Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.27","extra":{"field":"status","new_value":"open","old_value":"closed"}}
|
||||
{"id":"int-df7db2f07c3f013cefd5d427f766fea6","kind":"field_change","created_at":"2026-08-05T04:23:37.003152861Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.33","extra":{"field":"status","new_value":"open","old_value":"closed"}}
|
||||
{"id":"int-e7538b713cd9d6932e3d759ef294b5f5","kind":"field_change","created_at":"2026-08-05T07:20:39.887488125Z","actor":"Sam Catlow","issue_id":"archie-core-n8l","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Duplicate of archie-core-7ma, which has the sharper diagnosis (regression from 44f914c's v0.2.5->v0.3.0 bump, not a long-standing prefix squat). Fix landed under 7ma."}}
|
||||
{"id":"int-edf64421a584e5b563db3e2878a17c75","kind":"field_change","created_at":"2026-08-05T07:20:50.789955047Z","actor":"Sam Catlow","issue_id":"archie-core-7ma","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Fixed forward on v0.3.0 (no pin-back; sdk.MessageRange is v0.3.0-only so a revert would drag the session/message store with it).\n\ninternal/nell/adapter.go:\n- Counters moved off the SDK-reserved prefix: meta:task_id_counter -> counter:task_id, meta:event_id_counter -> counter:event_id.\n- migrateCounters() seeds the new keys from the old docs at open. The old doc is readable (only Put fails) and its next_id is load-bearing: restarting at 1 would reissue IDs belonging to live tasks. Old doc left in place; removing it is the op that cannot succeed. Migration failure is now fatal at OpenStore rather than silently starting a fresh sequence.\n- isMetaKey -> isReservedKey. Counter ids matched EXACTLY, not by prefix: task keys are owner:repo:number, so a counter: prefix rule would black-hole every task in a repo owned by 'counter' (enqueue succeeds, then invisible to ClaimNext/Tasks/StatusCounts forever).\n- EnqueueIssue now persists identity, which it previously accepted and silently dropped -- every forge-polled task was unattributed, diverging from the SQLite store and breaking multi-identity dispatch.\n\nTests (internal/nell/counter_repro_test.go): persisted log -> write -> reopen -> write again (the missing red test); migration continues a seeded sequence; migration failure prevents opening; identity round-trips; a task owned by 'counter' stays visible.\n\ngo build/vet/test ./... clean; lint at baseline."}}
|
||||
{"id":"int-7a545490a53d8e491ddeebe7ae4fa1a4","kind":"field_change","created_at":"2026-08-05T07:20:59.251143818Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.7","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Now integrated, not just implemented. agentexec.BuildToolSet applies the per-tool result cap and the per-turn budget inside the Execute closure it builds for every tool -- the one path from a ToolEntry to a model. tools.CapPayload is the single definition of the cap/spill rule, shared with the batch-dispatch path. Limits are configurable via [tools.tool_policy] (max_result_chars, turn_budget_chars, spill_dir), which previously had no toml tags and could not be set at all. Budget is minted per turn/stage, never shared. Adversarial pass fixed a double-charge (Spill billed the full displaced size on top of the caller's charge) and cross-turn spill filename collisions."}}
|
||||
{"id":"int-860bc7fc4c800ff799eda762ce6b8d55","kind":"field_change","created_at":"2026-08-05T07:20:59.532604119Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.25","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Now integrated, not just implemented. agentexec.BuildToolSet applies the per-tool result cap and the per-turn budget inside the Execute closure it builds for every tool -- the one path from a ToolEntry to a model. tools.CapPayload is the single definition of the cap/spill rule, shared with the batch-dispatch path. Limits are configurable via [tools.tool_policy] (max_result_chars, turn_budget_chars, spill_dir), which previously had no toml tags and could not be set at all. Budget is minted per turn/stage, never shared. Adversarial pass fixed a double-charge (Spill billed the full displaced size on top of the caller's charge) and cross-turn spill filename collisions."}}
|
||||
+33
-24
@@ -1,3 +1,4 @@
|
||||
{"_type":"issue","id":"archie-core-n8l","title":"fix(nell): counters squat on the SDK-reserved meta: prefix, blocking all writes after restart","description":"TOTAL OUTAGE. No task can be queued and no event recorded; survives restarts.\n\ninternal/nell/adapter.go:946,952 store auto-increment counters at meta:task_id_counter and meta:event_id_counter. The NellDB SDK reserves the meta: prefix for its own bookkeeping (sdk/replicate.go:841 isInternalID = id[:5]==\"meta:\").\n\nDocDB.reindex() skips internal ids when rebuilding the in-memory rev cache (sdk/docdb.go:128-137), but the record stays in the log. So after a restart Get returns the counter doc WITH its _rev while d.revs has no entry, and putIn rejects exactly that: 'incomingRev != \"\" \u0026\u0026 !exists' -\u003e ErrConflict (sdk/docdb.go:213-217). Permanent.\n\nHits nextTaskID (every EnqueueIssue) and nextEventID (every InsertEvent). processNATSTask Naks on error so NATS redelivers forever.\n\nReproduced: internal/nell/counter_repro_test.go - open, insert, close, reopen, insert -\u003e ErrConflict in 7ms with no daemon/NATS/forge.\n\nSECOND DEFECT: isInternalID exists to exclude records from replication, so the two carina instances never converge their counters and would allocate COLLIDING task IDs. Masked only because allocation currently fails outright.\n\nFIX: move the keys out of the reserved namespace (counter:task_id / counter:event_id) AND migrate on open - the old doc is readable (only Put fails), and its next_id is load-bearing because restarting at 1 would reissue live task IDs. Also teach isMetaKey (adapter.go:803) to skip the new prefix so scans do not parse a counter as a task.\n\nREJECTED: stripping _rev before Put is one line and works, but leaves the prefix squat, leaves counters unreplicated, and turns a loud failure into silent last-write-wins.\n\nFull writeup: docs/incident-nelldb-counter-conflict.md","status":"closed","priority":0,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T06:38:32Z","created_by":"Sam Catlow","updated_at":"2026-08-05T07:20:40Z","started_at":"2026-08-05T07:02:30Z","closed_at":"2026-08-05T07:20:40Z","close_reason":"Duplicate of archie-core-7ma, which has the sharper diagnosis (regression from 44f914c's v0.2.5-\u003ev0.3.0 bump, not a long-standing prefix squat). Fix landed under 7ma.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-cz8","title":"fix(gateway): /compress destroys message identity, breaking dedup permanently","description":"applyCompress (session_commands.go:561-573) rebuilds retained head/tail turns as bare Message{From, Text}, dropping MessageID, SourceID and At. newMessageID with an empty SourceID returns a random UUID, so every protected message is deleted and re-inserted under a new identity with source_id NULL and _ts reset to now.\n\nCONFIRMED by two independent reviewers, executed on BOTH backends. Before compress, redelivering tg-59 is a correct no-op (60 stays 60). After compress the same redelivery duplicates (24 -\u003e 25). So archie-core-963's whole guarantee survives only until the first /compress -- after that, a Telegram 24h backlog replay on restart appends every surviving message a second time.\n\nAlso violates messaging-and-work-intake.md:88-90 (immutable application-generated MessageID) and 112-114 (immutable records), and dangles any branch-point correlation to the old IDs.\n\nBlocks archie-core-963 and archie-core-0ua.","status":"closed","priority":0,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-03T16:00:51Z","created_by":"Sam Catlow","updated_at":"2026-08-04T12:25:25Z","started_at":"2026-08-03T16:13:11Z","closed_at":"2026-08-04T12:25:25Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-8u8","title":"feat(gateway): migrate canonical session/message store to SQLite","description":"docs/architecture/messaging-and-work-intake.md:107 requires the canonical session and message implementation to supply durable SQLite round trips. The current store is NellDB-backed.\n\nScope is the SETTLED parts of the messaging architecture only:\n- SQLite persistence (modernc.org/sqlite; FTS5 verified available at 3.53.3, no CGo)\n- application-generated canonical MessageID, platform IDs as correlation only (doc 88-90)\n- immutable message records (doc 112-114)\n- append-only linear sequence per conversation (doc 128)\n- real transactions for ReplaceMessages and Delete\n\nExplicitly OUT of scope: the rich typed-content / tool-call / tool-result model and delivery-attempt semantics. docs/architecture/messaging-and-work-intake.md:273-284 lists the canonical inbound message model, source-correlation model, and outbound delivery/retry/dedup semantics as DECISIONS STILL REQUIRED, so they are not specified enough to implement. That work belongs to archie-core-abg.16.\n\nDecision by Sam 2026-08-03 after the third review surfaced that the NellDB-vs-SQLite question was already settled by the architecture docs.","notes":"SQLite SessionStore implemented and verified 2026-08-03. Not yet wired into production.\n\nAdded (no existing production file touched):\n- internal/gateway/session_store_sqlite.go -- SessionStore on modernc.org/sqlite. Real sql.Tx for ReplaceMessages and Delete, which is the actual reason for the migration: /compress gets genuine atomicity instead of the write-then-delete approximation the NellDB path needs. FTS5 external-content index (content='messages', content_rowid='id') kept in sync by AFTER INSERT/UPDATE/DELETE triggers, so sync is enforced by the schema and no Go code path can forget it.\n- internal/gateway/sessionstore_conformance_test.go -- runSessionStoreSuite(t, newStore), the backend-agnostic contract.\n- Conformance hooks for both backends.\n\nVERIFIED, not taken on trust:\n- 19 identical subtest groups pass against BOTH backends. The suite is the migration gate.\n- FTS index does not drift: search and count stay equal through delete (5-\u003e3), replace (-\u003e1) and session delete (-\u003e0); no cross-session leak.\n- FTS5 syntax injection neutralised: 'text:hello', '\"unbalanced', 'NEAR(a b)', '*', 'needle OR elsewhere' all return 0 hits with no error, confirming terms are escaped phrases AND'ed rather than operators.\n\nBehavioural differences from NellDB, both improvements:\n- MessagePage.Truncated is always false. SQLite gives an exact COUNT(*), so the MaxTextSearchLimit ceiling that field exists to describe does not apply.\n- SourceID is persisted and round-trips; the NellDB path derives the canonical ID from it but never stores it.\n\nCleanup: the two agents ran in parallel, so the SQLite implementation shipped 22 standalone tests written before the suite existed. 18 duplicated suite coverage and were removed (701 -\u003e 170 lines); the 4 kept are genuinely SQLite-specific (transaction atomicity, Truncated semantics, error paths, file creation).\n\ntask check clean, golangci-lint ./internal/gateway/... 0 issues, -race clean.\n\nREMAINING: wire cmd/archied over (config switch), decide the NellDB path's retirement, adversarial review of the combined diff.","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-03T10:03:05Z","created_by":"Sam Catlow","updated_at":"2026-08-03T11:54:41Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-0ua","title":"fix(gateway): make /compress failure-safe","description":"applyCompress swallows MessageCount and DeleteRecentMessages errors (allCount, _ := and _, _ =) then deletes all messages BEFORE saving the compressed replacement. A crash or error between the two loses the session's entire history unrecoverably. Add a store-level ReplaceMessages that saves first and deletes the previously-listed IDs after, so the failure mode is recoverable duplicates rather than total loss.","notes":"ADVERSARIAL PASS CLEARED 2026-08-04. All blockers fixed and committed:\n- archie-core-8k8 (bare /compress could never apply, so this failure-safe path was unreachable) -\u003e cf74d9c\n- archie-core-6e0 (mid-compress message destroyed) -\u003e 3dd42a5, which changed ReplaceMessages to take the superseded set from the caller\n- archie-core-cz8 (identity) -\u003e cf74d9c\nThe core claim held under probing: write-then-delete on both backends, no record deleted that was just written, an injected failure leaves the full history with the error propagated.","status":"closed","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-03T09:25:26Z","created_by":"Sam Catlow","updated_at":"2026-08-04T12:48:08Z","closed_at":"2026-08-04T12:48:08Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
@@ -58,6 +59,11 @@
|
||||
{"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"closed","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-28T17:04:41Z","closed_at":"2026-07-28T17:04:41Z","close_reason":"Superseded by merged work: all 32 children complete (32/32, bd flags it 'eligible for close'). MemoryProvider interface, built-in file-backed memory, MemoryManager, scrubber, drain and threat scanning all landed in internal/memory. Nothing left in scope.","dependencies":[{"issue_id":"archie-core-abg.18","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:22Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16","title":"[EPIC] Gateway: rich message model, adapter lifecycle, session management","description":"Foundational gateway infrastructure to match Hermes parity. Three interdependent pieces:\\n\\n1. **Message model**: Replace the 3-field Message struct with a rich MessageEvent (MessageType enum: text/photo/video/audio/voice/document/sticker/command, media_urls, reply_to context, metadata dict, source). This is the wire type every adapter produces.\\n\\n2. **Adapter lifecycle**: Replace the 3-method Gateway interface with a BasePlatformAdapter interface: connect()/disconnect()/send() as required methods, plus optional overrides for typing indicators, edit/delete, image/voice/video/document send, interactive UX (clarify buttons, approval dialogs). Capability flags (supports_code_blocks, splits_long_messages, supports_async_delivery).\\n\\n3. **Session management**: SessionSource struct (platform, chat_id, chat_type, user_id, thread_id, guild_id, profile), AsyncSessionStore for persistent session storage, SessionContext for system prompt injection.\\n\\nAll three blocks together enable adding new platforms as plugins without touching core gateway code.\\n\\nRef: docs/prds/hermes-gap-analysis.md sections 1-2","acceptance_criteria":"New adapters can be added by implementing a Go interface with connect/disconnect/send + optional media methods. Messages carry full metadata through the pipeline. Sessions persist across gateway restarts.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:21Z","dependencies":[{"issue_id":"archie-core-abg.16","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-jfg","title":"Spawned archie-agent containers not on daemon's docker network — can't reach NATS","description":"Root cause of 'agent still failing on the server': archied's container.Pool.Acquire creates archie-agent containers via the Docker SDK with no NetworkMode set, so Docker attaches them to the default bridge network. archied and nats run on the compose-created 'archie-core_default' network instead, so the spawned container's hostname resolution for 'nats' (from NATS_URL=nats://nats:4222) fails and archie-agent can't connect. Confirmed on carina host logs: archied logs show repeating 'taskrun request failed err=\"nats: no responders available for request\"' for every task, containers created and destroyed within ~1.5s (consistent with archie-agent's NATS client failing fast). Fixed by detecting the daemon's own container's network in NewPool (selfNetwork, via ContainerInspect on os.Hostname()) and setting HostConfig.NetworkMode on spawned containers to match.","status":"closed","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:10:26Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:04:34Z","closed_at":"2026-07-25T13:04:34Z","close_reason":"Fix already implemented and verified: selfNetwork() in internal/container/pool.go detects the daemon's own container network via ContainerInspect(os.Hostname()) and Acquire() sets HostConfig.NetworkMode to match, so spawned archie-agent containers join the same compose network as nats. Build and internal/container tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-7ma","title":"Daemon: every task/event write fails with 'sdk: revision conflict' after NellDB v0.3.0 bump — counter RMW permanently broken","description":"## Symptom (observed 2026-08-05, task dev session)\n\n- Every 1m poll logs `issue queued` for the same open issue (sam/archie-core#8) again.\n- Every attempt logs `event sink insert failed: err=\"sdk: revision conflict\"` (cmd/archied/main.go:373, the event-sink goroutine calling st.InsertEvent).\n- The daemon's own task consumer logs `nats enqueue failed: err=\"sdk: revision conflict\"` (internal/daemon/daemon.go:599, calling Store.EnqueueIssue) and NAKs; JetStream redelivers to max-deliver 3 (triples of errors every ~2 min in the log).\n- The task doc is never persisted, so the enqueue dedup check always passes and the poll re-queues forever. Work never reaches the agent; dashboard shows a stuck/no-op task.\n\n## Exact cause\n\nCommit 44f914c bumped github.com/samcharles93/NellDB v0.2.5 -\u003e v0.3.0 touching only go.mod/go.sum. v0.3.0 changed the DocDB rev-cache rebuild:\n\n- v0.2.5 sdk/docdb.go reindex() indexed EVERY record by rec.ID, including Archie's meta:task_id_counter / meta:event_id_counter docs.\n- v0.3.0 sdk/docdb.go reindex() skips any id where isInternalID() is true (sdk/replicate.go:841: id[:5] == \"meta:\"), intended only for the SDK's own meta:clock/meta:vector bookkeeping but prefix-matching Archie's counter docs too.\n- v0.3.0 putIn (sdk/docdb.go:208-216) keeps the same conflict rule as v0.2.5: incomingRev != \"\" \u0026\u0026 !exists -\u003e sdk.ErrConflict.\n\nArchie's Adapter.nextCounter (internal/nell/adapter.go:957) is a Get -\u003e mutate -\u003e Put RMW that supplies the _rev returned by Get (joinDoc copies the payload, which putIn re-stamps with _rev). After any restart the counter docs are present in the log but absent from the rev cache, so exists=false and every counter Put conflicts. The counter doc can never be written again, so the cache is never repopulated — the failure is permanent for the lifetime of the DB, every process run, from the first poll.\n\nRepro (standalone, module cache, v0.3.0): open log, Put meta:task_id_counter, close, reopen, Get (rev e.g. \"1-69bfa51d...\"), Put with that rev -\u003e \"sdk: revision conflict\". First run of a fresh DB succeeds (empty-rev init Put is allowed); every subsequent process restart fails.\n\nWhy tests are green: OpenMemory/fresh-log tests initialize the counter via empty-rev Put within the same process; TestPersistenceAcrossRestart reopens a real log but only reads (TaskByIssue) and never exercises the counter RMW after reopen. The production path (restart an existing log, then enqueue) is untested.\n\n## Evidence\n\n- go.mod: github.com/samcharles93/NellDB v0.3.0 (no replace).\n- git show 44f914c --stat: go.mod, go.sum, .gitignore only; internal/nell/ untouched since.\n- Module cache diff !nell!d!b@v0.2.5 vs @v0.3.0: sdk/docdb.go reindex()/putIn(), sdk/replicate.go isInternalID.\n- /tmp/nell-repro: deterministic ErrConflict on counter RMW after reopen.\n\n## Fix direction\n\nOptions, in order of preference: (1) pin back to v0.2.5 (verified-2026-07-28 semantics) until adapter is migrated; (2) stop supplying _rev in nextCounter (drop rev from the RMW doc before Put — v0.3.0 continues the chain from the cached rev when incomingRev == \"\"), but that breaks the MVCC chain for the counter when the cache lacks it; (3) upstream: isInternalID should match exact SDK ids (meta:clock, meta:vector), not the meta: prefix, or reindex should index meta docs. Any fix must add a red test: open persisted log, EnqueueIssue, reopen, EnqueueIssue again -\u003e no conflict.","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-05T06:37:35Z","created_by":"Sam Catlow","updated_at":"2026-08-05T07:20:51Z","closed_at":"2026-08-05T07:20:51Z","close_reason":"Fixed forward on v0.3.0 (no pin-back; sdk.MessageRange is v0.3.0-only so a revert would drag the session/message store with it).\n\ninternal/nell/adapter.go:\n- Counters moved off the SDK-reserved prefix: meta:task_id_counter -\u003e counter:task_id, meta:event_id_counter -\u003e counter:event_id.\n- migrateCounters() seeds the new keys from the old docs at open. The old doc is readable (only Put fails) and its next_id is load-bearing: restarting at 1 would reissue IDs belonging to live tasks. Old doc left in place; removing it is the op that cannot succeed. Migration failure is now fatal at OpenStore rather than silently starting a fresh sequence.\n- isMetaKey -\u003e isReservedKey. Counter ids matched EXACTLY, not by prefix: task keys are owner:repo:number, so a counter: prefix rule would black-hole every task in a repo owned by 'counter' (enqueue succeeds, then invisible to ClaimNext/Tasks/StatusCounts forever).\n- EnqueueIssue now persists identity, which it previously accepted and silently dropped -- every forge-polled task was unattributed, diverging fromLine truncated
|
||||
{"_type":"issue","id":"archie-core-abg.17.46","title":"feat(gateway): task_list and task_spawn chat tools","description":"/spawn, /approve and /cancel are slash commands only a human types (internal/gateway/gateway.go:299-401), so 'what are you working on?' has no tool path, even though TaskCreator/TaskController (internal/gateway/tasks.go) are one import away.\n\ninternal/gateway/tasks.go gains a narrow read interface chatTaskLister (ListChatTasks(ctx, identity, limit) ([]ChatTaskSummary, error)), keeping gateway independent of internal/store; the daemon adapts store.Store.Tasks.\n\ninternal/gateway/task_tools.go (new): TaskTools(lister, creator, identity) returning task_list and task_spawn, both bound to the calling gateway's identity so the model never supplies it.\n\ntask_approve and task_cancel are deliberately excluded: waiting_human is the one point in the lifecycle where a person must act and /approve is that gate. Chat input is an untrusted path (a forge issue body or inbound email quoted into a turn is model-visible text), so a tool that approves Archie's own work removes the only human checkpoint. Add behind an operator flag defaulting to off if wanted later.\n\nWired into chatGenerateOptions, merged over the registry-built set.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-05T04:23:55Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:23:55Z","dependencies":[{"issue_id":"archie-core-abg.17.46","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-08-05T14:23:55Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.45","title":"feat(tools): web_fetch tool with dial-time SSRF protection","description":"Archie has no web access of any kind and no MCP server configured to substitute, so it cannot open a URL pasted into chat.\n\nNew package internal/tools/webfetch, registered directly in cmd/archied/main.go beside skill_activate.\n\nSchema: url (required), raw (bool, skip HTML extraction).\n\n- http/https scheme allowlist.\n- SSRF protection in DialContext, NOT as a pre-flight URL check: resolve the host, reject loopback/private/link-local/unspecified/multicast, then dial the vetted IP. A pre-flight URL check leaves a DNS-rebinding hole, and this daemon runs on a host with the Docker socket and NATS reachable on 172.19.0.1.\n- CheckRedirect caps hops and re-applies the scheme check.\n- Body capped by io.LimitReader; result then capped by the per-tool limit.\n- text/html -\u003e readable text via golang.org/x/net/html; text/*, json, xml as-is; anything else an error naming content type and size.\n- Non-2xx returns status plus a short excerpt.\n\nConfig [tools.web_fetch]: enabled, timeout, max_bytes, allow_private_networks (default false). Defaults via configuration.applyDefaults.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-05T04:23:47Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:23:47Z","dependencies":[{"issue_id":"archie-core-abg.17.45","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-08-05T14:23:46Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.20","title":"Fix Web Chat nil update service panic","description":"Fix the typed-nil *releaseupdate.Service injected into ChatUpdateService when update checking is unconfigured. Make the Web Chat update endpoints return a controlled not-configured response and add service nil-receiver safety as needed. Preserve the regression test in archie-core-3cf.19 and run focused tests plus task check.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T01:50:33Z","created_by":"Sam Catlow","updated_at":"2026-08-05T01:52:33Z","started_at":"2026-08-05T01:50:34Z","closed_at":"2026-08-05T01:52:33Z","close_reason":"Fixed typed-nil update service handling in Web Chat and releaseupdate, added nil-service coverage, and passed affected-package tests, race tests, vet, and builds. Full task check remains blocked by unrelated internal/tools/builtin/TestFindFallback_CancelledWalkReportsError.","dependencies":[{"issue_id":"archie-core-3cf.20","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T11:50:33Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.19","title":"Add regression test for nil Web Chat update service","description":"The Web Chat update endpoint receives a typed-nil *releaseupdate.Service through ChatUpdateService when update checking is unconfigured. Add a regression test proving the endpoint returns a controlled not-configured response instead of panicking. Do not implement the fix in this task.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T01:46:03Z","created_by":"Sam Catlow","updated_at":"2026-08-05T01:46:36Z","started_at":"2026-08-05T01:46:07Z","closed_at":"2026-08-05T01:46:36Z","close_reason":"Added typed-nil Web Chat update endpoint regression test; it currently fails with the observed nil-pointer panic as intended.","dependencies":[{"issue_id":"archie-core-3cf.19","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T11:46:02Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.12","title":"Web Chat: revalidate update snapshot before installation","description":"Make the Web update approval path match Telegram by requiring the displayed snapshot and rechecking available component versions immediately before installation.","design":"Export the existing releaseupdate available-version comparison instead of duplicating it. Keep the existing in-progress mutex and progress response.","acceptance_criteria":"Web install requests include the displayed snapshot; the server rejects changed or missing snapshots without installing; unchanged snapshots install once; the shared comparison logic is tested and used by Telegram and Web.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:37:52Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:40:48Z","started_at":"2026-08-05T00:37:53Z","closed_at":"2026-08-05T00:40:48Z","close_reason":"Web update installation now requires and revalidates the displayed snapshot before installing; shared releaseupdate.SameAvailable comparison is used by Web and Telegram. Added stale/unchanged API tests and Playwright request-body verification. Full task check passes.","dependencies":[{"issue_id":"archie-core-3cf.12","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:37:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-5oa","title":"Disable automatic forge comments and state labels","description":"Remove automatic plan/progress/retry/dead/state-label noise from normal execution. Preserve internal logs/events and retain only comments explicitly required by an operator decision flow, exposed through messaging or Web UI.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T15:08:02Z","created_by":"Sam Catlow","updated_at":"2026-08-04T15:28:28Z","started_at":"2026-08-04T15:08:20Z","closed_at":"2026-08-04T15:28:28Z","close_reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass.","dependencies":[{"issue_id":"archie-core-5oa","depends_on_id":"archie-core-hiy","type":"parent-child","created_at":"2026-08-05T01:08:12Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-g4c","title":"Link pushed task branch to source issue before opening PR","description":"After the task branch is successfully pushed, call the forge branch-link operation for the source issue, then create the PR without relying on a PR comment or Closes directive to associate it. Propagate link failures and cover Gitea plus forge RPC behavior.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T15:08:01Z","created_by":"Sam Catlow","updated_at":"2026-08-04T15:28:28Z","started_at":"2026-08-04T15:08:19Z","closed_at":"2026-08-04T15:28:28Z","close_reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass.","dependencies":[{"issue_id":"archie-core-g4c","depends_on_id":"archie-core-hiy","type":"parent-child","created_at":"2026-08-05T01:08:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
@@ -88,19 +94,19 @@
|
||||
{"_type":"issue","id":"archie-core-ky6","title":"One optional MCP provider failing takes down the whole daemon","description":"internal/tools/provider/provider.go Start() is atomic by design -- 'Any failure rolls the complete family back' -- so a single failing provider unregisters every other provider including the builtins, capabilityHost.Start returns the error, and cmd/archied/main.go:655 exits 1. Under compose restart or systemd Restart=on-failure that is a crash loop. Observed 2026-07-30 on carina: mcp.desktop-commander could not start (missing unzip in the runtime image, fixed in 455fd6f) and archied restarted continuously, losing chat, the gateway and every builtin tool over one third-party npm package.\\n\\nAtomicity is correct for a provider the daemon requires. It is wrong for an external MCP server pulled from a registry at runtime, which is exactly the category that should be allowed to be absent -- the same reasoning applied to the forge in 518a1a0, where a missing credential now disables the capability rather than the daemon.","design":"Needs a required/optional distinction on the registration or manifest, which does not exist today. Keep the all-or-nothing path for required providers; the atomic batch semantics for tool visibility (tools appear only after Start and Discover both succeed) should hold per-provider either way. Relates to the plugin engine rule in ARCHITECTURE.md: failure isolation is explicitly the owning manager's responsibility.","acceptance_criteria":"A provider can be declared optional. An optional provider that fails to start or discover is logged, excluded from the running set, and does not roll back the family or stop the daemon. A required provider keeps today's atomic rollback. Provider health reflects the degraded state so the failure is visible rather than silent. Regression test starts a family containing one failing optional provider and asserts the other providers' tools remain registered and Start returns nil.","notes":"Fixed 2026-08-04 in a8c9483.\n\nRegistry.RegisterOptional marks a provider the daemon can run without; Register is unchanged and keeps atomic rollback. The distinction lives on the registration rather than the manifest: required-vs-optional is a deployment fact, not a property of the code, and keeping it out of plugin.Manifest preserves the metadata-only rule.\n\nAn optional provider failing Start, Discover or index registration is stopped (so a half-started child process is not leaked), excluded from the running set, and recorded in Skipped(). The family carries on. Per-provider atomic tool visibility still holds either way: tools appear only after Start and Discover both succeed.\n\nDependency cascade: a provider whose dependency was skipped cannot run. Optional dependents are skipped with the reason; a required dependent is a hard failure, since it declared it cannot work without something now absent.\n\nVisibility: Health returns degraded naming each excluded provider and its cause, Skipped() exposes the set programmatically, and cmd/archied logs one error line per exclusion after capability host startup.\n\nmain.go now registers every [[tools.mcp_servers]] entry with RegisterOptional, and a registration error warns and continues rather than exiting.\n\nVerified: TestCarinaScenarioThroughCapabilityHost drives the real plugin.Host, the path main.go calls. Registered as required it fails with 'start plugin module \"archie.tools\": start tool provider \"mcp.desktop-commander\": npx exec: unzip: not found' -- verbatim the crash loop. As optional the host starts, read/shell/edit/memory_edit stay registered, and health is degraded carrying the cause.\n\nCLAUDE.md's per-package trap note updated; it documented the old hard-failure behaviour.\n\nNOT DONE, deliberately: there is no per-server required/optional switch in config. Every MCP server is optional. An operator who genuinely depends on one gets a degraded daemon and an error log rather than a refusal to start, which matches the forge and container precedent. Add a config knob only if a real deployment needs it.","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-30T06:49:26Z","created_by":"Sam Catlow","updated_at":"2026-08-04T13:33:08Z","closed_at":"2026-08-04T13:33:08Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-qa4.5","title":"Phase 5: the 56 lint findings Phase 4 left behind","description":"Discovered as a side effect of the 6d4e0be audit (archie-core-ifi), not as its\ngoal: running golangci-lint over the two packages I had touched showed findings\nin files nobody had flagged, so I ran it repo-wide.\n\nAll four children of archie-core-qa4 are closed and the epic reports \"4/4\ncomplete (100%) -- eligible for close\", but `golangci-lint run ./...` still\nreports 56 issues. The epic must not be closed on that prompt; its own\ndescription says the gate is RED until it closes, so closing it early declares\na green gate that does not exist.\n\nBreakdown: noctx 11, gocognit 11, gocritic 6, errcheck 6, nilerr 4, recvcheck 3,\nnestif 3, godox 3, sloglint 2, predeclared 2, funlen 2, gofumpt 1, cyclop 1,\nstaticcheck 0 (the one hit, configtemplate.go:6, is fixed).\n\nThe gocognit remainder is concentrated in exactly the functions Phase 4 named as\ndeferred -- cmd/archied/main.go run (106, the description predicted \"108-\u003e30\nremaining\" and it did not land), internal/workflow AgentStage.Stage (68),\nFeasibility and TDD (funlen), cmd/archie-agent startMCPProviders (45) -- plus\nthe whole of internal/tools/builtin: grepFallback 58, runFindGoFallback 57,\nmakeReadExecutor 56, makeGrepExecutor 41, makeShellExecutor 40, makeWriteExecutor\n38, suggestPaths 36. tomlwrite.Apply (82) is new, uncommitted-until-7fab597 code.\n\nREAD archie-core-qa4's notes before starting. Both known behaviour regressions\nfrom this epic came out of structural extraction, and every remaining gocognit\nsite is a structural extraction waiting to happen. The nilerr findings in\ngrep.go are not noise either -- see archie-core-ts9, where the same swallow in\nfind.go is a live false-negative bug. Fixing nilerr by \"returning the error\"\nwithout deciding what the caller does with it will change tool behaviour.","acceptance_criteria":"golangci-lint run ./... reports 0 issues, or every remaining finding has an explicit nolint with a reason. Each structural extraction lands with a behavioural test for the function it splits, per the discipline recorded in archie-core-qa4's notes.","status":"open","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:26:57Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:26:57Z","dependencies":[{"issue_id":"archie-core-qa4.5","depends_on_id":"archie-core-qa4","type":"parent-child","created_at":"2026-07-30T02:26:57Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-qa4.5","depends_on_id":"archie-core-ts9","type":"blocks","created_at":"2026-07-30T02:27:02Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-qa4.5","depends_on_id":"archie-core-ifi","type":"discovered-from","created_at":"2026-07-30T02:26:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-0d6","title":"[BUG] /model \u003cname\u003e asked the router for a doubled model name","description":"The nestif extraction in 651de0a pulled --provider parsing out of parseModelRest into extractProviderFlag, which took the modelParts slice by pointer and appended every non-provider field to it. The caller's own loop then appended the same fields again, so every field of the model name was duplicated: '/model gpt-5.6' resolved to 'gpt-5.6 gpt-5.6' and SetActiveModel rejected it as an unknown model. '/model gpt-5.6 --provider openai' was worse -- the space-separated provider value was no longer consumed with its flag, giving 'gpt-5.6 gpt-5.6 openai'. Direct model switching over Telegram was broken for anything but a bare --refresh or a provider-only switch. Found while auditing 6d4e0be for archie-core-ifi: the naked return in the same function could not be regression-tested until the function produced correct values.","design":"Two ways to fix the double append were available. Rejected: keep the helper\nsignature and delete the caller's default-branch append. That restores correct\noutput but leaves the shape intact -- a helper holding a pointer to the\ncaller's accumulator, with two loops over the same fields -- so the next person\nwho adds a field type has the same trap waiting. It also does not fix the\nspace-separated provider value, because the helper returns early on the first\n--provider and never sees the fields after it.\n\nChosen: splitProviderFlag returns (provider, remaining) and is the sole\naccumulator. One loop owns the fields, and there is no shared slice to append\nto twice. The index loop is kept deliberately -- i++ after reading a\nspace-separated value is what removes it with its flag, and converting that to\na range loop is precisely what 651de0a did wrong.\n\nLast --provider wins if repeated, matching the pre-651de0a behaviour rather\nthan the buggy helper's first-wins. Not worth a flag: /model does not document\nrepeating it.","acceptance_criteria":"parseModelRest returns the model name exactly once for bare names, scope flags, and both --provider spellings, with a regression test asserting field count rather than string equality.","notes":"Fixed by making splitProviderFlag the sole accumulator of surviving fields and returning them, so the shared-slice shape that allowed the double append is structurally impossible. Tests: TestParseModelRestDoesNotDoubleTheModelName, TestParseModelRestReturnsDeclaredValuesInOrder.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:18:46Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:26:09Z","closed_at":"2026-07-29T16:19:23Z","dependencies":[{"issue_id":"archie-core-0d6","depends_on_id":"archie-core-ifi","type":"discovered-from","created_at":"2026-07-30T02:18:46Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-ewk.1","title":"Export configuration.Validate for archied setup to call","description":"The ewk epic's acceptance criteria (and archie-core-cbk's, by inheritance) require: \"Every config it writes passes configuration.Validate, verified by a test that runs setup non-interactively and validates the output.\" That identifier does not exist. internal/infrastructure/configuration/validate.go defines only an unexported validate(cfg *config.Config) error, called from one place: loader.go:178 inside Loader.Load's own decode-then-validate sequence. There is no way for code outside the configuration package -- e.g. `archied setup` after it builds a config.Config in memory but before writing it to disk -- to run the same validation.\n\nDiscovered while implementing archie-core-rs9 (TOML write strategy). Not fixed there: rs9's scope was the text-patching mechanism, not wiring setup's actual validation step, and exporting validate() is really part of cbk's job (the thing that needs to call it).","acceptance_criteria":"configuration package exposes a callable that runs the same checks as the current unexported validate() against a config.Config value in memory (either export validate itself, or add a thin Validate(cfg *config.Config) error wrapper -- whichever fits the package's existing exported-surface conventions). Loader.Load continues to use it internally with no behavior change. A test outside the package (e.g. in cbk's setup tests) can call it directly without going through file I/O.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-29T16:18:36Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:18:36Z","dependencies":[{"issue_id":"archie-core-ewk.1","depends_on_id":"archie-core-ewk","type":"parent-child","created_at":"2026-07-30T02:18:36Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-ewk.1","title":"Export configuration.Validate for archied setup to call","description":"The ewk epic's acceptance criteria (and archie-core-cbk's, by inheritance) require: \"Every config it writes passes configuration.Validate, verified by a test that runs setup non-interactively and validates the output.\" That identifier does not exist. internal/infrastructure/configuration/validate.go defines only an unexported validate(cfg *config.Config) error, called from one place: loader.go:178 inside Loader.Load's own decode-then-validate sequence. There is no way for code outside the configuration package -- e.g. `archied setup` after it builds a config.Config in memory but before writing it to disk -- to run the same validation.\n\nDiscovered while implementing archie-core-rs9 (TOML write strategy). Not fixed there: rs9's scope was the text-patching mechanism, not wiring setup's actual validation step, and exporting validate() is really part of cbk's job (the thing that needs to call it).","acceptance_criteria":"configuration package exposes a callable that runs the same checks as the current unexported validate() against a config.Config value in memory (either export validate itself, or add a thin Validate(cfg *config.Config) error wrapper -- whichever fits the package's existing exported-surface conventions). Loader.Load continues to use it internally with no behavior change. A test outside the package (e.g. in cbk's setup tests) can call it directly without going through file I/O.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:18:36Z","created_by":"Sam Catlow","updated_at":"2026-08-05T02:44:50Z","started_at":"2026-08-05T02:43:36Z","closed_at":"2026-08-05T02:44:50Z","close_reason":"Exported Validate(cfg *config.Config) error wrapping the unexported validate; Loader.finalize now calls it. Documented that it doesn't apply defaults, so setup should render+reload through a Loader rather than call Validate on a hand-built config directly. 82fd015.","dependencies":[{"issue_id":"archie-core-ewk.1","depends_on_id":"archie-core-ewk","type":"parent-child","created_at":"2026-07-30T02:18:36Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-1y6","title":"SOUL cannot override the prompt invariants","description":"Enforce the boundary that makes SOUL safe to hand to users: it supplies identity and style, and cannot reach the instruction hierarchy, core rules, tool inventory or env block.","acceptance_criteria":"A test renders a hostile SOUL that attempts to countermand core_rules and asserts the invariant sections are still present and intact. The boundary is documented where the layering rule already lives so the next person editing the template does not quietly relax it.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:56Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:09:56Z","dependencies":[{"issue_id":"archie-core-1y6","depends_on_id":"archie-core-4gv","type":"parent-child","created_at":"2026-07-30T02:09:56Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-z8c","title":"SOUL loader with per-turn reload and default fallback","description":"Load the SOUL file from the config dir into the identity slot of the rendered prompt, re-reading it per turn so an edit takes effect on the next message with no restart.","acceptance_criteria":"SOUL content is rendered into the identity slot ahead of the invariant sections. An absent, empty or unreadable SOUL falls back to the shipped default identity rather than rendering nothing. Editing the file changes the next turn's prompt with no restart. A read error is logged once and degrades to the default; it never fails the turn. Size is bounded so an oversized SOUL cannot crowd out the rules.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:56Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:09:56Z","dependencies":[{"issue_id":"archie-core-z8c","depends_on_id":"archie-core-4gv","type":"parent-child","created_at":"2026-07-30T02:09:55Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-4gv","title":"[EPIC] SOUL file: user-authored agent identity","description":"Move Archie's identity and tone out of compiled Go constants and into a user-editable SOUL file. Root cause of a real defect on 2026-07-29: heyarchie answered 'Hey are you there?' with 'I'm here. What do you need?', which reads as demanding the user justify getting in touch. The fix required editing DefaultPersonas() in internal/gateway/persona.go and rebuilding -- personality is not tunable without a compile. Modelled on Hermes (SOUL.md occupies the identity slot in the stable tier, DEFAULT_AGENT_IDENTITY is the fallback when absent, re-read per message so no restart is needed) and openclaw, which injects SOUL.md alongside AGENTS.md.","design":"THE BOUNDARY IS THE POINT. The existing layering rule (recorded in the chat-system-prompt-design memory) is that PersonaRegistry is the style layer only and rules live in the template, so switching persona cannot strip the agent's rules or tool inventory. SOUL inherits exactly that constraint: it owns identity, name, register and warmth, and must not be able to touch core_rules -- otherwise 'be terse' in a SOUL silently disarms the no-fabrication rules. Steal from Hermes: is_legacy_template_soul upgrades untouched scaffolding in place but never overwrites a SOUL the user actually edited. This is the first of the three identity layers agreed with Sam on 2026-07-30: invariants (template, nobody edits at runtime) / SOUL (user-authored) / representation (curator-derived, proposes only).","acceptance_criteria":"A user can name their agent and define its personality by editing a file, with no rebuild and no restart. An absent or empty SOUL falls back to the shipped default identity. SOUL cannot weaken the invariants: \u003cinstruction_precedence\u003e, \u003ccore_rules\u003e, the \u003ctools\u003e block and \u003cenv\u003e stay in the template and remain unreachable from SOUL, enforced by a test. A SOUL the user has customised is never overwritten by an upgrade.","status":"open","priority":1,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:37Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:09:37Z","dependencies":[{"issue_id":"archie-core-4gv","depends_on_id":"archie-core-ewk","type":"related","created_at":"2026-07-30T02:09:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-ifi","title":"Audit the remaining golangci-lint autofix changes in 6d4e0be","description":"Commit 6d4e0be applied a golangci-lint --fix batch across 8 files. One of the eight was a behaviour regression: the errorlint fix in internal/tools/builtin/grep.go rewrote 'if exitErr, ok := err.(*exec.ExitError); ok \u0026\u0026 exitErr.ExitCode() == 1' into 'errors.As(err, \u0026exitErr)' and dropped the exit-code check, so any ripgrep failure (bad pattern, unreadable path) was reported to the model as 'no matches found' -- the agent would state a file contains nothing on the strength of a search that never ran. Fixed in 782510d. The other seven changes were eyeballed as benign (naked return expanded, err != ctx.Err() -\u003e errors.Is) but were never verified individually. A one-in-eight regression rate does not justify trusting the remainder on inspection alone.","acceptance_criteria":"Each remaining changed hunk in 6d4e0be is reviewed against its pre-fix behaviour, specifically for predicates that were narrowed or widened. internal/channels/telegram/model.go, internal/infrastructure/configuration/discovery.go, internal/tools/builtin/find.go, internal/tools/builtin/shell.go and the touched test files are covered. Any behaviour change found gets a regression test in the style of TestGrepReportsSearchFailureRatherThanNoMatches.","notes":"AUDIT COMPLETE. Per-hunk verdicts against pre-fix behaviour:\n\n- telegram/model.go (nakedret expansion): return order matches the declaration, and no defer mutates the results, so the expansion is behaviour-neutral. Two strings and three bools mean a transposed pair would have compiled silently, so it is now pinned by TestParseModelRestReturnsDeclaredValuesInOrder. Writing that test surfaced an unrelated P1 regression from 651de0a -- archie-core-0d6, fixed here.\n- configuration/discovery.go ((path string, yaml bool, ok bool) -\u003e (path string, yaml, ok bool)): type-identical signature reshuffle, no semantic content.\n- tools/builtin/find.go (err != ctx.Err() -\u003e !errors.Is(err, ctx.Err())): behaviour-neutral. Verified on go1.26 that errors.Is(err, nil) is false for non-nil err, so with a live context the new predicate still means err != nil. With a cancelled context the walk returns ctx.Err() unwrapped, so identity and errors.Is agree. The audit did expose that this branch is unreachable in practice and cancellation is reported as 'no matches found' -- pre-existing, filed as archie-core-ts9.\n- tools/builtin/shell.go (err.(*exec.ExitError) -\u003e errors.As): NOT the grep failure. The original had no companion condition to drop -- the exit code is read inside the branch, not used to gate it -- and the ctx.Err() timeout check already runs first. Widening to wrapped ExitErrors is unreachable since cmd.Run returns them unwrapped. The branch had no test at all, so TestShellReportsExitCodeRatherThanAGenericError now covers it.\n- loader_test.go, pluginextract/*.go, secretextract/*.go: blank-line insertions only.\n- read_test.go ((cwd string, params string) -\u003e (cwd, params string)): type-identical.\n- webui_test.go (\"GET\" -\u003e http.MethodGet): same constant value.\n\nOne-in-eight held: the batch itself had exactly the one regression already fixed in 782510d. The lint-driven refactor in 651de0a, however, carried a second regression of the same family, which suggests the review discipline belongs on structural extractions as much as on --fix batches.","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:21Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:19:15Z","closed_at":"2026-07-29T16:19:15Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-cbk","title":"Setup steps: operator, provider, models, forge, chat channel","description":"The archie equivalent of tau's provider+model flow. Steps: (1) operator display name -\u003e [chat].operator; (2) LLM provider -\u003e [providers.\u003cname\u003e] class and api_key_env, with the key value stored via the secret engine; (3) models per role -\u003e [models] triage/planner/builder, plus the optional [chat].models catalog; (4) forge -\u003e github/gitea/none with host and a token reference, explicitly optional now that a missing forge credential only disables the forge; (5) chat channel -\u003e Telegram bot token, optional. bot_user must always be written because validation requires it when no [[identities]] exist.","acceptance_criteria":"Each step is skippable where the underlying setting is optional, and skipping leaves a valid config. Forge selection defaults to none rather than assuming a forge. The token key written into config matches the key the value was stored under, for every forge type -- the exact drift that broke the installer. Local model discovery (Ollama) is offered when available and degrades to free text when not.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T16:02:50Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:02:50Z","dependencies":[{"issue_id":"archie-core-cbk","depends_on_id":"archie-core-ewk.1","type":"blocks","created_at":"2026-07-30T02:18:40Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-cbk","depends_on_id":"archie-core-rs9","type":"blocks","created_at":"2026-07-30T02:02:55Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-cbk","depends_on_id":"archie-core-ewk","type":"parent-child","created_at":"2026-07-30T02:02:50Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-via","title":"SetupPrompter interface and UI-agnostic setup flow","description":"Port tau's split: setup logic lives in a package that takes a SetupPrompter interface; the command layer supplies the terminal implementation. This is what makes setup testable without a TTY.","acceptance_criteria":"Setup logic has no direct terminal dependency and is driven end to end in tests by a fake prompter. The terminal implementation provides a numbered Select and a non-echoing ReadSecret via golang.org/x/term, both cancellable on Ctrl+C via context. No TUI framework is introduced.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T16:02:50Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:02:50Z","dependencies":[{"issue_id":"archie-core-via","depends_on_id":"archie-core-ewk","type":"parent-child","created_at":"2026-07-30T02:02:49Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-cbk","title":"Setup steps: operator, provider, models, forge, chat channel","description":"The archie equivalent of tau's provider+model flow. Steps: (1) operator display name -\u003e [chat].operator; (2) LLM provider -\u003e [providers.\u003cname\u003e] class and api_key_env, with the key value stored via the secret engine; (3) models per role -\u003e [models] triage/planner/builder, plus the optional [chat].models catalog; (4) forge -\u003e github/gitea/none with host and a token reference, explicitly optional now that a missing forge credential only disables the forge; (5) chat channel -\u003e Telegram bot token, optional. bot_user must always be written because validation requires it when no [[identities]] exist.","acceptance_criteria":"Each step is skippable where the underlying setting is optional, and skipping leaves a valid config. Forge selection defaults to none rather than assuming a forge. The token key written into config matches the key the value was stored under, for every forge type -- the exact drift that broke the installer. Local model discovery (Ollama) is offered when available and degrades to free text when not.","status":"closed","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T16:02:50Z","created_by":"Sam Catlow","updated_at":"2026-08-05T02:58:58Z","closed_at":"2026-08-05T02:58:58Z","close_reason":"Implemented Run in internal/infrastructure/configuration/setup: operator, provider, models, forge, chat(telegram) steps, returning tomlwrite edits (not a parallel config.Config). Tested by rendering+loading through a real Loader. Found and fixed two boot-time landmines in config.example.toml along the way ([providers.openai] bws default, [[repos]] placeholder). 56d684a.","dependencies":[{"issue_id":"archie-core-cbk","depends_on_id":"archie-core-ewk.1","type":"blocks","created_at":"2026-07-30T02:18:40Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-cbk","depends_on_id":"archie-core-rs9","type":"blocks","created_at":"2026-07-30T02:02:55Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-cbk","depends_on_id":"archie-core-ewk","type":"parent-child","created_at":"2026-07-30T02:02:50Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-via","title":"SetupPrompter interface and UI-agnostic setup flow","description":"Port tau's split: setup logic lives in a package that takes a SetupPrompter interface; the command layer supplies the terminal implementation. This is what makes setup testable without a TTY.","acceptance_criteria":"Setup logic has no direct terminal dependency and is driven end to end in tests by a fake prompter. The terminal implementation provides a numbered Select and a non-echoing ReadSecret via golang.org/x/term, both cancellable on Ctrl+C via context. No TUI framework is introduced.","status":"closed","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T16:02:50Z","created_by":"Sam Catlow","updated_at":"2026-08-05T02:47:24Z","closed_at":"2026-08-05T02:47:24Z","close_reason":"Defined Prompter (Select/ReadLine/ReadSecret/Confirm, all context-aware) in internal/infrastructure/configuration/setup, and a real TTY-gated implementation in internal/infrastructure/terminalprompt. Construction refuses a non-terminal input with a clear message rather than a degraded fallback. b04733c.","dependencies":[{"issue_id":"archie-core-via","depends_on_id":"archie-core-ewk","type":"parent-child","created_at":"2026-07-30T02:02:49Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-rs9","title":"Decide and implement the TOML write strategy","description":"Settle how setup persists config before any prompting code is written; everything else depends on it. BurntSushi/toml loses comments on re-marshal, and config.example.toml carries substantial inline documentation users are meant to read and edit by hand. Options: (a) generate a fresh commented config from a template on first run and only line-patch specific keys on re-run; (b) full re-marshal and accept losing comments; (c) adopt a comment-preserving TOML editor.","design":"Decision: text-based line patching, not decode/re-marshal, not a comment-preserving TOML AST library (none exist for Go that are safe to depend on).\n\nNew package internal/infrastructure/configuration/tomlwrite:\n- Apply(src []byte, edits []Edit) ([]byte, error): for each {Table, Key, Value} edit, finds an active \"key = value\" line in that table and replaces just the value (preserving indent + trailing inline comment); else finds a commented \"# key = value\" line in that table, uncomments the table header and the line; else appends the key at the end of the table's content (or appends a brand new [table] section at EOF if the table doesn't exist at all, active or commented). Lines not named by an edit are copied through byte-for-byte.\n- Generate(template, edits) is Apply against configtemplate.Example (config.example.toml embedded at the module root via configtemplate.go, since go:embed can't reach outside its own directory tree -- this keeps config.example.toml the single source of truth instead of a second copy, which is exactly the drift bug this epic exists to fix).\n- Value callers pre-render TOML literals; String() and Ref(engine,key) helpers cover the two shapes setup needs (quoted strings, secret.SecretRef inline tables). Deliberately does not import internal/secret -- it edits text, not Go values.\n\nTrade-off: only understands single-line scalar/inline-table values. Does not handle multi-line arrays or [[array-of-tables]] (e.g. [[repos]]) -- those aren't setup's targets and must not be routed through this patcher.\n\nTests (internal/infrastructure/configuration/tomlwrite/tomlwrite_test.go) cover: active-key replace preserving trailing comment, active inline-table replace, commented-table uncomment-one-key-leave-siblings-commented, append into existing active table, append brand-new table, byte-identical-elsewhere on a single edit, byte-identical-elsewhere across two sequential runs (the rs9 acceptance criterion), and a full run against the real config.example.toml verified to decode via BurntSushi/toml and round-trip bot_user/forge.token correctly.\n\n`go build ./...` and `task check` pass clean; no other files touched.","acceptance_criteria":"The chosen strategy is documented with its trade-off. A first run produces a config a human can read and hand-edit afterwards. A second run changing one value leaves every other line, including comments, byte-identical -- asserted by a test. No strategy is adopted that silently discards user edits.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:02:49Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:14:13Z","started_at":"2026-07-29T16:09:23Z","closed_at":"2026-07-29T16:14:13Z","close_reason":"text-based line patcher implemented in internal/infrastructure/configuration/tomlwrite; template embedded via configtemplate.go; tests pass, task check clean","dependencies":[{"issue_id":"archie-core-rs9","depends_on_id":"archie-core-ewk","type":"parent-child","created_at":"2026-07-30T02:02:49Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-ewk","title":"[EPIC] archied setup: interactive first-run configuration","description":"Move config generation out of install.sh and into the daemon as 'archied setup', so the thing that writes config.toml is the same code that reads it. install.sh currently hand-rolls TOML and has already drifted from the schema once: it hardcoded the GitHub token key and the Gitea host, so a Gitea install produced a config naming a token the installer never wrote. Modelled on tau's 'tau setup' (internal/cli/setup.go, internal/app/setup.go), adapted for archie's TOML config and existing secret-reference indirection.","design":"Port from tau: the CLI/app split behind a SetupPrompter interface so business logic is UI-agnostic and testable without a terminal; plain-stdio Select and hidden ReadSecret (golang.org/x/term) racing ctx.Done for Ctrl+C -- no TUI dependency; atomic temp+rename writes. DIVERGENCE FROM TAU: tau surgically patches YAML nodes to preserve comments. archie uses BurntSushi/toml, which does not preserve comments across a decode/encode round trip, so a full re-marshal would destroy config.example.toml's documentation. Decide this explicitly -- see the child issue. Secrets differ too: archie already has secret.SecretRef{engine,key} indirection, so setup writes the reference into TOML and the value into the env engine's store; that is archie's equivalent of tau's config.yaml/auth.yaml split and should be used rather than reinvented.","acceptance_criteria":"install.sh no longer generates config.toml; it invokes archied setup. Setup is idempotent and re-runnable against an existing config without clobbering unrelated settings. Every config it writes passes configuration.Validate, verified by a test that runs setup non-interactively and validates the output. Secrets never reach config.toml or argv: config holds a secret reference, the value goes to the env file at 0600 via atomic write. Prompts for secrets do not echo. A non-TTY invocation without sufficient input fails with a clear message rather than writing a partial config.","status":"open","priority":1,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-29T16:02:28Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:02:28Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-035","title":"Trigger accounting: curator output must not feed its own trigger","description":"Establish the invariant that work a curator produces does not count toward the condition that schedules the next curator run. Honcho hit this directly: their dream scheduler explicitly excludes dreamer output from the observation threshold, noting that counting it would inflate the threshold and create a feedback loop.","acceptance_criteria":"Derived curator output is distinguishable from primary input at the point the trigger is evaluated. A curator that writes memories does not thereby schedule itself again. There is a regression test that would fail if derived output were counted, with the feedback-loop rationale recorded in the test so the guard is not removed as redundant.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-29T15:47:44Z","created_by":"Sam Catlow","updated_at":"2026-07-29T15:47:44Z","dependencies":[{"issue_id":"archie-core-035","depends_on_id":"archie-core-yp9","type":"parent-child","created_at":"2026-07-30T01:47:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-89x","title":"Curator runtime: persistent loop with idle cooldown","description":"Implement the loop that runs a registered curator: continuous operation while work is available, backing off to a configured cooldown when there is nothing to do, waking on new input, and honouring per-curator check-in intervals.","acceptance_criteria":"A curator with pending input runs without waiting for its next interval; an idle curator consumes no meaningful CPU and wakes on new input. Cooldown and check-in interval are configurable per curator. Loop timing is tested with a fake clock, not wall-clock sleeps. Shutdown is clean and bounded: an in-flight curator pass is cancelled via context and the daemon does not block indefinitely on it. A panicking curator is recovered and isolated from other curators and from the agent loop.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T15:47:43Z","created_by":"Sam Catlow","updated_at":"2026-07-29T15:47:43Z","dependencies":[{"issue_id":"archie-core-89x","depends_on_id":"archie-core-yp9","type":"parent-child","created_at":"2026-07-30T01:47:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-rfp","title":"Curator contract, registry, and internal/curator package","description":"Stand up internal/curator as a package in its own right: the typed curator contract, the owning registry that controls registration and discovery, and the definition of a curator's declared shape (check-in interval, tool set, attached memory engine).","acceptance_criteria":"internal/curator owns a typed contract exposing real curator operations plus start/health/stop. A registry controls registration, discovery, and shutdown ordering, and defines failure isolation. Curators receive a narrow typed registrar and only the host services their declared capability requires -- never *daemon.Daemon or an untyped hook map. internal/plugin/architecture_test.go recognises curator as a conforming engine family.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T15:47:42Z","created_by":"Sam Catlow","updated_at":"2026-07-29T15:47:42Z","dependencies":[{"issue_id":"archie-core-rfp","depends_on_id":"archie-core-yp9","type":"parent-child","created_at":"2026-07-30T01:47:42Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-yp9","title":"[EPIC] Curator engine: persistent memory-reasoning agent loops","description":"Introduce curators as their own engine family: long-running agent loops that reason over memory and perform small maintenance tasks, rather than one hardcoded background job. A curator is defined by a check-in interval, a tool set, and (once the memory engine family lands) an attached memory engine. It runs persistently while there is input and backs off to a cooldown when idle. Ship two reference curators -- a skill curator and a persistent-session-memory curator -- so the interface is proven against two consumers rather than designed around one.","design":"Modelled on Honcho's dreamer (/work/clones/honcho/src/dreamer). Two findings from that source worth carrying: (1) the split between a cheap hot-path extractor and an expensive sampled reasoner, so agentic cost is never paid per message; (2) surprisal-based sampling to choose which memories deserve attention, implemented over embeddings via interchangeable strategies including a k-NN graph random walk. Note Archie has no embedding capability today, so any surprisal-style sampling is gated behind adding one.","acceptance_criteria":"Curator is a conforming engine family per ARCHITECTURE.md 'Plugin engine rule (strict)': typed contract, owning registry/manager, start/health/stop, narrow typed host access. Curators are registered and configured declaratively, not hardcoded. The runtime supports persistent operation under load and cooldown when idle, with intervals configurable per curator. Both reference curators run against the shipped defaults. Curator activity is observable: what ran, when, what it changed, and why. A curator failure is isolated and never takes down the daemon or a chat turn.","status":"open","priority":1,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-29T15:47:27Z","created_by":"Sam Catlow","updated_at":"2026-07-29T15:47:27Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-035","title":"Trigger accounting: curator output must not feed its own trigger","description":"Establish the invariant that work a curator produces does not count toward the condition that schedules the next curator run. The scheduler must explicitly exclude derived curator output from the observation threshold: counting it would inflate the threshold and create a feedback loop, so a curator that writes memories must not thereby schedule itself again.","acceptance_criteria":"Derived curator output is distinguishable from primary input at the point the trigger is evaluated. A curator that writes memories does not thereby schedule itself again. There is a regression test that would fail if derived output were counted, with the feedback-loop rationale recorded in the test so the guard is not removed as redundant.","notes":"IMPLEMENTED 2026-08-05 (commit 7372ddf): turn_completed event published from the single responder choke point (makeChatLLMResponder in cmd/archied/telegram_setup.go, shared by telegram + web gateways; redeliveries return earlier and never emit). curator.WakeOnPrimaryInput forwards ONLY primary-input kinds to the runtime as best-effort nudges — curator output (curator_run/action/error, future derived kinds) never reaches the wake path, so derived work cannot feed its own trigger. Regression test TestWakeOnPrimaryInputForwardsOnlyPrimaryKinds carries the feedback-loop rationale in its comment. REMaining: the store-level derived marker (primary-vs-derived distinction at the trigger's store read) lands with gs8 (session-memory curator writes carry a derived marker, per the SummaryMarker precedent). Adversarial review still pending per repo protocol.\nIMPLEMENTED 2026-08-05 (commit 7372ddf): turn_completed event published from the single responder choke point (makeChatLLMResponder in cmd/archied/telegram_setup.go, shared by telegram and web gateways; redeliveries return earlier and never emit). curator.WakeOnPrimaryInput forwards ONLY primary-input kinds to the runtime as best-effort nudges — curator output (curator_run/action/error, future derived kinds) never reaches the wake path, so derived work cannot feed its own trigger. Regression test TestWakeOnPrimaryInputForwardsOnlyPrimaryKinds carries the feedback-loop rationale in its comment. Remaining: the store-level derived marker (distinguishing primary vs derived at the trigger's store read) lands with gs8, following the SummaryMarker precedent. Adversarial review still pending per repo protocol.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-29T15:47:44Z","created_by":"Sam Catlow","updated_at":"2026-08-05T05:00:42Z","dependencies":[{"issue_id":"archie-core-035","depends_on_id":"archie-core-yp9","type":"parent-child","created_at":"2026-07-30T01:47:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-89x","title":"Curator runtime: persistent loop with idle cooldown","description":"Implement the loop that runs a registered curator: continuous operation while work is available, backing off to a configured cooldown when there is nothing to do, waking on new input, and honouring per-curator check-in intervals.","acceptance_criteria":"A curator with pending input runs without waiting for its next interval; an idle curator consumes no meaningful CPU and wakes on new input. Cooldown and check-in interval are configurable per curator. Loop timing is tested with a fake clock, not wall-clock sleeps. Shutdown is clean and bounded: an in-flight curator pass is cancelled via context and the daemon does not block indefinitely on it. A panicking curator is recovered and isolated from other curators and from the agent loop.","notes":"ISOLATION INVARIANT (added 2026-08-05, Sam): curators are PEERS, not dependencies. They run on their own registry-owned loops and consume their own events; a curator must never block, delay, or take down chat turns, agent runs, or the daemon. Wake events ride the in-process events.Bus (mutex fan-out, bounded per-subscriber buffers that DROP on overflow) so a slow curator can never backpressure the chat publisher. WAKE IS A NUDGE, TRIGGER IS TRUTH: wake events are best-effort; the trigger decision is a deterministic read of persisted primary-input state at pass time, so a dropped wake only delays a run to the next check-in and never corrupts trigger accounting (archie-core-035). Per-pass recover(); per-pass budgets (max steps/tokens/timeout); max concurrent passes configurable (default 1) so curators cannot saturate the shared LLM runtime against chat. Registry lifecycle independent of the agent loop; daemon shutdown cancels in-flight passes and waits bounded. Rule of thumb: no code path a curator executes may ever appear on a chat turn's critical path.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T15:47:43Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:27:12Z","dependencies":[{"issue_id":"archie-core-89x","depends_on_id":"archie-core-yp9","type":"parent-child","created_at":"2026-07-30T01:47:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-rfp","title":"Curator contract, registry, and internal/curator package","description":"Stand up internal/curator as a package in its own right: the typed curator contract, the owning registry that controls registration and discovery, and the definition of a curator's declared shape (check-in interval, tool set, attached memory engine).","acceptance_criteria":"internal/curator owns a typed contract exposing real curator operations plus start/health/stop. A registry controls registration, discovery, and shutdown ordering, and defines failure isolation. Curators receive a narrow typed registrar and only the host services their declared capability requires -- never *daemon.Daemon or an untyped hook map. internal/plugin/architecture_test.go recognises curator as a conforming engine family.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T15:47:42Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:30:03Z","started_at":"2026-08-05T04:30:03Z","dependencies":[{"issue_id":"archie-core-rfp","depends_on_id":"archie-core-yp9","type":"parent-child","created_at":"2026-07-30T01:47:42Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-yp9","title":"[EPIC] Curator engine: persistent memory-reasoning agent loops","description":"Introduce curators as their own engine family: long-running agent loops that reason over memory and perform small maintenance tasks, rather than one hardcoded background job. A curator is defined by a check-in interval, a tool set, and (once the memory engine family lands) an attached memory engine. It runs persistently while there is input and backs off to a cooldown when idle. Ship two reference curators -- a skill curator and a persistent-session-memory curator -- so the interface is proven against two consumers rather than designed around one.","design":"The design splits a cheap hot-path extractor from an expensive sampled reasoner, so agentic cost is never paid per message. Sampling chooses which memories deserve attention via surprisal-based scoring, implemented over embeddings through interchangeable strategies including a k-NN graph random walk. Archie has no embedding capability today, so any surprisal-style sampling is gated behind adding one.","acceptance_criteria":"Curator is a conforming engine family per ARCHITECTURE.md 'Plugin engine rule (strict)': typed contract, owning registry/manager, start/health/stop, narrow typed host access. Curators are registered and configured declaratively, not hardcoded. The runtime supports persistent operation under load and cooldown when idle, with intervals configurable per curator. Both reference curators run against the shipped defaults. Curator activity is observable: what ran, when, what it changed, and why. A curator failure is isolated and never takes down the daemon or a chat turn.","notes":"FULL PLAN (2026-08-05, approved by Sam; no external-app references anywhere in this epic):\nTARGET: internal/curator is a conforming engine family per the strict plugin engine rule: typed CuratorEngine contract, owning Registry with start/health/stop and shutdown ordering, narrow typed registrar, never the daemon. In-process execution in the daemon (precedent: chat + inprocess agent mode). \nWAVE 1 (no memory engine needed): rfp contract+registry+registrar -\u003e 89x runtime loop (fake clock, per-pass budgets, panic isolation, bounded shutdown) -\u003e 035 trigger accounting (new KindTurnCompleted event from chat responder paths; derived-output marker excludes curator writes from the trigger; regression test carries the feedback-loop rationale) -\u003e i7i skill curator (new skill write path, config-scoped root, attributable actions) -\u003e 114 observability (curator event kinds + /api/curators).\nWAVE 2 (after memory-engine family 1x7 lands): pek curator\u003c-\u003ememory binding, then gs8 persistent session-memory curator (hot path = the trigger event only; no per-message model calls; writes derived memories through the engine contract).\nSAMPLING: Sampler strategy seam with cheap strategies (recency/random/all/staleness proxy) ships in wave 1; embedding-backed surprisal deferred (see children archie-core-yp9.1 and archie-core-yp9.2).\nISOLATION INVARIANT (load-bearing): curators are peers, never dependencies - own registry-owned loops, own events; a curator must never block, delay, or take down chat turns, agent runs, or the daemon. Wake events ride events.Bus (bounded dropping subscriber); wake is a best-effort nudge, the trigger is a deterministic persisted-state read at pass time. Per-pass recover + budgets; max concurrent passes configurable (default 1); registry lifecycle independent of the agent loop; daemon shutdown cancels in-flight passes and waits bounded. See bd memory curator-isolation-invariant.","status":"open","priority":1,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-29T15:47:27Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:27:08Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-lp1","title":"Ship the file-writing store as the default memory engine","description":"Reframe internal/memory/builtin as the reference engine implementation behind the new contract, so the standard install keeps writing memories to files with no configuration and no behaviour change.","acceptance_criteria":"The builtin store implements the engine contract and registers as the default. A config that names no memory engine behaves exactly as today, verified by existing internal/memory tests continuing to pass unmodified where they assert behaviour rather than structure. Its lifecycle methods are real or explicit no-ops, not stubs that silently do nothing surprising.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T15:46:57Z","created_by":"Sam Catlow","updated_at":"2026-07-29T15:46:57Z","dependencies":[{"issue_id":"archie-core-lp1","depends_on_id":"archie-core-huu","type":"parent-child","created_at":"2026-07-30T01:46:57Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-lp1","depends_on_id":"archie-core-1x7","type":"blocks","created_at":"2026-07-30T01:48:15Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-1x7","title":"Memory engine contract and owning registry","description":"Define the typed memory engine interface and the registry that owns provider registration, discovery, and lifecycle. This is the load-bearing design step: everything else in the epic is written against this contract.","acceptance_criteria":"A typed interface exposes real memory operations beyond identity metadata. An owning Registry/Manager controls registration, init, start, health, and stop, and defines failure isolation and shutdown ordering. Providers receive only a typed registrar and the host services their capability declares. internal/plugin/architecture_test.go passes with memory recognised as a conforming engine family. Stateless providers may declare explicit no-op lifecycle.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T15:46:56Z","created_by":"Sam Catlow","updated_at":"2026-07-29T15:46:56Z","dependencies":[{"issue_id":"archie-core-1x7","depends_on_id":"archie-core-huu","type":"parent-child","created_at":"2026-07-30T01:46:56Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":4,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-huu","title":"[EPIC] Pluggable memory engine: typed family + external providers","description":"Make the memory subsystem a pluggable engine family so an external memory backend (Honcho, or a future alternative) can be bolted on without touching the agent loop, while the file-writing store ships as the default. internal/memory already has a Manager and lifecycle hooks (TurnStartHook, SessionEndHook, SessionSwitchHook); this epic promotes that into a conforming engine family per the strict plugin engine rule in ARCHITECTURE.md rather than inventing a parallel abstraction.","design":"Constraint from the plugin engine rule: 'engine' requires a typed domain contract, an owning Registry or Manager, explicit lifecycle/health, and narrow typed registrars -- providers never receive *daemon.Daemon or untyped hook maps. The contract must express real memory operations (write observation, query, list, forget), not just Name/Version.","acceptance_criteria":"Memory is a typed engine family with an owning registry/manager, start/health/stop lifecycle, and narrow typed host access, satisfying every invariant in ARCHITECTURE.md 'Plugin engine rule (strict)' and passing internal/plugin/architecture_test.go. The builtin file-writing store is the shipped default engine and remains the behaviour when nothing is configured. At least one external engine is implementable against the contract without changes to the agent loop or gateway. Engine selection and per-engine settings are configurable, validated, and documented. Failure of a non-default engine degrades to a reported error rather than taking down a turn.","status":"open","priority":1,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-29T15:46:38Z","created_by":"Sam Catlow","updated_at":"2026-07-29T15:46:38Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
@@ -158,7 +164,7 @@
|
||||
{"_type":"issue","id":"archie-core-abg.18.28","title":"Verify: MemoryManager prefetch with timeout","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:55Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:17:34Z","closed_at":"2026-07-25T23:17:34Z","close_reason":"Adversarial review of 18.8 prefetch with timeout: verified tests pass, formatting clean, build succeeds. All ACs met: PrefetchContext with configurable timeout (8s default), per-provider in-flight CAS skip, timeout via context cancellation, result storage for SystemPromptBlock, metrics/logging for duration/timeout/skip. No issues found.","dependencies":[{"issue_id":"archie-core-abg.18.28","depends_on_id":"archie-core-abg.18.8","type":"blocks","created_at":"2026-07-26T00:19:42Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.28","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:55Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.34","title":"Verify: Context-pressure threshold gating","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:54Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:39:14Z","closed_at":"2026-07-25T23:39:14Z","close_reason":"17.15 implemented and all verification checks pass: tests pass with -race, go vet clean, gofmt clean.","dependencies":[{"issue_id":"archie-core-abg.17.34","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:54Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.34","depends_on_id":"archie-core-abg.17.15","type":"blocks","created_at":"2026-07-26T00:19:34Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.18.27","title":"Verify: MemoryManager background sync pipeline","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:50Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:17:33Z","closed_at":"2026-07-25T23:17:33Z","close_reason":"Adversarial review of 18.7 sync pipeline: verified go test ./internal/memory/... passes (30 new tests), gofmt clean, go build ./... succeeds. Reviewed code paths for dead code, race conditions (added pipelineMu TOCTOU guard), and AC compliance. All ACs met: single-worker FIFO channel, configurable buffer (100), completion notification, shutdown drain, error logging without crash. Implementation is clean.","dependencies":[{"issue_id":"archie-core-abg.18.27","depends_on_id":"archie-core-abg.18.7","type":"blocks","created_at":"2026-07-26T00:19:43Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.27","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:50Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.33","title":"Verify: Progressive tool disclosure (bridge tools)","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:49Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:39:00Z","closed_at":"2026-07-25T23:39:00Z","close_reason":"All verification checks pass: tests pass with -race, go vet clean, gofmt clean, golangci-lint identifies only pre-existing issues. No dead code paths, no hardcoded values in tests.","dependencies":[{"issue_id":"archie-core-abg.17.33","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:48Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.33","depends_on_id":"archie-core-abg.17.14","type":"blocks","created_at":"2026-07-26T00:19:35Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.33","title":"Verify: Progressive tool disclosure (bridge tools)","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","notes":"Reopened 2026-08-05: implementation landed in ccb5560 but has no caller. agentexec.BuildToolSet is the only path from a ToolEntry to the model and it reads Name/Description/Schema/Handler only, so dispatch, budget, spill, availability caching and disclosure are all unreachable. The epic's acceptance criteria (loop protection, schemas within context budget) are therefore unmet. Closing these on implementation without integration is what hid the gap.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:49Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:23:37Z","dependencies":[{"issue_id":"archie-core-abg.17.33","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:48Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.33","depends_on_id":"archie-core-abg.17.14","type":"blocks","created_at":"2026-07-26T00:19:35Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.32","title":"Verify: Guardrail decision engine: warning vs hard-stop","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:45Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:39:00Z","closed_at":"2026-07-25T23:39:00Z","close_reason":"All verification checks pass: tests pass with -race, go vet clean, gofmt clean, golangci-lint identifies only pre-existing issues. No dead code paths, no hardcoded values in tests.","dependencies":[{"issue_id":"archie-core-abg.17.32","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:45Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.32","depends_on_id":"archie-core-abg.17.13","type":"blocks","created_at":"2026-07-26T00:19:36Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.31","title":"Verify: Mutating tool classification set","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:39Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:38:59Z","closed_at":"2026-07-25T23:38:59Z","close_reason":"All verification checks pass: tests pass with -race, go vet clean, gofmt clean, golangci-lint identifies only pre-existing issues. No dead code paths, no hardcoded values in tests.","dependencies":[{"issue_id":"archie-core-abg.17.31","depends_on_id":"archie-core-abg.17.12","type":"blocks","created_at":"2026-07-26T00:19:37Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.31","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:39Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.30","title":"Verify: Idempotent tool classification set","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:35Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:38:59Z","closed_at":"2026-07-25T23:38:59Z","close_reason":"All verification checks pass: tests pass with -race, go vet clean, gofmt clean, golangci-lint identifies only pre-existing issues. No dead code paths, no hardcoded values in tests.","dependencies":[{"issue_id":"archie-core-abg.17.30","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:35Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.30","depends_on_id":"archie-core-abg.17.11","type":"blocks","created_at":"2026-07-26T00:19:41Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
@@ -167,17 +173,17 @@
|
||||
{"_type":"issue","id":"archie-core-abg.16.26","title":"Verify: MessageDeduplicator with TTL-based dedup cache","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:27Z","created_by":"Sam Catlow","updated_at":"2026-07-28T17:04:59Z","closed_at":"2026-07-28T17:04:59Z","close_reason":"Deliverable is a review, not code: the only acceptance criterion is 'Independent adversarial review by fresh agent ... Report findings or confirm clean'. CLAUDE.md's Development Protocol already makes an adversarial verification pass mandatory in the definition-of-done for the paired implementation bead, so tracking it as a separate ticket is a review campaign with no code output. Verification still happens - it is folded into the parent implementation issue.","dependencies":[{"issue_id":"archie-core-abg.16.26","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:12:26Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.16.26","depends_on_id":"archie-core-abg.16.12","type":"blocks","created_at":"2026-07-26T00:19:51Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.28","title":"Verify: Per-turn aggregate budget enforcement (200K char cap)","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:24Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:38:59Z","closed_at":"2026-07-25T23:38:59Z","close_reason":"All verification checks pass: tests pass with -race, go vet clean, gofmt clean, golangci-lint identifies only pre-existing issues. No dead code paths, no hardcoded values in tests.","dependencies":[{"issue_id":"archie-core-abg.17.28","depends_on_id":"archie-core-abg.17.7","type":"blocks","created_at":"2026-07-26T00:19:46Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.28","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:24Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.25","title":"Verify: Platform capability flags for adapters","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:23Z","created_by":"Sam Catlow","updated_at":"2026-07-28T17:04:58Z","closed_at":"2026-07-28T17:04:58Z","close_reason":"Deliverable is a review, not code: the only acceptance criterion is 'Independent adversarial review by fresh agent ... Report findings or confirm clean'. CLAUDE.md's Development Protocol already makes an adversarial verification pass mandatory in the definition-of-done for the paired implementation bead, so tracking it as a separate ticket is a review campaign with no code output. Verification still happens - it is folded into the parent implementation issue.","dependencies":[{"issue_id":"archie-core-abg.16.25","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:12:22Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.16.25","depends_on_id":"archie-core-abg.16.8","type":"blocks","created_at":"2026-07-26T00:19:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.27","title":"Verify: Concurrent tool dispatch with execution gating","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:20Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:38:59Z","closed_at":"2026-07-25T23:38:59Z","close_reason":"All verification checks pass: tests pass with -race, go vet clean, gofmt clean, golangci-lint identifies only pre-existing issues. No dead code paths, no hardcoded values in tests.","dependencies":[{"issue_id":"archie-core-abg.17.27","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:20Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.27","depends_on_id":"archie-core-abg.17.6","type":"blocks","created_at":"2026-07-26T00:19:44Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.27","title":"Verify: Concurrent tool dispatch with execution gating","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","notes":"Reopened 2026-08-05: implementation landed in ccb5560 but has no caller. agentexec.BuildToolSet is the only path from a ToolEntry to the model and it reads Name/Description/Schema/Handler only, so dispatch, budget, spill, availability caching and disclosure are all unreachable. The epic's acceptance criteria (loop protection, schemas within context budget) are therefore unmet. Closing these on implementation without integration is what hid the gap.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:20Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:23:37Z","dependencies":[{"issue_id":"archie-core-abg.17.27","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:20Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.27","depends_on_id":"archie-core-abg.17.6","type":"blocks","created_at":"2026-07-26T00:19:44Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.24","title":"Verify: BasePlatformAdapter optional methods (typing, edit, delete, media)","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:19Z","created_by":"Sam Catlow","updated_at":"2026-07-28T17:04:58Z","closed_at":"2026-07-28T17:04:58Z","close_reason":"Deliverable is a review, not code: the only acceptance criterion is 'Independent adversarial review by fresh agent ... Report findings or confirm clean'. CLAUDE.md's Development Protocol already makes an adversarial verification pass mandatory in the definition-of-done for the paired implementation bead, so tracking it as a separate ticket is a review campaign with no code output. Verification still happens - it is folded into the parent implementation issue.","dependencies":[{"issue_id":"archie-core-abg.16.24","depends_on_id":"archie-core-abg.16.6","type":"blocks","created_at":"2026-07-26T00:19:52Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.16.24","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:12:18Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.26","title":"Verify: Sequential tool dispatch with per-result previews and error handling","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:16Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:38:58Z","closed_at":"2026-07-25T23:38:58Z","close_reason":"All verification checks pass: tests pass with -race, go vet clean, gofmt clean, golangci-lint identifies only pre-existing issues. No dead code paths, no hardcoded values in tests.","dependencies":[{"issue_id":"archie-core-abg.17.26","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:16Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.26","depends_on_id":"archie-core-abg.17.5","type":"blocks","created_at":"2026-07-26T00:19:47Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.26","title":"Verify: Sequential tool dispatch with per-result previews and error handling","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","notes":"Reopened 2026-08-05: implementation landed in ccb5560 but has no caller. agentexec.BuildToolSet is the only path from a ToolEntry to the model and it reads Name/Description/Schema/Handler only, so dispatch, budget, spill, availability caching and disclosure are all unreachable. The epic's acceptance criteria (loop protection, schemas within context budget) are therefore unmet. Closing these on implementation without integration is what hid the gap.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:16Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:23:37Z","dependencies":[{"issue_id":"archie-core-abg.17.26","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:16Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.26","depends_on_id":"archie-core-abg.17.5","type":"blocks","created_at":"2026-07-26T00:19:47Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.23","title":"Verify: SendResult struct with retry/error classification","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:15Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:27:33Z","started_at":"2026-07-25T15:24:34Z","closed_at":"2026-07-25T15:27:33Z","close_reason":"Adversarial review complete. 2 gofmt issues fixed (already corrected before review completed), race condition fixed (mutex now covers Save/Delete/Touch consistently), style issues resolved (idiomatic IsZero() checks, zero-value Source assertions added). Final: 58/58 tests pass with -race, gofmt clean, golangci-lint 0 issues, go vet clean.","dependencies":[{"issue_id":"archie-core-abg.16.23","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:12:15Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.16.23","depends_on_id":"archie-core-abg.16.3","type":"blocks","created_at":"2026-07-26T00:19:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.25","title":"Verify: Per-tool result size limits with spill-to-disk","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:12Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:38:58Z","closed_at":"2026-07-25T23:38:58Z","close_reason":"All verification checks pass: tests pass with -race, go vet clean, gofmt clean, golangci-lint identifies only pre-existing issues. No dead code paths, no hardcoded values in tests.","dependencies":[{"issue_id":"archie-core-abg.17.25","depends_on_id":"archie-core-abg.17.4","type":"blocks","created_at":"2026-07-26T00:19:49Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.25","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:12Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.24","title":"Verify: Tool availability checks with TTL caching","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:09Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:38:58Z","closed_at":"2026-07-25T23:38:58Z","close_reason":"All verification checks pass: tests pass with -race, go vet clean, gofmt clean, golangci-lint identifies only pre-existing issues. No dead code paths, no hardcoded values in tests.","dependencies":[{"issue_id":"archie-core-abg.17.24","depends_on_id":"archie-core-abg.17.3","type":"blocks","created_at":"2026-07-26T00:19:48Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.24","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:08Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.25","title":"Verify: Per-tool result size limits with spill-to-disk","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","notes":"Reopened 2026-08-05: implementation landed in ccb5560 but has no caller. agentexec.BuildToolSet is the only path from a ToolEntry to the model and it reads Name/Description/Schema/Handler only, so dispatch, budget, spill, availability caching and disclosure are all unreachable. The epic's acceptance criteria (loop protection, schemas within context budget) are therefore unmet. Closing these on implementation without integration is what hid the gap.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:12Z","created_by":"Sam Catlow","updated_at":"2026-08-05T07:20:59Z","started_at":"2026-08-05T04:24:04Z","closed_at":"2026-08-05T07:20:59Z","close_reason":"Now integrated, not just implemented. agentexec.BuildToolSet applies the per-tool result cap and the per-turn budget inside the Execute closure it builds for every tool -- the one path from a ToolEntry to a model. tools.CapPayload is the single definition of the cap/spill rule, shared with the batch-dispatch path. Limits are configurable via [tools.tool_policy] (max_result_chars, turn_budget_chars, spill_dir), which previously had no toml tags and could not be set at all. Budget is minted per turn/stage, never shared. Adversarial pass fixed a double-charge (Spill billed the full displaced size on top of the caller's charge) and cross-turn spill filename collisions.","dependencies":[{"issue_id":"archie-core-abg.17.25","depends_on_id":"archie-core-abg.17.4","type":"blocks","created_at":"2026-07-26T00:19:49Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.25","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:12Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.24","title":"Verify: Tool availability checks with TTL caching","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","notes":"Reopened 2026-08-05: implementation landed in ccb5560 but has no caller. agentexec.BuildToolSet is the only path from a ToolEntry to the model and it reads Name/Description/Schema/Handler only, so dispatch, budget, spill, availability caching and disclosure are all unreachable. The epic's acceptance criteria (loop protection, schemas within context budget) are therefore unmet. Closing these on implementation without integration is what hid the gap.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:09Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:23:36Z","dependencies":[{"issue_id":"archie-core-abg.17.24","depends_on_id":"archie-core-abg.17.3","type":"blocks","created_at":"2026-07-26T00:19:48Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.24","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:12:08Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.18.16","title":"Shutdown drain with timeout and abandoned-write tracking","description":"Implement graceful shutdown drain for MemoryManager with a bounded timeout. In-flight sync operations are given a configurable deadline to complete. Operations that don't finish within the deadline are tracked as abandoned writes for diagnostics.","acceptance_criteria":"Shutdown(ctx) method on MemoryManager with context-based deadline\nIn-flight sync pipeline operations are given N seconds (default 10) to complete\nAbandoned writes (those exceeding the deadline) are logged with: provider name, operation type, age\nshutdown() is called on all active providers in reverse registration order\nAfter shutdown, no new operations are accepted\nProvider shutdown respects the same deadline\nAbandoned-write counter is accessible for health/status reporting","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:26Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:17:27Z","closed_at":"2026-07-25T23:17:27Z","close_reason":"Implemented ShutdownContext(ctx) with pipeline drain timeout (default 10s), shutdownDeadlineNano for worker self-abandonment, AbandonedCount() counter, SetShutdownTimeout config, reverse-order provider shutdown, pipelineMu TOCTOU guard. 4 tests covering drain, abandoned count, reverse order, and timeout config.","dependencies":[{"issue_id":"archie-core-abg.18.16","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:08:25Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.18.15","title":"Threat scanning integration for memory content","description":"Integrate threat scanning for all memory content writes. Before persisting any memory content (add/replace/remove), scan the content for potentially dangerous patterns (injection attempts, sensitive data leakage, prompt injection in stored memory).","acceptance_criteria":"A ScanContent(content string) function or hook is called before every memory write\nScans cover: prompt injection patterns, sensitive data patterns (API keys, passwords, tokens)\nConfigurable to reject (block the write) or warn (allow with log) on suspicious content\nIntegration point at the MemoryManager level so it applies to all providers\nResults are logged for audit\nConfig flag to disable scanning for development","notes":"Follow-up: ScanContent was implemented but never actually called before a write reached a provider (the close reason overstated this). Fixed: Manager.HandleToolCall now scans any \"content\"/\"replacement\" string argument via ScanContent before dispatching, rejecting on ThreatBlock. GetToolSchemas()'s injected tool Handler now routes through m.HandleToolCall (was calling tcp.HandleToolCall directly, bypassing scanning). Added TestManager_HandleToolCall_ScanBlocksPromptInjection and TestManager_HandleToolCall_ScanAllowsCleanContent.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:21:03Z","closed_at":"2026-07-25T23:17:26Z","close_reason":"Implemented Scanner interface and DefaultScanner with prompt injection (ThreatBlock) and sensitive data (ThreatWarn) patterns. Configurable reject/warn via SetScanReject, disable via SetScanDisabled, integration at Manager.ScanContent level. 8 tests covering no scanner, disabled, prompt injection, reject mode, sensitive data, clean content, and scanner clear.","dependencies":[{"issue_id":"archie-core-abg.18.15","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:08:20Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.18.14","title":"Frozen snapshot pattern for memory injection","description":"Implement the frozen snapshot pattern: memory content is read at session start and injected into the system prompt as a snapshot. On write, files are updated immediately but the system prompt is NOT changed mid-session. Only the next session picks up the new snapshot.","acceptance_criteria":"At session start, MEMORY.md and USER.md are read and formatted into a system prompt block\nThis formatted block becomes part of the session's system prompt (frozen for the session duration)\nWhen a memory write occurs, the files are updated immediately on disk\nThe in-memory snapshot for the current session is NOT updated\nThe next session reads the fresh files and creates a new frozen snapshot\nConfig flag to disable frozen snapshot (always read fresh) for testing","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:08:16Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:01:51Z","started_at":"2026-07-25T22:56:19Z","closed_at":"2026-07-25T23:01:51Z","close_reason":"Frozen snapshot pattern implemented in builtin Provider. Initialize() captures Render() of both MEMORY.md and USER.md into frozen string fields. SystemPromptBlock() returns \u003cmemory\u003e-fenced markdown from frozen snapshot (or live if DisableFrozenSnapshot=true). Writes go to disk immediately; snapshot unchanged mid-session. 8 tests covering: freeze on write, live mode, empty stores, memory-only, user-only, re-initialize, default enabled, both files. Full build + all memory tests pass.","dependencies":[{"issue_id":"archie-core-abg.18.14","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:08:16Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.15","title":"Context-pressure threshold gating","description":"Implement context-pressure threshold gating: when the combined size of tool schemas exceeds a configurable percentage of the LLM context window, automatically switch to progressive tool disclosure mode (bridge tools). Monitor context usage and toggle between full disclosure and bridge-tool mode dynamically.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:58Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:35:36Z","closed_at":"2026-07-25T23:35:36Z","close_reason":"All 10 implementation issues done: 6 new files + 1 field addition. Full test coverage with race detector passing.","dependencies":[{"issue_id":"archie-core-abg.17.15","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.14","title":"Progressive tool disclosure (bridge tools)","description":"Implement the progressive tool disclosure pattern with three bridge tools: tool_search (search available tools by keyword), tool_describe (return full schema for one tool), and tool_call (invoke a tool by name after discovery). This keeps the LLM's tool schema footprint small while providing full access to the tool arsenal on demand.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:53Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:35:35Z","closed_at":"2026-07-25T23:35:35Z","close_reason":"All 10 implementation issues done: 6 new files + 1 field addition. Full test coverage with race detector passing.","dependencies":[{"issue_id":"archie-core-abg.17.14","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.14","title":"Progressive tool disclosure (bridge tools)","description":"Implement the progressive tool disclosure pattern with three bridge tools: tool_search (search available tools by keyword), tool_describe (return full schema for one tool), and tool_call (invoke a tool by name after discovery). This keeps the LLM's tool schema footprint small while providing full access to the tool arsenal on demand.","notes":"Reopened 2026-08-05: implementation landed in ccb5560 but has no caller. agentexec.BuildToolSet is the only path from a ToolEntry to the model and it reads Name/Description/Schema/Handler only, so dispatch, budget, spill, availability caching and disclosure are all unreachable. The epic's acceptance criteria (loop protection, schemas within context budget) are therefore unmet. Closing these on implementation without integration is what hid the gap.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:53Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:23:36Z","dependencies":[{"issue_id":"archie-core-abg.17.14","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.13","title":"Guardrail decision engine: warning vs hard-stop","description":"Implement the guardrail decision engine that uses ToolCallGuardrailConfig thresholds to decide between sending a warning to the LLM or issuing a hard-stop (aborting the tool loop). Considers exact_failure_warn_after, same_tool_failure_warn_after, and no_progress_warn_after. Must track per-session and per-turn counters.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:51Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:35:35Z","closed_at":"2026-07-25T23:35:35Z","close_reason":"All 10 implementation issues done: 6 new files + 1 field addition. Full test coverage with race detector passing.","dependencies":[{"issue_id":"archie-core-abg.17.13","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:50Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.12","title":"Mutating tool classification set","description":"Define and maintain a classification set of mutating (mutation-capable) tools. These tools can modify state and require serialization, checkpointing, and stricter guardrail monitoring. The set should be extensible via registration metadata and feed into dispatch gating and checkpointing decisions.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:50Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:35:35Z","started_at":"2026-07-25T23:26:51Z","closed_at":"2026-07-25T23:35:35Z","close_reason":"All 10 implementation issues done: 6 new files + 1 field addition. Full test coverage with race detector passing.","dependencies":[{"issue_id":"archie-core-abg.17.12","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:50Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.18.9","title":"MemoryManager notify_memory_tool_write","description":"Implement notify_memory_tool_write() in MemoryManager that mirrors built-in memory tool writes to external providers. When the agent uses the built-in memory tool (add/replace/remove), external providers receive a notification so they can stay in sync.","acceptance_criteria":"After any successful built-in memory tool write, MemoryManager calls external provider's on_memory_write(content) hook\nThe notification is asynchronous and goes through the background sync pipeline\nThe notification includes the full content of what was written and the action type (add/replace/remove)\nIf no external provider is active, the call is a no-op\nExternal provider can choose to ignore the notification if it doesn't implement the hook","notes":"Follow-up: HandleToolCall previously did not actually invoke NotifyMemoryToolWrite automatically — GetToolSchemas() wired tool Handlers directly to tcp.HandleToolCall, bypassing Manager cross-cutting logic. Fixed: Handler now routes through m.HandleToolCall, which calls NotifyMemoryToolWrite after a successful builtin write. Added TestManager_HandleToolCall_NotifiesExternalOnBuiltinWrite and TestManager_HandleToolCall_DoesNotNotifyOnExternalWrite.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:47Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:21:03Z","closed_at":"2026-07-25T23:17:24Z","close_reason":"Implemented NotifyMemoryToolWrite(sessionID, action, section, content) that dispatches through sync pipeline for write ordering. No-op when no external provider or provider unavailable. 3 tests covering external dispatch, no-op without external, and no-op when unavailable.","dependencies":[{"issue_id":"archie-core-abg.18.9","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:47Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
@@ -186,9 +192,9 @@
|
||||
{"_type":"issue","id":"archie-core-abg.18.8","title":"MemoryManager prefetch with timeout","description":"Implement prefetch in MemoryManager with an 8-second default timeout. If a provider's prefetch is still running from the previous turn, skip it rather than queue another. This prevents memory lookups from blocking the agent loop.","acceptance_criteria":"prefetch(ctx, query) accepts a context with configurable timeout (default 8s)\nIf a provider is still prefetching from the previous turn, the new prefetch is skipped (not queued)\nA provider-level mutex or state flag tracks in-flight prefetch operations\nTimeout causes context cancellation which the provider should respect\nResults from prefetch are stored for retrieval in system_prompt_block()\nMetrics/logging track prefetch duration, timeouts, and skips","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:43Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:17:23Z","closed_at":"2026-07-25T23:17:23Z","close_reason":"Implemented PrefetchContext(ctx, query) with configurable timeout (default 8s), per-provider in-flight tracking via atomic.Bool CAS, skip-when-in-flight, result storage in prefetchResults for SystemPromptBlock inclusion via \u003cprefetch\u003e blocks. 5 tests covering success, result storage, skip, timeout, and timeout config.","dependencies":[{"issue_id":"archie-core-abg.18.8","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.18.7","title":"MemoryManager background sync pipeline","description":"Implement a serialized background sync pipeline in MemoryManager using a single-worker ThreadPoolExecutor pattern. All write operations from external providers are serialized through one worker to guarantee write ordering and prevent concurrent mutations.","acceptance_criteria":"A single-worker goroutine/worker pool processes queued sync operations\nWrite operations are submitted to the pipeline and processed in FIFO order\nCaller receives a channel/future for optional completion notification\nWrite ordering is guaranteed - operations don't reorder\nPipeline has a configurable buffer size (default 100)\nPipeline drains on shutdown with configurable timeout\nErrors from sync operations are logged but don't crash the pipeline","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:39Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:17:18Z","closed_at":"2026-07-25T23:17:18Z","close_reason":"Implemented background sync pipeline with single-worker channel (default buf=100), FIFO ordering, completion notification via Done channel, SubmitSync/processSyncOp/syncWorker, pipeline mutex for TOCTOU safety. 5 tests covering dispatch, FIFO, completion, not-found, and shutdown rejection.","dependencies":[{"issue_id":"archie-core-abg.18.7","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:38Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.6","title":"Concurrent tool dispatch with execution gating","description":"Implement concurrent tool dispatch with execution gating classes: never-parallel (e.g. state mutators), parallel-safe (e.g. read-only tools), and path-scoped (same-path tools are serialized, different paths run in parallel). Use sync primitives and a gating engine to classify and schedule tool invocations correctly.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:37Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:35:34Z","closed_at":"2026-07-25T23:35:34Z","close_reason":"All 10 implementation issues done: 6 new files + 1 field addition. Full test coverage with race detector passing.","dependencies":[{"issue_id":"archie-core-abg.17.6","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:36Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.7","title":"Per-turn aggregate budget enforcement (200K char cap)","description":"Implement a per-turn aggregate output budget of 200,000 characters. Track cumulative tool result sizes within a turn. When the budget is exceeded, auto-spill the largest results to disk. Enforce a hard stop at the budget limit with clear reporting to the user.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:37Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:35:34Z","closed_at":"2026-07-25T23:35:34Z","close_reason":"All 10 implementation issues done: 6 new files + 1 field addition. Full test coverage with race detector passing.","dependencies":[{"issue_id":"archie-core-abg.17.7","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:37Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.5","title":"Sequential tool dispatch with per-result previews and error handling","description":"Build the sequential tool dispatch pipeline: invoke tools one-at-a-time, capture per-result previews (truncated output for context-feed), and implement error classification with graceful fallback. Each result should produce a short preview snippet for inclusion in the conversation context.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:32Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:35:34Z","closed_at":"2026-07-25T23:35:34Z","close_reason":"All 10 implementation issues done: 6 new files + 1 field addition. Full test coverage with race detector passing.","dependencies":[{"issue_id":"archie-core-abg.17.5","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:32Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.3","title":"Tool availability checks with TTL caching","description":"Implement the check_fn pattern for tool availability predicates (e.g. 'is Docker running'). Results should be TTL-cached (e.g. 30s check interval) with a failure grace period (e.g. 60s before re-checking on error). This prevents redundant checking on every invocation while keeping availability fresh.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:31Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:35:33Z","started_at":"2026-07-25T23:26:50Z","closed_at":"2026-07-25T23:35:33Z","close_reason":"All 10 implementation issues done: 6 new files + 1 field addition. Full test coverage with race detector passing.","dependencies":[{"issue_id":"archie-core-abg.17.3","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:30Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.7","title":"Per-turn aggregate budget enforcement (200K char cap)","description":"Implement a per-turn aggregate output budget of 200,000 characters. Track cumulative tool result sizes within a turn. When the budget is exceeded, auto-spill the largest results to disk. Enforce a hard stop at the budget limit with clear reporting to the user.","notes":"Reopened 2026-08-05: implementation landed in ccb5560 but has no caller. agentexec.BuildToolSet is the only path from a ToolEntry to the model and it reads Name/Description/Schema/Handler only, so dispatch, budget, spill, availability caching and disclosure are all unreachable. The epic's acceptance criteria (loop protection, schemas within context budget) are therefore unmet. Closing these on implementation without integration is what hid the gap.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:37Z","created_by":"Sam Catlow","updated_at":"2026-08-05T07:20:59Z","started_at":"2026-08-05T04:24:04Z","closed_at":"2026-08-05T07:20:59Z","close_reason":"Now integrated, not just implemented. agentexec.BuildToolSet applies the per-tool result cap and the per-turn budget inside the Execute closure it builds for every tool -- the one path from a ToolEntry to a model. tools.CapPayload is the single definition of the cap/spill rule, shared with the batch-dispatch path. Limits are configurable via [tools.tool_policy] (max_result_chars, turn_budget_chars, spill_dir), which previously had no toml tags and could not be set at all. Budget is minted per turn/stage, never shared. Adversarial pass fixed a double-charge (Spill billed the full displaced size on top of the caller's charge) and cross-turn spill filename collisions.","dependencies":[{"issue_id":"archie-core-abg.17.7","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:37Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.5","title":"Sequential tool dispatch with per-result previews and error handling","description":"Build the sequential tool dispatch pipeline: invoke tools one-at-a-time, capture per-result previews (truncated output for context-feed), and implement error classification with graceful fallback. Each result should produce a short preview snippet for inclusion in the conversation context.","notes":"Reopened 2026-08-05: implementation landed in ccb5560 but has no caller. agentexec.BuildToolSet is the only path from a ToolEntry to the model and it reads Name/Description/Schema/Handler only, so dispatch, budget, spill, availability caching and disclosure are all unreachable. The epic's acceptance criteria (loop protection, schemas within context budget) are therefore unmet. Closing these on implementation without integration is what hid the gap.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:32Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:23:36Z","dependencies":[{"issue_id":"archie-core-abg.17.5","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:32Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.3","title":"Tool availability checks with TTL caching","description":"Implement the check_fn pattern for tool availability predicates (e.g. 'is Docker running'). Results should be TTL-cached (e.g. 30s check interval) with a failure grace period (e.g. 60s before re-checking on error). This prevents redundant checking on every invocation while keeping availability fresh.","notes":"Reopened 2026-08-05: implementation landed in ccb5560 but has no caller. agentexec.BuildToolSet is the only path from a ToolEntry to the model and it reads Name/Description/Schema/Handler only, so dispatch, budget, spill, availability caching and disclosure are all unreachable. The epic's acceptance criteria (loop protection, schemas within context budget) are therefore unmet. Closing these on implementation without integration is what hid the gap.","status":"open","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:31Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:23:35Z","started_at":"2026-07-25T23:26:50Z","dependencies":[{"issue_id":"archie-core-abg.17.3","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:30Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.4","title":"Per-tool result size limits with spill-to-disk","description":"Implement max_result_size_chars enforcement on each ToolEntry. When a tool result exceeds its limit, auto-spill large outputs to disk and return a reference/location instead of the full content. This prevents memory blowout from oversized tool results.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:31Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:37:37Z","started_at":"2026-07-25T23:35:56Z","closed_at":"2026-07-25T23:37:37Z","close_reason":"Per-tool MaxResultSizeChars enforcement added to dispatchOne and DispatchSequential. Results exceeding limit are spilled to disk or truncated inline.","dependencies":[{"issue_id":"archie-core-abg.17.4","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:31Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.15","title":"Media utilities: cache, validate, deliver images/audio/video/documents","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:06:57Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:06:57Z","dependencies":[{"issue_id":"archie-core-abg.16.15","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:06:56Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.12","title":"MessageDeduplicator with TTL-based dedup cache","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:06:55Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:06:55Z","dependencies":[{"issue_id":"archie-core-abg.16.12","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:06:55Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
@@ -202,8 +208,11 @@
|
||||
{"_type":"issue","id":"archie-core-s1r","title":"Test forge fakes missing LinkBranch method broke go vet/test for whole module","description":"forge.Forge gained LinkBranch(ctx, owner, repo, issueNumber, branch) error in the branch-linking feature (ff4c51e) but the hand-rolled test doubles (stubForge in cmd/archied/main_test.go, prCapturingForge in cmd/archie-agent/taskrun_test.go, testForge in internal/daemon/daemon_test.go, fakeForge in internal/forgerpc/forgerpc_test.go) never got the method added, so they stopped satisfying forge.Forge. This broke go vet ./... and go test ./... for the entire module, not just those 4 packages, since go vet type-checks all test files as part of module vet. Fixed by adding LinkBranch stubs to all four fakes.","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:04:53Z","created_by":"Sam Catlow","updated_at":"2026-07-24T03:04:58Z","closed_at":"2026-07-24T03:04:58Z","close_reason":"Added LinkBranch stub methods to stubForge, prCapturingForge, testForge, and fakeForge. go build/vet/test ./... now clean across the whole module.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-633","title":"config.docker.toml missing required fields, no overlay merge implemented","description":"config.docker.toml was rewritten to be a docs-as-overlay file (comment says base+overlay merge) but internal/config.Load has no merge logic and docker-compose.yml mounts only config.docker.toml at /etc/archie/config.toml. It is missing bot_user, [forge], [dispatch], [models], [providers], [budgets] which Load requires -\u003e daemon fails to start in docker as currently configured. Implement real base+overlay config loading (or restore a full standalone docker config) so there is one source of truth.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-24T02:42:07Z","created_by":"Sam Catlow","updated_at":"2026-07-24T02:44:53Z","started_at":"2026-07-24T02:42:11Z","closed_at":"2026-07-24T02:44:53Z","close_reason":"Implemented config.LoadOverlay (base decode + overlay decode into same struct, then shared finalize/validate), wired -config-overlay flag in cmd/archied, fixed docker-compose.yml to mount both base config.toml and config.docker.toml overlay, minimized config.docker.toml to true diff-only overlay, added tests proving overlay-omitted required fields (bot_user, repos) still come from base.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-u64","title":"Daemon: process multiple tasks concurrently (max_concurrency enforcement)","description":"Daemon currently processes one task at a time (docs/prds/archie-core-v2-architecture.md Phase 2). This is the core blocker between current state and any multi-agent scaling mode — needed before container max_concurrency or same-repo concurrency can matter. Wire the daemon's dispatch loop to run N tasks in parallel, respecting a configurable max_concurrency.","design":"internal/container/pool.go already enforces max_concurrency for container lifecycle — reuse that limit/pattern in the daemon's task dispatch rather than inventing a second concurrency control.","acceptance_criteria":"Daemon dispatch loop runs multiple tasks concurrently up to a configured max_concurrency limit; single-task-at-a-time behavior is gone.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:31Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:37:42Z","started_at":"2026-07-23T21:29:41Z","closed_at":"2026-07-23T21:37:42Z","close_reason":"Implemented concurrent SQLite and NATS task dispatch using containers.max_concurrency, with default same-repo serialization and race-tested dispatcher coverage.","dependency_count":0,"dependent_count":2,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.17","title":"Web Chat: split component markup and presentation files","description":"Refactor the Web Chat out of a large JavaScript-built markup blob. Keep HTML structure in a dedicated template, CSS in dedicated chat styles, Markdown rendering in its own module, and interaction/rendering behavior in focused modules while preserving current API behavior.","acceptance_criteria":"Chat source has dedicated HTML, CSS, Markdown, and behavior/view modules; chat.js is orchestration only; no duplicated markup blob remains; npm tests/build and task check pass; Playwright confirms chat interactions and Markdown rendering.","status":"in_progress","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:55:15Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:55:16Z","started_at":"2026-08-05T00:55:16Z","dependencies":[{"issue_id":"archie-core-3cf.17","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:55:15Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.16","title":"Web Chat: restore Telegram-compatible Markdown rendering","description":"Ensure assistant history and streamed replies render Markdown consistently in the split Web Chat component, matching Telegram-visible formatting. The renderer must remain a dedicated module and be covered by UI and Playwright tests.","acceptance_criteria":"History and streamed assistant bubbles use the same dedicated safe Markdown renderer; supported Markdown constructs render as semantic HTML; raw markup is not shown for supported constructs; unsafe links remain inert; tests and task check pass.","status":"in_progress","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:50:53Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:55:16Z","started_at":"2026-08-05T00:51:00Z","dependencies":[{"issue_id":"archie-core-3cf.16","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:50:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-yp9.2","title":"Surprisal sampling: embedding-backed strategies","description":"Implement the embedding-backed surprisal strategy behind the Sampler seam that wave 1 of the curator epic ships (cheap strategies: recency, random, all, staleness proxy). Surprisal scores memories by how surprising they are so the sampled reasoner's agentic budget is spent on the memories most likely to matter. DEFERRED by design: gated behind the embeddings capability (sibling issue 'Embeddings capability (prerequisite for surprisal sampling)') — pick up only after that lands.","acceptance_criteria":"A Sampler implementation behind the same interface as the cheap strategies; selection is deterministic given fixed inputs. Algorithm: sample up to a candidate cap; build a k-NN graph over embedding vectors; row-normalize the adjacency with self-loops; power-iterate to the stationary distribution; surprisal = -log(stationary probability of the nearest point); select the highest-surprisal items. Degradation: content with no embedding is skipped; an embedding failure aborts sampling and falls back to free exploration - a sampling failure must never fail or crash a curator pass. Cost: the graph build is quadratic in the candidate cap; the cap is a named constant with a documented bound. Tests use synthetic vectors via httptest, never a live embedding service.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-05T04:26:36Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:26:36Z","labels":["P2","feature"],"dependencies":[{"issue_id":"archie-core-yp9.2","depends_on_id":"archie-core-rfp","type":"blocks","created_at":"2026-08-05T14:26:50Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-yp9.2","depends_on_id":"archie-core-yp9.1","type":"blocks","created_at":"2026-08-05T14:26:50Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-yp9.2","depends_on_id":"archie-core-yp9","type":"parent-child","created_at":"2026-08-05T14:26:35Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-yp9.1","title":"Embeddings capability (prerequisite for surprisal sampling)","description":"Surprisal-based sampling (curator epic DESIGN) requires computing vector embeddings of memory content so memories can be scored by how surprising they are. Archie has no embedding capability today; the epic gates any surprisal-style sampling behind adding one. This issue tracks that prerequisite so it can be picked up independently of the curator epic's main work. The consumer is the embedding-backed surprisal sampler (sibling issue 'Surprisal sampling: embedding-backed strategies'). Embedding consumers must degrade gracefully: content with no embedding is skipped, and an embedding failure aborts sampling in favour of free exploration rather than crashing the pass.","acceptance_criteria":"An embedding client exists behind a narrow typed interface usable by in-process daemon components (curators first, other consumers later). Provider/model is config-driven (providers table + a role in [models]). A missing credential degrades per the credential-missing-degrades-not-fatal rule: capability reports unavailable, daemon still starts. Network calls carry timeouts; failures surface as reported errors, never a crash or a failed chat turn. Tests use httptest and never require a live embedding service.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-05T04:22:16Z","created_by":"Sam Catlow","updated_at":"2026-08-05T04:26:25Z","labels":["P3","feature"],"dependencies":[{"issue_id":"archie-core-yp9.1","depends_on_id":"archie-core-yp9","type":"parent-child","created_at":"2026-08-05T14:22:16Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.18","title":"Web Chat: render rich Markdown during streamed replies","description":"Telegram drafts render Markdown while a turn is streaming. Web Chat currently appends deltas as plain text and only renders rich output after completion. Keep the live assistant bubble semantically rich throughout SSE updates, including safe handling of partial Markdown.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T01:14:07Z","created_by":"Sam Catlow","updated_at":"2026-08-05T01:20:16Z","started_at":"2026-08-05T01:14:12Z","closed_at":"2026-08-05T01:20:16Z","close_reason":"Web Chat now replaces the live assistant bubble with the safe Markdown renderer on every streamed delta; unit coverage, Playwright verification, npm tests, build, and task check pass.","dependencies":[{"issue_id":"archie-core-3cf.18","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T11:14:07Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.17","title":"Web Chat: split component markup and presentation files","description":"Refactor the Web Chat out of a large JavaScript-built markup blob. Keep HTML structure in a dedicated template, CSS in dedicated chat styles, Markdown rendering in its own module, and interaction/rendering behavior in focused modules while preserving current API behavior.","acceptance_criteria":"Chat has dedicated HTML, CSS, Markdown, view, catalog, panel, render, and state modules; chat.js contains only chat-specific coordination and event wiring with no static markup blob; npm tests/build and task check pass; Playwright confirms chat interactions and Markdown rendering.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:55:15Z","created_by":"Sam Catlow","updated_at":"2026-08-05T01:05:24Z","started_at":"2026-08-05T00:55:16Z","closed_at":"2026-08-05T01:05:24Z","close_reason":"Split chat.html, chat.css, markdown.js, chat-view.js, chat-render.js, chat-state.js, chat-catalog.js, and chat-panels.js; browser and full gate pass.","dependencies":[{"issue_id":"archie-core-3cf.17","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:55:15Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.16","title":"Web Chat: restore Telegram-compatible Markdown rendering","description":"Ensure assistant history and streamed replies render Markdown consistently in the split Web Chat component, matching Telegram-visible formatting. The renderer must remain a dedicated module and be covered by UI and Playwright tests.","acceptance_criteria":"History and streamed assistant bubbles use the same dedicated safe Markdown renderer; supported Markdown constructs render as semantic HTML; raw markup is not shown for supported constructs; unsafe links remain inert; tests and task check pass.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:50:53Z","created_by":"Sam Catlow","updated_at":"2026-08-05T01:01:37Z","started_at":"2026-08-05T00:51:00Z","closed_at":"2026-08-05T01:01:37Z","close_reason":"Markdown is now a dedicated tested renderer and Chat markup/view/state are split into dedicated source files; Playwright and task check pass.","dependencies":[{"issue_id":"archie-core-3cf.16","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:50:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.15","title":"Web Chat: cancel server-side turns from Stop","description":"Make the Web Chat Stop action cancel the server-side gateway turn lane and discard queued turns, matching Telegram behavior. Add an authenticated cancel endpoint, wire the shared ChatService to gateway.Turns, and cover API/UI behavior.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:46:31Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:49:48Z","started_at":"2026-08-05T00:46:35Z","closed_at":"2026-08-05T00:49:48Z","close_reason":"Implemented server-side Web turn cancellation, authenticated cancel endpoint, immediate session event, UI Stop wiring, API test; task check and UI tests/build pass.","dependencies":[{"issue_id":"archie-core-3cf.15","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:46:31Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.14","title":"Chat parity: align shared and Telegram command catalogs","description":"Align command discovery with the commands actually handled by the shared gateway and Telegram adapter while preserving Telegram’s intentional hidden dangerous approval commands.","design":"Keep command execution unchanged. Extend the existing catalog entries with accurate descriptions and preserve the existing dangerous-command hiding rule; do not duplicate dispatch logic.","acceptance_criteria":"The shared gateway catalog includes /start and Telegram publishes /start; Telegram’s intentionally hidden /approve and /deny remain executable but undiscoverable; capability-specific dangerous commands remain correctly gated in Web; tests assert the published Telegram menu covers the non-hidden executable command surface.","status":"closed","priority":2,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:43:18Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:44:41Z","started_at":"2026-08-05T00:43:18Z","closed_at":"2026-08-05T00:44:41Z","close_reason":"Aligned command discovery without weakening the intentional dangerous-command hiding rule: /start is now in the shared gateway catalog and Telegram menu; Web slash completion inherits it. Focused and full task-check suites pass.","dependencies":[{"issue_id":"archie-core-3cf.14","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:43:17Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.13","title":"Web Chat: add contextual session lifecycle controls","description":"Expose Telegram session lifecycle actions directly in the Web Chat workspace while continuing to route them through the shared gateway.","design":"Use a native details popover in the workspace header, prompt only for title/branch names, and keep compression destructive work behind the existing gateway preview command. Do not add Web-only session semantics or duplicate command implementations.","acceptance_criteria":"An active Web session exposes retry, undo, title, branch, and compression preview actions; actions use shared commands, refresh the selected session/history, handle missing sessions and failures visibly, and remain keyboard accessible. Browser verification covers command dispatch and session refresh.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:41:24Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:42:41Z","started_at":"2026-08-05T00:41:25Z","closed_at":"2026-08-05T00:42:41Z","close_reason":"Added a contextual Web Chat session-actions menu for retry, undo, rename, branch, and compression preview. Actions dispatch shared gateway commands and refresh the active session/history. Playwright MCP verified the menu and /undo dispatch; npm tests/build and full task check pass.","dependencies":[{"issue_id":"archie-core-3cf.13","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:41:24Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
@@ -224,20 +233,20 @@
|
||||
{"_type":"issue","id":"archie-core-7ve","title":"test(gateway): the conformance suite does not pin what it claims, and the backends already drift","description":"The commit message for 3eb00db claims the shared suite means NellDB and SQLite 'cannot drift'. Two confirmed divergences it does not catch:\n\n1. testReplaceMessagesIsFailureSafe (sessionstore_conformance_test.go:769) never induces a failure -- four happy-path cases asserting the post-condition of a SUCCESSFUL call. Swapping the write and delete loops in session_store.go:696-708 would leave it green. Only SQLite has a real abort test, and it pins rollback, the opposite failure mode. The backends genuinely differ here: SQLite is atomic (failure -\u003e clean rollback), NellDB is not (failure -\u003e duplicates). SQLite's semantics are better; the point is the suite does not know.\n\n2. NellDB's lastTS cache is never invalidated by deletes; SQLite recomputes MAX(ts). Save at 13:00, delete it, save with At=12:00 -\u003e NellDB persists 13:00:00.001Z, SQLite persists 12:00:00Z. Both pass the suite.\n\n3. GetByChannel ordering differs between backends and is unpinned (see the newest-first bead).\n\n4. applyCompress has zero test coverage: no test in the package calls it, none of its three error returns is exercised, and fakeSessionStore.ReplaceMessages is a slice assignment that cannot observe ordering or identity.","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-03T16:01:53Z","created_by":"Sam Catlow","updated_at":"2026-08-03T16:01:53Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-la1","title":"fix(gateway): doc comments contradict the implementation in three places","description":"Each of these actively misleads, and one already caused a real bug:\n\n1. gateway.go:23-27 says MessageID is 'Populated on read; ignored on write.' Both stores honour an incoming MessageID in preference to deriving one (session_store.go:588, session_store_sqlite.go:291). This is exactly the misreading behind /branch copying parent history into the child under the PARENT's canonical IDs -- CONFIRMED on both backends, and newMessageID's own doc claims the opposite ('the same upstream message copied into a branch gets its own identity'). Two branches from one parent produce three sessions holding the same MessageID.\n\n2. session_store.go:405-409 describes msgID and a disambiguating counter, both deleted in this commit, and now sits above messageIDNamespace describing the opposite of the current design.\n\n3. telegram.go:474-477 still says a redelivered update 'updates the stored turn' -- the exact behaviour the immutability fix removed.","status":"closed","priority":2,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-03T16:01:53Z","created_by":"Sam Catlow","updated_at":"2026-08-04T12:25:28Z","started_at":"2026-08-04T12:23:28Z","closed_at":"2026-08-04T12:25:28Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-le6","title":"fix(gateway): assorted confirmed defects around the compress and undo paths","description":"Small, individually confirmed, none blocking on their own:\n\n1. session_commands.go:563 -- the compression summary is persisted as a USER turn. CompressHistory emits it with Role 'system' (compression.go:118) but the write-back only maps 'assistant' -\u003e Identity, so system falls through to 'user'. The model replays '[Earlier conversation has been summarised...]' as if the human said it. (Retained bot turns are handled correctly.)\n\n2. session_commands.go:488 -- compressPreview reads RecentMessages(200) while reporting count from MessageCount. With 100 large + 250 tiny messages the preview says 'Compression not needed (350 messages, ~0 tokens)' while apply on the same session reports '350 -\u003e 24 (~100000 -\u003e ~3063 tokens)'. The two numbers in one sentence describe different histories, and the preview advises against a compression that is needed.\n\n3. session_commands.go:329 -- handleUndo discards the deleted count from DeleteRecentMessages, so /undo 10 failing after 6 removals reports failure while six messages are gone.\n\n4. session_store.go:626 -- nextTimestamp has no upper bound and lastTimestamp re-reads from the store, so one future-dated write (host clock 24h fast) pins the session's clock for its lifetime; every later At handed to callers is wrong by a day.\n\n5. session_store.go:268 -- Close() calls s.store.Close() on the SHARED nl.Store (in production the daemon's tasks/events log) and, unlike every other method, does not take s.mu. Nothing calls it today.\n\n6. session_store.go:429 -- newMessageID's UUIDv5 input sessionID+\"\\x00\"+sourceID is not injectively encoded: newMessageID('a\\x00b','c') == newMessageID('a','b\\x00c'). No reachable input today; hardening, not a live bug.\n\n7. turns.go:79-85 -- Turns.lanes grows without bound; a lane is inserted per session key and never deleted. No goroutine leak.","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-03T16:01:53Z","created_by":"Sam Catlow","updated_at":"2026-08-03T16:01:53Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.5","title":"Add accessible interaction semantics across the dashboard","description":"Source review found navigation icons and a theme toggle that depend on visual glyphs or title text, and task rows are clickable table rows without keyboard semantics or an explicit expandable control. Audit the main pages for labels, focus visibility, keyboard operation, semantic headings and table behavior, status announcements, and sufficient non-color cues. Add automated DOM/accessibility-oriented regression tests for the critical controls.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-03T15:17:59Z","created_by":"Sam Catlow","updated_at":"2026-08-03T15:17:59Z","dependencies":[{"issue_id":"archie-core-3cf.5","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-04T01:17:59Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.5","title":"Add accessible interaction semantics across the dashboard","description":"Source review found navigation icons and a theme toggle that depend on visual glyphs or title text, and task rows are clickable table rows without keyboard semantics or an explicit expandable control. Audit the main pages for labels, focus visibility, keyboard operation, semantic headings and table behavior, status announcements, and sufficient non-color cues. Add automated DOM/accessibility-oriented regression tests for the critical controls.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-03T15:17:59Z","created_by":"Sam Catlow","updated_at":"2026-08-05T01:13:00Z","started_at":"2026-08-05T01:10:24Z","closed_at":"2026-08-05T01:13:00Z","close_reason":"Added explicit task timeline controls with keyboard operation, accessible state/relationships, focus styling, DOM regression coverage, Playwright verification, and task check.","dependencies":[{"issue_id":"archie-core-3cf.5","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-04T01:17:59Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.3","title":"Make dense dashboard views usable on narrow screens","description":"The responsive layout collapses the sidebar at 860px, but the dashboard relies on dense tables and multi-control filter rows without a documented table overflow/stacking treatment. Exercise dashboard, tasks, logs, workflows, settings, and channels at narrow viewport widths; fix clipping, horizontal scrolling ownership, control wrapping, and touch target sizing while preserving desktop density.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-03T15:17:40Z","created_by":"Sam Catlow","updated_at":"2026-08-03T16:08:59Z","started_at":"2026-08-03T15:55:36Z","closed_at":"2026-08-03T16:08:59Z","close_reason":"Completed responsive table containment across dashboard, tasks, settings, and workflows; added narrow-screen filter wrapping and grid shrink safeguards. Validated with ui npm test and npm run build; live daemon verification requires restarting the embedded UI bundle.","dependencies":[{"issue_id":"archie-core-3cf.3","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-04T01:17:39Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.4","title":"Improve operator orientation and safe refresh behavior","description":"The current shell has a minimal brand/sidebar, repeated bare actions, and limited indication of data freshness or which filters are active. Define a small consistent page-toolbar pattern with last-updated/loading/error states, clearer action labels, and preserved filter/navigation state across refresh and route changes. Keep the visual system lightweight and consistent with the existing dark/light themes.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-03T15:17:40Z","created_by":"Sam Catlow","updated_at":"2026-08-03T15:17:40Z","dependencies":[{"issue_id":"archie-core-3cf.4","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-04T01:17:40Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf","title":"[EPIC] Web UI polish and enhancements","description":"Polish and extend the Archie dashboard against the supplied reference design. Keep the UI a trustworthy operator control room: show real state, explain auth/connectivity failures, remain usable on narrow screens, make interactions accessible, and follow the reference composition and visual system. Existing feature issues for dashboard chat, configuration editing, and logs remain separate unless a child below explicitly coordinates with them.","acceptance_criteria":"Authenticated dashboard renders meaningful KPI values; unauthorised access has a clear recovery path; core navigation, tables, controls, and task interactions are keyboard/screen-reader usable; dense views remain usable on narrow viewports; the dashboard follows the supplied reference composition and visual treatment; each child has focused UI tests or runtime verification.","status":"open","priority":2,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-08-03T15:17:25Z","created_by":"Sam Catlow","updated_at":"2026-08-03T15:20:01Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-wb2","title":"feat(container): pass registry auth on image pull","description":"internal/container/pool.go:305 calls p.cli.ImagePull(ctx, ref, client.ImagePullOptions{}) with RegistryAuth never set, so the daemon talks to the Docker Engine API with no credentials. Against a private registry (git.catlow.cloud) every pull answers 401 regardless of pull_policy.\n\ndocker login does NOT help: it writes ~/.docker/config.json, which only the CLI reads. The operator has to pull by hand with the CLI so the daemon's pull_policy=missing check finds the image already present. That workaround is currently documented in CLAUDE.md as a hard constraint rather than fixed.\n\nFix: populate ImagePullOptions.RegistryAuth with a base64-encoded registry.AuthConfig, sourced from ~/.docker/config.json or an explicit [containers] credential. Removes a documented footgun and makes pull_policy actually mean what it says against private registries.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-03T15:12:16Z","created_by":"Sam Catlow","updated_at":"2026-08-03T15:12:16Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-afe","title":"feat(config): edit configuration from the dashboard (hybrid file + DB)","description":"Goal: change runtime-tunable settings from the web UI without hand-editing TOML.\n\nDecision (Sam, 2026-08-04): HYBRID, file stays primary. config.toml remains authoritative for bootstrap; a DB layer holds only runtime-tunable values as an overlay. Making the DB primary would move the thing that decides whether the daemon can boot into the thing the daemon must boot to read, and would lose the property that config is editable with any editor independent of daemon health.\n\nThe file format is NOT the blocker. Three things are, in this order:\n\n1. Config is passed BY VALUE. daemon.Daemon{Cfg config.Config} and workflow.Cfg config.Config each hold a copy made at construction, so mutating a central config would never reach them. Subsystems must read through an accessor or receive change events instead of holding snapshots. This is the real prerequisite.\n\n2. There is no reload path. No fsnotify, no SIGHUP, nothing -- Load runs once at startup. Changing the source without this only changes WHERE values come from, not WHEN.\n\n3. Startup is a hard gate. cmd/archied/main.go:588-598 exits the daemon when an MCP provider fails to start. A UI that writes bad config could brick the next boot, which is worse from a DB than from a file you can open in an editor. Writes need validation before persist, and a documented recovery path.\n\nAlready in our favour: internal/infrastructure/configuration/ is a real loader package (discovery, feature files, extras, defaults, validation, provenance, tomlwrite) and is already multi-source across TOML and YAML. A DB source is a new decoder alongside decodeTOML/decodeYAML, not a rewrite. provenance.go already tracks where each value came from, which is what the UI needs to show 'this came from the file, this from the DB'.\n\nRead-only config viewing already ships in the dashboard's Configuration section.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-03T14:43:43Z","created_by":"Sam Catlow","updated_at":"2026-08-03T14:43:43Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cy","title":"MCP servers are re-fetched from npm on every daemon start","description":"config.docker.toml launches desktop-commander with 'npx -y @wonderwhy-er/desktop-commander@0.2.46'. The container has no persistent npm cache, so every restart re-resolves and re-downloads the package and its puppeteer browser payload. That is slow, makes startup depend on npm registry availability, and turns a registry outage or a yanked version into a daemon outage. It also amplified the crash loop observed on 2026-07-30, since each restart repeated the whole download.","acceptance_criteria":"Daemon startup does not depend on reaching the npm registry. Either the MCP servers are installed into the image at build time and invoked directly, or the npm cache is persisted across restarts. Startup time no longer scales with the size of the server's dependency tree.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-30T06:49:29Z","created_by":"Sam Catlow","updated_at":"2026-07-30T06:49:29Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-ts9","title":"[BUG] find fallback reports a cancelled walk as 'no matches found'","description":"runFindGoFallback's walk callback swallows every per-entry error (returns nil to skip inaccessible entries), so the only error that can escape filepath.WalkDir is ctx.Err() from the cancellation select. The guard 'if err != nil \u0026\u0026 !errors.Is(err, ctx.Err())' therefore never fires: on timeout or /stop the function falls through and returns whatever it had collected, or 'no matches found' when it had collected nothing. This is the same failure the grep exit-code bug had -- the model is told a search found nothing when the search did not finish. Behaviour predates 6d4e0be; the errors.Is autofix in that commit is behaviour-neutral here (errors.Is(err, nil) is false for non-nil err, matching the old err != ctx.Err() when the context is live).","acceptance_criteria":"A find whose context is cancelled mid-walk returns an error result naming the cancellation, not 'no matches found' and not a silently partial list. Regression test in the style of TestGrepReportsSearchFailureRatherThanNoMatches.","notes":"Evidence, gathered while auditing 6d4e0be for archie-core-ifi. The swallow is\nat internal/tools/builtin/find.go:169-171 -- the WalkDir callback returns nil\nfor every per-entry error (\"skip inaccessible entries\"). The only error that\ncan reach the guard at find.go:242 is ctx.Err(), returned by the cancellation\nselect at find.go:173-177, and the guard exists specifically to ignore that.\nSo the guard can never fire, and a cancelled walk falls through to the\nlen(matches)==0 check at find.go:245 and returns Content:\"no matches found\",\nIsError:false -- the same false-negative shape as the grep exit-code bug.\n\nThe linter is already pointing at this. golangci-lint reports nilerr on the\nidentical swallow in internal/tools/builtin/grep.go:380 and :411, so grep's\ndirect-search path likely has the same hole; that was not in scope for the\naudit and is not verified. Whoever fixes this should check both files, and\nshould decide the harder question the bug hides: partial results from a\ncancelled walk are currently returned as if complete, so \"report the\ncancellation\" has to choose between discarding them and labelling them.\n\nLeft as-is deliberately. The audit's scope was behaviour CHANGES in 6d4e0be\nand this predates it -- the errors.Is rewrite in that commit is neutral here.","status":"open","priority":2,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:19:00Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:26:25Z","dependencies":[{"issue_id":"archie-core-ts9","depends_on_id":"archie-core-ifi","type":"discovered-from","created_at":"2026-07-30T02:18:59Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-ts9","title":"[BUG] find fallback reports a cancelled walk as 'no matches found'","description":"runFindGoFallback's walk callback swallows every per-entry error (returns nil to skip inaccessible entries), so the only error that can escape filepath.WalkDir is ctx.Err() from the cancellation select. The guard 'if err != nil \u0026\u0026 !errors.Is(err, ctx.Err())' therefore never fires: on timeout or /stop the function falls through and returns whatever it had collected, or 'no matches found' when it had collected nothing. This is the same failure the grep exit-code bug had -- the model is told a search found nothing when the search did not finish. Behaviour predates 6d4e0be; the errors.Is autofix in that commit is behaviour-neutral here (errors.Is(err, nil) is false for non-nil err, matching the old err != ctx.Err() when the context is live).","acceptance_criteria":"A find whose context is cancelled mid-walk returns an error result naming the cancellation, not 'no matches found' and not a silently partial list. Regression test in the style of TestGrepReportsSearchFailureRatherThanNoMatches.","notes":"Evidence, gathered while auditing 6d4e0be for archie-core-ifi. The swallow is\nat internal/tools/builtin/find.go:169-171 -- the WalkDir callback returns nil\nfor every per-entry error (\"skip inaccessible entries\"). The only error that\ncan reach the guard at find.go:242 is ctx.Err(), returned by the cancellation\nselect at find.go:173-177, and the guard exists specifically to ignore that.\nSo the guard can never fire, and a cancelled walk falls through to the\nlen(matches)==0 check at find.go:245 and returns Content:\"no matches found\",\nIsError:false -- the same false-negative shape as the grep exit-code bug.\n\nThe linter is already pointing at this. golangci-lint reports nilerr on the\nidentical swallow in internal/tools/builtin/grep.go:380 and :411, so grep's\ndirect-search path likely has the same hole; that was not in scope for the\naudit and is not verified. Whoever fixes this should check both files, and\nshould decide the harder question the bug hides: partial results from a\ncancelled walk are currently returned as if complete, so \"report the\ncancellation\" has to choose between discarding them and labelling them.\n\nLeft as-is deliberately. The audit's scope was behaviour CHANGES in 6d4e0be\nand this predates it -- the errors.Is rewrite in that commit is neutral here.","status":"closed","priority":2,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:19:00Z","created_by":"Sam Catlow","updated_at":"2026-08-05T01:53:09Z","started_at":"2026-08-05T01:51:34Z","closed_at":"2026-08-05T01:53:09Z","close_reason":"Fixed the cancellation guard; runFindGoFallback now returns an error result when ctx.Err() fires instead of falling through to 'no matches found'. Test + fix in 6d47fb3.","dependencies":[{"issue_id":"archie-core-ts9","depends_on_id":"archie-core-ifi","type":"discovered-from","created_at":"2026-07-30T02:18:59Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-60f","title":"Seed a default SOUL without clobbering user edits","description":"Write a starter SOUL on first run and allow upgrading untouched scaffolding in place, following Hermes' is_legacy_template_soul approach: compare normalised content against known-shipped templates, which carry zero user intent, and only replace on an exact match.","acceptance_criteria":"First run seeds a documented starter SOUL. A SOUL matching a known shipped template can be upgraded in place. A SOUL the user has edited in any way is never modified. Comparison normalises line endings and trailing whitespace so a CRLF checkout does not defeat it.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:58Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:09:58Z","dependencies":[{"issue_id":"archie-core-60f","depends_on_id":"archie-core-4gv","type":"parent-child","created_at":"2026-07-30T02:09:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t08","title":"Reconcile SOUL with PersonaRegistry and the six built-in personas","description":"Decide what happens to DefaultPersonas() (archie, helpful, concise, technical, creative, teacher) and the /personality command once SOUL owns identity. Options: SOUL replaces the default archie persona and the rest remain selectable style modifiers; or personas become seed templates a user copies into their SOUL; or personas are retired. Currently GetActive composes the baseline archie prompt with the selected persona, so the interaction with SOUL must be explicit rather than emergent.","acceptance_criteria":"Precedence between SOUL and a selected persona is defined and documented. /personality either keeps working with stated semantics or is removed deliberately. No path lets a persona selection blank out the user's SOUL without them asking.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:57Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:09:57Z","dependencies":[{"issue_id":"archie-core-t08","depends_on_id":"archie-core-4gv","type":"parent-child","created_at":"2026-07-30T02:09:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3fb","title":"worktree.Manager gets an empty token when the forge degrades","description":"Since 518a1a0 a missing forge credential disables the forge instead of stopping archied. resolveForge returns an empty token in that case and cmd/archied/main.go still hands it to worktree.Manager{Token: token}. If repos are configured while the forge is disabled, clone/push fails at push time rather than at startup. This is the intended trade -- a deferred error beats a crash loop -- but the failure is currently discovered late and its message will not explain that the cause is an unconfigured forge.","acceptance_criteria":"A worktree operation attempted with no forge credential fails with a message naming the missing forge configuration as the cause, rather than a bare git transport error. Alternatively the manager refuses the operation up front. Either way the operator can tell why from the error alone.","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:21Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:09:21Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-bfw","title":"install.sh: --force is advertised but does nothing","description":"FORCE_BUILD is initialised at install.sh:42 and set at :67 by --force, then never read. --help advertises '--force Force rebuild binaries even if up to date', so the flag is documented, accepted, and inert. The build step always rebuilds unconditionally, which means the flag is either redundant (delete it and the help line) or the up-to-date check it implies was never written.","acceptance_criteria":"Either the flag and its help text are removed, or an up-to-date check exists that --force actually bypasses. No advertised flag is inert.","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:02Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:09:02Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-c6o","title":"install.sh: unknown flags are silently ignored","description":"The 'for arg in $@' case statement has no default branch, so a mistyped flag does nothing and the installer proceeds with defaults. '--no-systmd' installs the systemd service the user was trying to skip. Options discussed 2026-07-30: (a) reject unknown args with exit 1; (b) warn on stderr and continue; (c) reject unknown --flags but ignore bare words. Recommendation was (a) -- this is an interactive installer run by hand, typos dominate, and silent wrong behaviour is the worst outcome; the forward-compatibility argument for (b) does not apply while there is no ecosystem of wrapper scripts. Awaiting Sam's decision.","acceptance_criteria":"A mistyped flag produces a clear diagnostic rather than silently different behaviour. The chosen policy is applied consistently and reflected in --help.","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:02Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:09:02Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-utt","title":"install.sh: linger detection claims success it did not verify","description":"install.sh greps 'loginctl show-user $USER' for 'Linger=no'. When show-user fails or prints nothing -- no logind session, a container, USER unset -- the grep fails and control falls to the else branch, which prints '[OK] User linger is already enabled.' Nothing was verified and linger is never enabled, so systemd --user dies at logout. Worst for someone installing on a remote box over SSH: Archie works while they are connected and stops when they disconnect. Discussed 2026-07-30, fix agreed but not applied.","acceptance_criteria":"Detection tests for the positive (Linger=yes) and attempts enable-linger in every other case, including when show-user fails. Uses $(id -un) rather than $USER, which is unset in some container and cron contexts and would abort under set -u. enable-linger is idempotent so a redundant call is harmless. No branch claims linger is enabled without having observed it.","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:01Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:09:01Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3fb","title":"worktree.Manager gets an empty token when the forge degrades","description":"Since 518a1a0 a missing forge credential disables the forge instead of stopping archied. resolveForge returns an empty token in that case and cmd/archied/main.go still hands it to worktree.Manager{Token: token}. If repos are configured while the forge is disabled, clone/push fails at push time rather than at startup. This is the intended trade -- a deferred error beats a crash loop -- but the failure is currently discovered late and its message will not explain that the cause is an unconfigured forge.","acceptance_criteria":"A worktree operation attempted with no forge credential fails with a message naming the missing forge configuration as the cause, rather than a bare git transport error. Alternatively the manager refuses the operation up front. Either way the operator can tell why from the error alone.","status":"closed","priority":2,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:21Z","created_by":"Sam Catlow","updated_at":"2026-08-05T01:55:45Z","started_at":"2026-08-05T01:53:12Z","closed_at":"2026-08-05T01:55:45Z","close_reason":"Push now checks the worktree's origin remote for an HTTP(S) scheme and fails immediately naming the missing forge.token config, instead of letting go-git fail late with a bare transport error. Local transports unaffected. 69bc618.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-bfw","title":"install.sh: --force is advertised but does nothing","description":"FORCE_BUILD is initialised at install.sh:42 and set at :67 by --force, then never read. --help advertises '--force Force rebuild binaries even if up to date', so the flag is documented, accepted, and inert. The build step always rebuilds unconditionally, which means the flag is either redundant (delete it and the help line) or the up-to-date check it implies was never written.","acceptance_criteria":"Either the flag and its help text are removed, or an up-to-date check exists that --force actually bypasses. No advertised flag is inert.","status":"closed","priority":2,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:02Z","created_by":"Sam Catlow","updated_at":"2026-08-05T01:57:21Z","started_at":"2026-08-05T01:55:50Z","closed_at":"2026-08-05T01:57:21Z","close_reason":"Removed --force and its help line rather than fake an up-to-date check go build's own cache already makes unnecessary. 625e0ba.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-c6o","title":"install.sh: unknown flags are silently ignored","description":"The 'for arg in $@' case statement has no default branch, so a mistyped flag does nothing and the installer proceeds with defaults. '--no-systmd' installs the systemd service the user was trying to skip. Options discussed 2026-07-30: (a) reject unknown args with exit 1; (b) warn on stderr and continue; (c) reject unknown --flags but ignore bare words. Recommendation was (a) -- this is an interactive installer run by hand, typos dominate, and silent wrong behaviour is the worst outcome; the forward-compatibility argument for (b) does not apply while there is no ecosystem of wrapper scripts. Awaiting Sam's decision.","acceptance_criteria":"A mistyped flag produces a clear diagnostic rather than silently different behaviour. The chosen policy is applied consistently and reflected in --help.","status":"closed","priority":2,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:02Z","created_by":"Sam Catlow","updated_at":"2026-08-05T01:57:22Z","started_at":"2026-08-05T01:55:50Z","closed_at":"2026-08-05T01:57:22Z","close_reason":"Added a default case: unknown options now print a diagnostic naming the flag and exit 1, per the agreed (a) option. 625e0ba.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-utt","title":"install.sh: linger detection claims success it did not verify","description":"install.sh greps 'loginctl show-user $USER' for 'Linger=no'. When show-user fails or prints nothing -- no logind session, a container, USER unset -- the grep fails and control falls to the else branch, which prints '[OK] User linger is already enabled.' Nothing was verified and linger is never enabled, so systemd --user dies at logout. Worst for someone installing on a remote box over SSH: Archie works while they are connected and stops when they disconnect. Discussed 2026-07-30, fix agreed but not applied.","acceptance_criteria":"Detection tests for the positive (Linger=yes) and attempts enable-linger in every other case, including when show-user fails. Uses $(id -un) rather than $USER, which is unset in some container and cron contexts and would abort under set -u. enable-linger is idempotent so a redundant call is harmless. No branch claims linger is enabled without having observed it.","status":"closed","priority":2,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:09:01Z","created_by":"Sam Catlow","updated_at":"2026-08-05T01:57:22Z","started_at":"2026-08-05T01:55:50Z","closed_at":"2026-08-05T01:57:22Z","close_reason":"Detection now requires positive Linger=yes and falls through to enable-linger (idempotent) on any other outcome, including a failed/empty loginctl call; uses $(id -un) instead of $USER. 625e0ba.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-547","title":"install.sh delegates config generation to archied setup","description":"Remove the TOML-generating branches from install.sh and call the binary it just built. Ends the class of bug where the installer's idea of the config schema drifts from the daemon's.","acceptance_criteria":"install.sh contains no TOML templates and no sed-patching of config files. It invokes archied setup for a fresh install and skips it when a config already exists. A non-interactive install still produces a valid config or fails loudly. The forge_block helper and its awk splice are deleted.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-29T16:02:51Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:02:51Z","dependencies":[{"issue_id":"archie-core-547","depends_on_id":"archie-core-cbk","type":"blocks","created_at":"2026-07-30T02:02:56Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-547","depends_on_id":"archie-core-ewk","type":"parent-child","created_at":"2026-07-30T02:02:50Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-114","title":"Curator observability surface","description":"Give curator activity visibility: which curators are registered, when each last ran, what it changed, and why. Background agents mutating memory unobserved is the failure mode this epic most needs to avoid.","acceptance_criteria":"Registered curators, their schedule state, and their recent activity are inspectable at runtime. Each recorded action carries enough context to answer why it happened. Surfaced through the existing observability paths rather than a bespoke channel.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T15:48:01Z","created_by":"Sam Catlow","updated_at":"2026-07-29T15:48:01Z","dependencies":[{"issue_id":"archie-core-114","depends_on_id":"archie-core-yp9","type":"parent-child","created_at":"2026-07-30T01:48:01Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-pek","title":"Bind curators to memory engines","description":"Wire the attached-memory-engine part of a curator's declared shape once the memory engine family exists, so a curator reads and writes through the engine contract rather than a concrete store.","acceptance_criteria":"A curator declares which memory engine it uses and receives it as a typed dependency. Swapping the configured engine changes where a curator's memories land with no change to the curator. A curator with no declared memory engine is a valid configuration and is rejected only if it attempts a memory operation.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-29T15:48:01Z","created_by":"Sam Catlow","updated_at":"2026-07-29T15:48:01Z","dependencies":[{"issue_id":"archie-core-pek","depends_on_id":"archie-core-1x7","type":"blocks","created_at":"2026-07-30T01:48:14Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-pek","depends_on_id":"archie-core-yp9","type":"parent-child","created_at":"2026-07-30T01:48:00Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
|
||||
@@ -21,9 +21,8 @@ authoritative**. It is a design to implement against — not a draft to extend.
|
||||
|
||||
- Do **not** produce new architecture documents, migration plans, ownership
|
||||
ledgers, field-level inventories, current-state traces, decision records, or
|
||||
review campaigns. If a design question isn't answered in
|
||||
`docs/architecture/`, ask the maintainer in one sentence — don't write a
|
||||
document to resolve it.
|
||||
review campaigns. If a design question isn't answered in `docs/architecture/`,
|
||||
ask the maintainer in one sentence — don't write a document to resolve it.
|
||||
- Do **not** open planning, review, or refactor issues. Open issues only for
|
||||
concrete bugs and user-facing features.
|
||||
- This is a **solo project**. There is no review board, no handoff to a
|
||||
@@ -34,9 +33,9 @@ authoritative**. It is a design to implement against — not a draft to extend.
|
||||
|
||||
## Deployment model
|
||||
|
||||
**archied runs on the host under systemd.** Its chat tools operate on host
|
||||
files (shell, read, write, edit, find, grep), which a container cannot reach.
|
||||
NATS and per-task archie-agent containers stay in Docker.
|
||||
**archied runs on the host under systemd.** Its chat tools operate on host files
|
||||
(shell, read, write, edit, find, grep), which a container cannot reach. NATS and
|
||||
per-task archie-agent containers stay in Docker.
|
||||
|
||||
```bash
|
||||
# On the deployment host (carina):
|
||||
@@ -48,23 +47,23 @@ docker compose pull agent # refresh agent image after CI pushes
|
||||
|
||||
**The daemon hands agent containers its own `nats.url` verbatim**
|
||||
(`internal/daemon/daemon.go:1177`), so that URL must reachable from both the
|
||||
host *and* from inside containers. Use the compose network's gateway address
|
||||
(`172.19.0.1:4222`), not the service name or localhost. The subnet is pinned
|
||||
in `docker-compose.yml` so this address cannot drift.
|
||||
host _and_ from inside containers. Use the compose network's gateway address
|
||||
(`172.19.0.1:4222`), not the service name or localhost. The subnet is pinned in
|
||||
`docker-compose.yml` so this address cannot drift.
|
||||
|
||||
**`containers.pull_policy` can only be `"missing"`** (the default) or
|
||||
`"always"`. `"always"` against the private Gitea registry answers 401 because
|
||||
the daemon sends no credentials to the Docker API. Refresh the agent image by
|
||||
hand: `docker compose pull agent`.
|
||||
|
||||
**`docker-compose.yml`** carries only NATS and the agent build stanza. The
|
||||
agent has a build profile so `up -d` skips it — without the profile, compose
|
||||
creates a container that exits 0 immediately and reports "Started", which
|
||||
reads as a crash loop. `docker compose build agent` and `docker compose pull
|
||||
agent` still work by name without activating the profile.
|
||||
**`docker-compose.yml`** carries only NATS and the agent build stanza. The agent
|
||||
has a build profile so `up -d` skips it — without the profile, compose creates a
|
||||
container that exits 0 immediately and reports "Started", which reads as a crash
|
||||
loop. `docker compose build agent` and `docker compose pull agent` still work by
|
||||
name without activating the profile.
|
||||
|
||||
**Config lives at `~/.config/archie/config.toml`**, outside the repo. Nothing
|
||||
in the repo working tree is load-bearing at runtime. The reference template is
|
||||
**Config lives at `~/.config/archie/config.toml`**, outside the repo. Nothing in
|
||||
the repo working tree is load-bearing at runtime. The reference template is
|
||||
`deployments/docker-nats-stack.toml`.
|
||||
|
||||
## Release process
|
||||
@@ -82,14 +81,14 @@ task release VERSION=1.3.0 # commit + tag
|
||||
git push origin main --follow-tags # CI stamps images with real versions
|
||||
```
|
||||
|
||||
Pass `GATEWAY=<ver>`/`RUNTIME=<ver>` to version them independently, or `skip`
|
||||
to hold one back. Linting ensures the changelogs can be parsed deterministically
|
||||
by `tools/release.sh`.
|
||||
Pass `GATEWAY=<ver>`/`RUNTIME=<ver>` to version them independently, or `skip` to
|
||||
hold one back. Linting ensures the changelogs can be parsed deterministically by
|
||||
`tools/release.sh`.
|
||||
|
||||
CI (`deploy.yml`) now runs a gate job *before* building images: `task check`,
|
||||
then verifies that any release tag at HEAD has a matching `[version]` section
|
||||
in the corresponding changelog. A tag without a changelog entry is a hard
|
||||
failure. No tags at HEAD prints a warning (images get stamped `dev`).
|
||||
CI (`deploy.yml`) now runs a gate job _before_ building images: `task check`,
|
||||
then verifies that any release tag at HEAD has a matching `[version]` section in
|
||||
the corresponding changelog. A tag without a changelog entry is a hard failure.
|
||||
No tags at HEAD prints a warning (images get stamped `dev`).
|
||||
|
||||
## Build & Test
|
||||
|
||||
@@ -126,17 +125,17 @@ flat layout keeps regrowing, and undoing it is measured in weeks.
|
||||
|
||||
- **`internal/domain/<area>/`** — one cohesive job Archie performs. Owns that
|
||||
job's language, state, rules, operations, commands, events, policy
|
||||
implementations, runtime settings, and the *contracts* it needs from the
|
||||
implementations, runtime settings, and the _contracts_ it needs from the
|
||||
outside world. A domain declares the interface it needs; it never names who
|
||||
implements it.
|
||||
- **`internal/infrastructure/<service>/`** — implementations of those
|
||||
contracts: configuration, persistence, forge clients, event-bus transports,
|
||||
anything that talks to something external.
|
||||
- **`internal/infrastructure/<service>/`** — implementations of those contracts:
|
||||
configuration, persistence, forge clients, event-bus transports, anything that
|
||||
talks to something external.
|
||||
- **`internal/app/<application>/`** — composition. Constructs domains and
|
||||
infrastructure, translates external configuration into domain settings,
|
||||
connects commands and events, starts services in dependency order, owns
|
||||
health aggregation and shutdown ordering. It is the only layer that knows
|
||||
about both of the two above.
|
||||
connects commands and events, starts services in dependency order, owns health
|
||||
aggregation and shutdown ordering. It is the only layer that knows about both
|
||||
of the two above.
|
||||
- **`cmd/<binary>/`** — process-level input only: flags, environment, signals.
|
||||
It MUST NOT contain substantive wiring and MUST NOT act as a service locator.
|
||||
|
||||
@@ -151,8 +150,8 @@ changing.
|
||||
`cmd → app → {domain, infrastructure}`, and `infrastructure → domain` to
|
||||
implement its contracts. Nothing points back up: a domain importing
|
||||
infrastructure, or infrastructure importing app, is a defect regardless of how
|
||||
convenient it is. If a domain needs something an infrastructure package has,
|
||||
the domain declares an interface and app wires the implementation in.
|
||||
convenient it is. If a domain needs something an infrastructure package has, the
|
||||
domain declares an interface and app wires the implementation in.
|
||||
|
||||
### Cross-cutting packages
|
||||
|
||||
@@ -175,31 +174,30 @@ nobody can say what they are. `utils`, `helpers`, `common` and `misc` are
|
||||
prohibited for the same reason: if a package cannot be named for what it
|
||||
provides, it is misplaced, not shared.
|
||||
|
||||
Cross-cutting utilities exist precisely to keep the code DRY — a function
|
||||
owned by no single package and used by many. Do not wait for a second consumer
|
||||
to justify one, and do not copy a helper into two domains to avoid creating
|
||||
one. (The "second consumer" rule below is about feature code, not this.)
|
||||
Cross-cutting utilities exist precisely to keep the code DRY — a function owned
|
||||
by no single package and used by many. Do not wait for a second consumer to
|
||||
justify one, and do not copy a helper into two domains to avoid creating one.
|
||||
(The "second consumer" rule below is about feature code, not this.)
|
||||
|
||||
### Within a package: organise by concern, never by layer or type
|
||||
|
||||
- One file per API area, named for it: `api_tasks.go`, `api_logs.go`,
|
||||
`api_skills.go`. A new endpoint group is a new file. Cross-cutting wiring
|
||||
gets its own file too: `server.go` (routes and construction only), `auth.go`,
|
||||
`api_skills.go`. A new endpoint group is a new file. Cross-cutting wiring gets
|
||||
its own file too: `server.go` (routes and construction only), `auth.go`,
|
||||
`sse.go`.
|
||||
- **A package owns its own format end to end.** `internal/logging` defines the
|
||||
on-disk log format *and* reads it (`reader.go`); `internal/webui/api_logs.go`
|
||||
on-disk log format _and_ reads it (`reader.go`); `internal/webui/api_logs.go`
|
||||
is transport and parses nothing. If two packages both know a format, one of
|
||||
them is wrong.
|
||||
- Empty or ceremonial `entities`, `repositories` or `services` layers are
|
||||
prohibited. Code that changes together lives together.
|
||||
- No grab-bag file. If you cannot name a file after the single thing it does,
|
||||
it is doing more than one thing.
|
||||
- No grab-bag file. If you cannot name a file after the single thing it does, it
|
||||
is doing more than one thing.
|
||||
|
||||
### Frontend
|
||||
|
||||
- One folder per feature under `ui/src/<feature>/`, holding its own `.js` and
|
||||
`.css`, with the JS importing its own CSS. Changing logs cannot disturb
|
||||
tasks.
|
||||
`.css`, with the JS importing its own CSS. Changing logs cannot disturb tasks.
|
||||
- Shared primitives live in `ui/src/base/` and `ui/src/css/`, one file per
|
||||
primitive (`button.css`, `card.css`, `pill.css`, `table.css`).
|
||||
- Extract a feature's code into a shared primitive on the **second** real
|
||||
@@ -218,8 +216,8 @@ A domain that declares its own contracts can be tested, reviewed, replaced and
|
||||
reasoned about without the rest of the system. Once the direction of dependency
|
||||
inverts anywhere, that stops being true everywhere downstream. It also has an
|
||||
immediate cost with parallel sessions: `cmd/archied/main.go` had to be split
|
||||
hunk-by-hunk three times in one day because two sessions were editing it at
|
||||
once — a symptom of wiring living where it should not.
|
||||
hunk-by-hunk three times in one day because two sessions were editing it at once
|
||||
— a symptom of wiring living where it should not.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -248,31 +246,31 @@ boundaries. Summary of what's evolved since that doc was last fully accurate:
|
||||
### Per-package traps (things an agent will break if it doesn't check first)
|
||||
|
||||
- **`internal/channels/telegram/`** — the long-polling branch calls
|
||||
`dropPendingUpdates(ctx, b)` before `go b.Start(ctx)`. This clears
|
||||
Telegram's 24h undelivered-update queue so a reboot doesn't answer
|
||||
hours-old messages. It also runs on `/restart`. The webhook branch already
|
||||
passes `DropPendingUpdates: true` in `SetWebhookParams`; both paths must
|
||||
stay consistent.
|
||||
`dropPendingUpdates(ctx, b)` before `go b.Start(ctx)`. This clears Telegram's
|
||||
24h undelivered-update queue so a reboot doesn't answer hours-old messages. It
|
||||
also runs on `/restart`. The webhook branch already passes
|
||||
`DropPendingUpdates: true` in `SetWebhookParams`; both paths must stay
|
||||
consistent.
|
||||
- **`internal/container/pool.go` `WriteTaskJSON`** — the per-task boot brief
|
||||
goes to `<worktree>/.git/task.json`, not the worktree root.
|
||||
`worktree.CommitAll` stages via go-git `Add{All:true}`, which ignores
|
||||
`.gitignore` and `.git/info/exclude`, so anything in the worktree root is
|
||||
pushed onto the task branch. Nothing under `.git` can be tracked;
|
||||
`worktree.go:41-46` documents this reasoning for the prepared sentinel.
|
||||
If you change the path, update `cmd/archie-agent/main.go` `bootTaskID`
|
||||
(the reader) in lockstep.
|
||||
- **MCP providers are registered by the daemon as *optional*** (`cmd/archied/
|
||||
main.go`, `providerRegistry.RegisterOptional`). One that cannot start is
|
||||
logged at error level, excluded from the running set, and reported through
|
||||
`Registry.Health` as degraded — it does not roll back the other providers
|
||||
or stop the daemon. That was previously a hard failure, so one broken npm
|
||||
package unregistered every builtin tool and crash-looped archied under
|
||||
`Restart=on-failure`, taking Telegram with it. Providers the daemon
|
||||
`worktree.go:41-46` documents this reasoning for the prepared sentinel. If you
|
||||
change the path, update `cmd/archie-agent/main.go` `bootTaskID` (the reader)
|
||||
in lockstep.
|
||||
- **MCP providers are registered by the daemon as _optional_**
|
||||
(`cmd/archied/ main.go`, `providerRegistry.RegisterOptional`). One that cannot
|
||||
start is logged at error level, excluded from the running set, and reported
|
||||
through `Registry.Health` as degraded — it does not roll back the other
|
||||
providers or stop the daemon. That was previously a hard failure, so one
|
||||
broken npm package unregistered every builtin tool and crash-looped archied
|
||||
under `Restart=on-failure`, taking Telegram with it. Providers the daemon
|
||||
genuinely requires still use `Register` and keep atomic rollback; check
|
||||
`providerRegistry.Skipped()` when tools are mysteriously missing. No
|
||||
npx-launched servers are configured in production anyway — the builtin
|
||||
tools (read, write, edit, find, grep, shell, test) cover what
|
||||
desktop-commander did.
|
||||
npx-launched servers are configured in production anyway — the builtin tools
|
||||
(read, write, edit, find, grep, shell) and `web_fetch`. There is no `test`
|
||||
tool; gates run test commands, the model does not.
|
||||
|
||||
**Task lifecycle** (from ARCHITECTURE.md, still current):
|
||||
`queued → running(workflow:stage) → pr_open → merged|rejected`, with
|
||||
@@ -290,7 +288,7 @@ behavior.
|
||||
|
||||
## Conventions
|
||||
|
||||
- Go 1.26.3, module `github.com/samcharles93/archie-core`.
|
||||
- Go 1.26.5, module `github.com/samcharles93/archie-core`.
|
||||
- `ai-sdk/runtime`, `ai-sdk/agentloop`, `ai-sdk/core` are external other
|
||||
projects, not vendored copies. Changes affect other repos.
|
||||
- Non-interactive shell commands only: some environments alias `cp`/`mv`/`rm` to
|
||||
|
||||
+139
-14
@@ -10,6 +10,7 @@ import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -56,6 +57,7 @@ import (
|
||||
builtintoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/builtin"
|
||||
mcptoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
|
||||
memorytoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/memory"
|
||||
"github.com/samcharles93/archie-core/internal/tools/webfetch"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
"github.com/samcharles93/archie-core/internal/workflow/skillbuild"
|
||||
"github.com/samcharles93/archie-core/internal/workflow/wfeval"
|
||||
@@ -76,12 +78,6 @@ func main() {
|
||||
const (
|
||||
// defaultChatMaxSteps bounds the model/tool round-trips in one chat
|
||||
// turn when [config.ChatConfig.MaxSteps] is unset.
|
||||
//
|
||||
// It was 8, which is roughly one read, one grep and a couple of edits
|
||||
// -- less than a single small change to a Go package costs. Turns hit
|
||||
// the cap and stopped mid-task with no indication they had been cut
|
||||
// off. Interruption is /stop's job; this only has to stop a genuine
|
||||
// runaway, so it is set well above real work.
|
||||
defaultChatMaxSteps = 100
|
||||
packagedGatewayChangelogPath = "/usr/share/archie/CHANGELOG.archied.md"
|
||||
packagedRuntimeChangelogPath = "/usr/share/archie/CHANGELOG.archie.md"
|
||||
@@ -95,15 +91,24 @@ var (
|
||||
runtimeVersion = "dev"
|
||||
)
|
||||
|
||||
// chatGenerateOptions builds one chat turn's request.
|
||||
func chatGenerateOptions(
|
||||
messages []chat.Message,
|
||||
registry *tools.Registry,
|
||||
maxSteps int,
|
||||
limits agentexec.ToolLimits,
|
||||
extra []tools.ToolEntry,
|
||||
) (core.GenerateOptions, error) {
|
||||
toolSet, err := agentexec.BuildToolSet(registry)
|
||||
toolOpts := limits.Options()
|
||||
toolSet, err := agentexec.BuildToolSet(registry, toolOpts)
|
||||
if err != nil {
|
||||
return core.GenerateOptions{}, err
|
||||
}
|
||||
extraSet, err := agentexec.BuildToolSetFrom(extra, toolOpts)
|
||||
if err != nil {
|
||||
return core.GenerateOptions{}, err
|
||||
}
|
||||
maps.Copy(toolSet, extraSet)
|
||||
if maxSteps <= 0 {
|
||||
maxSteps = defaultChatMaxSteps
|
||||
}
|
||||
@@ -114,6 +119,71 @@ func chatGenerateOptions(
|
||||
}, nil
|
||||
}
|
||||
|
||||
// isWithin reports whether target sits inside base.
|
||||
func isWithin(base, target string) bool {
|
||||
absBase, err := filepath.Abs(base)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
absTarget, err := filepath.Abs(target)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
rel, err := filepath.Rel(absBase, absTarget)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
|
||||
}
|
||||
|
||||
// toolLimits reads the configured per-turn result limits.
|
||||
func toolLimits(cfg config.Config) agentexec.ToolLimits {
|
||||
return agentexec.ToolLimits{
|
||||
MaxResultChars: cfg.Tools.Policy.MaxResultChars,
|
||||
TurnBudgetChars: cfg.Tools.Policy.TurnBudgetChars,
|
||||
SpillDir: cfg.Tools.Policy.SpillDir,
|
||||
}
|
||||
}
|
||||
|
||||
// taskListOverRead multiplies the requested limit when reading rows that are
|
||||
// filtered by identity afterwards.
|
||||
const taskListOverRead = 5
|
||||
|
||||
// chatTaskListerAdapter gives the gateway a read view of one identity's tasks.
|
||||
// gateway deliberately does not import internal/store, so the projection
|
||||
// happens here, as it does for the writer and controller adapters below.
|
||||
type chatTaskListerAdapter struct {
|
||||
tasks func(context.Context, int) ([]store.Task, error)
|
||||
}
|
||||
|
||||
func (a chatTaskListerAdapter) ListChatTasks(ctx context.Context, identity string, limit int) ([]gateway.ChatTaskSummary, error) {
|
||||
// Over-read before filtering: Tasks applies its limit across the whole
|
||||
// table, so asking for exactly `limit` would return fewer than that for
|
||||
// this identity whenever another identity's work is more recent.
|
||||
rows, err := a.tasks(ctx, limit*taskListOverRead)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]gateway.ChatTaskSummary, 0, limit)
|
||||
for _, task := range rows {
|
||||
if task.Identity != identity {
|
||||
continue
|
||||
}
|
||||
if len(out) >= limit {
|
||||
break
|
||||
}
|
||||
out = append(out, gateway.ChatTaskSummary{
|
||||
ID: task.ID,
|
||||
Repo: task.Owner + "/" + task.Repo,
|
||||
Title: task.Title,
|
||||
Status: task.Status,
|
||||
Workflow: task.Workflow,
|
||||
PRNumber: task.PRNumber,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func configuredMCPProvider(server config.MCPServer) (toolprovider.Engine, error) {
|
||||
name := strings.TrimSpace(server.Name)
|
||||
if name == "" {
|
||||
@@ -394,21 +464,27 @@ func run() int {
|
||||
}
|
||||
}
|
||||
webRouter.Models = chatModels
|
||||
webRouter.Updates = updateService
|
||||
if updateService != nil {
|
||||
webRouter.Updates = updateService
|
||||
}
|
||||
webRouter.Personas = personas
|
||||
webRouter.InitSessions(chatSessionStore)
|
||||
configureTaskCommands(webRouter, chatTasks, chatController, defaultChatIdentity)
|
||||
webSetup := telegramSetup{
|
||||
Cfg: cfg, St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg,
|
||||
Personas: personas, ChatTasks: chatTasks, ChatController: chatController,
|
||||
ChatTaskLister: chatTaskListerAdapter{tasks: st.Tasks},
|
||||
DefaultChatIdentity: defaultChatIdentity, SessionStore: chatSessionStore,
|
||||
Bus: bus, Log: log,
|
||||
}
|
||||
webRouter.LLM, webRouter.LLMStream = makeChatLLMResponder(ctx, "web", webSetup, chatSessionStore, webRouter)
|
||||
webRouter.LLM, webRouter.LLMStream = makeChatLLMResponder("web", webSetup, chatSessionStore, webRouter)
|
||||
web.Chat = &webui.ChatService{
|
||||
Router: webRouter, Sessions: chatSessionStore,
|
||||
Turns: gateway.NewTurns(log),
|
||||
Models: chatModels, Personas: personas, Updates: updateService,
|
||||
Models: chatModels, Personas: personas,
|
||||
}
|
||||
if updateService != nil {
|
||||
web.Chat.Updates = updateService
|
||||
}
|
||||
if l := cfg.Web.Listen; l != "" && l != "off" {
|
||||
web.Token = webTokenFor(l, cfg.DBPath, log)
|
||||
@@ -426,6 +502,7 @@ func run() int {
|
||||
Cfg: cfg, CfgPath: *cfgPath, OverlayPath: *overlayPath,
|
||||
St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg,
|
||||
Personas: personas, ChatTasks: chatTasks, ChatController: chatController,
|
||||
ChatTaskLister: chatTaskListerAdapter{tasks: st.Tasks},
|
||||
DefaultChatIdentity: defaultChatIdentity, SessionStore: chatSessionStore, Updates: updateService,
|
||||
Bus: bus,
|
||||
RegisterRestart: func(request func() error) { restartTelegram = request }, Log: log,
|
||||
@@ -485,7 +562,9 @@ func run() int {
|
||||
Providers: providers,
|
||||
}
|
||||
case "inprocess":
|
||||
agentRunner = agentexec.NewInProcessRunner(llm, log, toolReg)
|
||||
inproc := agentexec.NewInProcessRunner(llm, log, toolReg)
|
||||
inproc.Limits = toolLimits(cfg)
|
||||
agentRunner = inproc
|
||||
case "nats":
|
||||
if natsClient == nil {
|
||||
log.Error("agent.mode is nats but [nats] is not configured")
|
||||
@@ -581,7 +660,9 @@ func run() int {
|
||||
Providers: idProviders,
|
||||
}
|
||||
case "inprocess":
|
||||
runner.Agent = agentexec.NewInProcessRunner(idRuntime, log.With("identity", idCfg.Name), toolReg)
|
||||
idRunner := agentexec.NewInProcessRunner(idRuntime, log.With("identity", idCfg.Name), toolReg)
|
||||
idRunner.Limits = toolLimits(cfg)
|
||||
runner.Agent = idRunner
|
||||
case "nats":
|
||||
runner.Agent = &agentexec.NATSRunner{
|
||||
Bus: natsClient, Providers: idProviders,
|
||||
@@ -698,11 +779,16 @@ func run() int {
|
||||
// configured: these read, write and execute, so the directory is a
|
||||
// deliberate choice rather than a default.
|
||||
if workspace := cfg.Chat.Workspace; workspace != "" {
|
||||
if err := providerRegistry.Register(builtintoolprovider.New(workspace)); err != nil {
|
||||
unrestricted := cfg.Chat.UnrestrictedFilesystem
|
||||
if err := providerRegistry.Register(builtintoolprovider.New(workspace, unrestricted)); err != nil {
|
||||
log.Error("workspace tool provider registration failed", "err", err)
|
||||
return 1
|
||||
}
|
||||
log.Info("workspace tools enabled", "workspace", workspace)
|
||||
// Logged at the same level either way: which of the two postures is
|
||||
// running is the first thing worth knowing when a file tool refuses a
|
||||
// path, or reaches one it should not have.
|
||||
log.Info("workspace tools enabled",
|
||||
"workspace", workspace, "unrestricted_filesystem", unrestricted)
|
||||
} else {
|
||||
log.Info("workspace tools disabled (chat.workspace is unset)")
|
||||
}
|
||||
@@ -741,6 +827,45 @@ func run() int {
|
||||
}
|
||||
}
|
||||
|
||||
// Tool results too large to inline are written here. Created once, at
|
||||
// startup: the write failure inside a turn is silent, so without this
|
||||
// every oversized result would quietly fall back to truncation and
|
||||
// spilling would look configured while doing nothing.
|
||||
if spillDir := cfg.Tools.Policy.SpillDir; spillDir != "" {
|
||||
if err := toolLimits(cfg).EnsureSpillDir(); err != nil {
|
||||
log.Warn("tool spill directory unavailable; large results will be truncated instead", "err", err)
|
||||
} else if ws := cfg.Chat.Workspace; ws != "" && !cfg.Chat.UnrestrictedFilesystem && !isWithin(ws, spillDir) {
|
||||
// A spill hands the model a path to read back, and a confined read
|
||||
// tool refuses anything outside the workspace. Outside it, the
|
||||
// spill reference is a dead end and the result is lost rather than
|
||||
// displaced -- worse than truncating in the first place.
|
||||
//
|
||||
// Not a concern when the filesystem is unrestricted: the read tool
|
||||
// can reach the spill wherever it lives.
|
||||
log.Warn("tool spill directory is outside chat.workspace; the model cannot read back what is spilled there",
|
||||
"spill_dir", spillDir, "workspace", ws)
|
||||
}
|
||||
}
|
||||
|
||||
// web_fetch. Registered directly rather than as a tool provider: it has
|
||||
// no process to start or stop, so the provider lifecycle would buy
|
||||
// nothing. Disabled by configuration returns nil and advertises nothing.
|
||||
if entry := webfetch.Tool(webfetch.Config{
|
||||
Enabled: cfg.Tools.WebFetch.IsEnabled(),
|
||||
Timeout: cfg.Tools.WebFetch.Timeout.Std(),
|
||||
MaxBytes: cfg.Tools.WebFetch.MaxBytes,
|
||||
AllowPrivateNetworks: cfg.Tools.WebFetch.AllowPrivateNetworks,
|
||||
}); entry != nil {
|
||||
if err := toolReg.Register(*entry); err != nil {
|
||||
log.Warn("web_fetch registration failed", "err", err)
|
||||
} else {
|
||||
log.Info("web fetch enabled",
|
||||
"allow_private_networks", cfg.Tools.WebFetch.AllowPrivateNetworks)
|
||||
}
|
||||
} else {
|
||||
log.Info("web fetch disabled")
|
||||
}
|
||||
|
||||
// Built-in tools are registered at startup via init(). Tool discovery
|
||||
// via Yaegi is deferred to the container/agent runtime.
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -17,6 +16,7 @@ import (
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
@@ -39,7 +39,7 @@ import (
|
||||
func TestResolveForgeDegradesInsteadOfFailing(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -90,7 +90,7 @@ func TestResolveForgeDegradesInsteadOfFailing(t *testing.T) {
|
||||
// Not parallel: t.Setenv mutates process state and panics under t.Parallel.
|
||||
func TestResolveForgeBuildsClientWhenTokenResolves(t *testing.T) {
|
||||
t.Setenv("ARCHIE_TEST_FORGE_TOKEN", "ghp_exampletoken")
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
client, token := resolveForge(config.Forge{
|
||||
Type: "github",
|
||||
@@ -200,7 +200,7 @@ func TestChatGenerateOptionsIncludesToolsAndMultipleSteps(t *testing.T) {
|
||||
}
|
||||
messages := []chat.Message{{Role: chat.RoleUser, Content: "remember this"}}
|
||||
|
||||
options, err := chatGenerateOptions(messages, registry, 0)
|
||||
options, err := chatGenerateOptions(messages, registry, 0, agentexec.ToolLimits{}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -226,7 +226,7 @@ func TestChatGenerateOptionsReportsInvalidToolSchemas(t *testing.T) {
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := chatGenerateOptions(nil, registry, 0); err == nil {
|
||||
if _, err := chatGenerateOptions(nil, registry, 0, agentexec.ToolLimits{}, nil); err == nil {
|
||||
t.Fatal("chatGenerateOptions() error = nil, want invalid tool schema error")
|
||||
}
|
||||
}
|
||||
@@ -235,7 +235,7 @@ func TestChatGenerateOptionsReportsInvalidToolSchemas(t *testing.T) {
|
||||
// deployment-controlled. A cap that cannot be raised without a rebuild is
|
||||
// the situation this replaced.
|
||||
func TestChatGenerateOptionsHonoursConfiguredMaxSteps(t *testing.T) {
|
||||
options, err := chatGenerateOptions(nil, tools.NewRegistry(), 250)
|
||||
options, err := chatGenerateOptions(nil, tools.NewRegistry(), 250, agentexec.ToolLimits{}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ type telegramSetup struct {
|
||||
Personas *gateway.PersonaRegistry
|
||||
ChatTasks gateway.TaskCreator
|
||||
ChatController gateway.TaskController
|
||||
ChatTaskLister gateway.ChatTaskLister
|
||||
DefaultChatIdentity string
|
||||
SessionStore gateway.SessionStore
|
||||
Updates telegram.UpdateService
|
||||
@@ -164,20 +165,26 @@ func buildTelegramRouter(ctx context.Context, tg *telegram.Gateway, s telegramSe
|
||||
router.InitSessions(sessionStore)
|
||||
configureTaskCommands(router, s.ChatTasks, s.ChatController, s.DefaultChatIdentity)
|
||||
|
||||
router.LLM, router.LLMStream = makeChatLLMResponder(ctx, tg.Name(), s, sessionStore, router)
|
||||
router.LLM, router.LLMStream = makeChatLLMResponder(tg.Name(), s, sessionStore, router)
|
||||
return router
|
||||
}
|
||||
|
||||
func makeChatLLMResponder(ctx context.Context, channel string, s telegramSetup, sessionStore gateway.SessionStore, router *gateway.Router) (gateway.LLMResponder, gateway.LLMStreamResponder) {
|
||||
func makeChatLLMResponder(
|
||||
channel string,
|
||||
s telegramSetup,
|
||||
sessionStore gateway.SessionStore,
|
||||
router *gateway.Router,
|
||||
) (gateway.LLMResponder, gateway.LLMStreamResponder) {
|
||||
if s.LLM == nil {
|
||||
return nil, nil
|
||||
}
|
||||
// Built once: these carry this gateway's identity, which does not change
|
||||
// between turns, so there is nothing per-turn to rebuild.
|
||||
taskTools := gateway.TaskTools(s.ChatTaskLister, s.ChatTasks, s.DefaultChatIdentity)
|
||||
respond := func(ctx context.Context, msg gateway.Message, onDelta func(string)) (string, error) {
|
||||
// Resolve through the router's session tracker, not a local
|
||||
// channel-keyed helper. They agree until /new, /branch or /resume
|
||||
// assigns a session a generated id; from then on the commands and
|
||||
// the conversation address different histories, so /new would report
|
||||
// history cleared while the next turn still saw all of it.
|
||||
// Use the router's session tracker, not a local channel-keyed helper.
|
||||
// Commands like /new, /branch, or /resume may reassign a session to a
|
||||
// generated ID; after that, only the router sees the correct history.
|
||||
sk, err := router.ResolveSessionKey(ctx, msg)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve chat session: %w", err)
|
||||
@@ -186,12 +193,10 @@ func makeChatLLMResponder(ctx context.Context, channel string, s telegramSetup,
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("load chat history: %w", err)
|
||||
}
|
||||
// A redelivered update must not be answered twice. The store already
|
||||
// refuses to store the message again, but that alone changed
|
||||
// nothing here: the model still ran, costing a second billed turn,
|
||||
// running any tool side effects again, and appending a second reply
|
||||
// (replies carry no upstream reference, so they always append).
|
||||
// Replaying the answer we already gave is both cheaper and correct.
|
||||
// Deduplicate redelivered updates: the store already rejects the
|
||||
// duplicate message, but that alone doesn't prevent a second model
|
||||
// call with its cost and side effects. Replaying the prior reply
|
||||
// is both cheaper and correct.
|
||||
if prior := gateway.PriorReply(history, sk, msg.SourceID, s.Cfg.BotUser); prior != "" {
|
||||
s.Log.Info("replaying the reply to a redelivered message",
|
||||
"session", sk, "source_id", msg.SourceID)
|
||||
@@ -204,10 +209,8 @@ func makeChatLLMResponder(ctx context.Context, channel string, s telegramSetup,
|
||||
return "", fmt.Errorf("save inbound chat message: %w", err)
|
||||
}
|
||||
history = append(history, msg)
|
||||
// Chat turns were entirely unlogged, so a report of lost context had
|
||||
// no evidence to check against: session id, history depth and the
|
||||
// resolved persona are the three things needed to tell "wrong
|
||||
// session" from "history not loaded".
|
||||
// Log session id, history depth, and resolved persona to
|
||||
// distinguish "wrong session" bugs from "history not loaded".
|
||||
s.Log.Info("chat turn",
|
||||
"session", sk,
|
||||
"channel", msg.ChannelID,
|
||||
@@ -222,7 +225,7 @@ func makeChatLLMResponder(ctx context.Context, channel string, s telegramSetup,
|
||||
compressed = append(compressed, gateway.CompressedMessage{Role: role, Content: h.Text})
|
||||
}
|
||||
view := gateway.CompressHistory(compressed, gateway.DefaultCompressionConfig())
|
||||
options, err := chatGenerateOptions(nil, s.ToolReg, s.Cfg.Chat.MaxSteps)
|
||||
options, err := chatGenerateOptions(nil, s.ToolReg, s.Cfg.Chat.MaxSteps, toolLimits(s.Cfg), taskTools)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("build chat tools: %w", err)
|
||||
}
|
||||
|
||||
+112
-41
@@ -1,20 +1,25 @@
|
||||
# archied configuration. Copy to ~/.config/archie/config.toml.
|
||||
# Secrets are NOT configured here directly: each one is a {engine, key}
|
||||
# reference resolved through a secrets engine at startup. The built-in
|
||||
# "env" engine reads key as an environment variable name. Custom engines
|
||||
# (sops, bws, vault/openbao, ...) are Yaegi plugins loaded from a
|
||||
# directory -- see internal/secret.
|
||||
#
|
||||
# archied configuration
|
||||
#
|
||||
# Secrets are NOT stored here: each one is a {engine, key}
|
||||
# reference resolved through a secrets engine at startup.
|
||||
# The built-in "env" engine reads key as an environment variable name.
|
||||
# Custom engines (sops, bws, vault/openbao, ...)
|
||||
# are Yaegi plugins loaded from a directory -- see internal/secret.
|
||||
# secret_engine_dir = "~/.config/archie/secret-engines"
|
||||
|
||||
# work_dir = "~/.local/share/archie/work" # default
|
||||
# db_path = "~/.local/share/archie/archie.db"
|
||||
|
||||
poll_interval = "60s"
|
||||
label = "archie"
|
||||
bot_user = "vectis-labs-archie"
|
||||
diff_cap_lines = 400
|
||||
# max_retries = 3 # how many operator-triggered retries a parked task gets
|
||||
# before it moves to dead (global default; set per-repo to
|
||||
# override). Enforced by the dashboard's retry action.
|
||||
|
||||
# how many operator-triggered retries a parked task gets
|
||||
# before it moves to dead (global default; set per-repo to
|
||||
# override). Enforced by the dashboard's retry action.
|
||||
# max_retries = 3
|
||||
|
||||
[forge]
|
||||
type = "github"
|
||||
@@ -22,9 +27,21 @@ host = "https://github.com"
|
||||
token = { engine = "env", key = "ARCHIE_GITHUB_TOKEN" }
|
||||
|
||||
[dispatch]
|
||||
trigger = "assignee" # "assignee", "label", or "either"
|
||||
ack_reaction = "eyes" # "off" disables pickup reactions
|
||||
# Can be of "assignee", "label", or "either"
|
||||
# this sets the method archie uses to pick up tasks.
|
||||
trigger = "assignee"
|
||||
|
||||
# Optionally set a reaction to show that archie has picked up a task.
|
||||
# setting this to "off" disables the pickup reactions.
|
||||
ack_reaction = "eyes"
|
||||
|
||||
# dispatch.labels maps each task lifecycle state to the label
|
||||
# Archie applies on the issue.
|
||||
# You can rename labels to match your project's conventions,
|
||||
# or comment one out to skip that transition.
|
||||
# The labels are the *source of truth* for the dispatch loop: Archie
|
||||
# scans for issues bearing queued, then moves them through working →
|
||||
# waiting → pr → parked (→ dead when max_retries is exhausted).
|
||||
[dispatch.labels]
|
||||
queued = "archie:queued"
|
||||
working = "archie:working"
|
||||
@@ -33,7 +50,7 @@ pr = "archie:pr"
|
||||
parked = "archie:parked"
|
||||
# dead = "archie:dead" # state label for a task that exhausted max_retries
|
||||
|
||||
[models] # role -> ai-sdk runtime ref (used by agent workflows, Phase 4b)
|
||||
[models] # role -> ai-sdk runtime ref (used by agent workflows)
|
||||
triage = "openai/gpt-5.4"
|
||||
planner = "openai/gpt-5.4"
|
||||
builder = "openai/gpt-5.4"
|
||||
@@ -46,30 +63,34 @@ api_key = { engine = "bws", key = "OPENAI_API_KEY" }
|
||||
[providers.ollama]
|
||||
class = "ollama"
|
||||
|
||||
# Optional interactive-chat catalog. /provider groups these references by
|
||||
# their first path segment, and /model shows only the selected provider's
|
||||
# entries. When omitted, Archie uses the distinct refs in [models].
|
||||
#
|
||||
# `operator` is the display name of the person this deployment assists. It is
|
||||
# [chat]
|
||||
# `operator` is the display name of user. It is
|
||||
# passed to the chat agent as runtime metadata, which means it is sent to the
|
||||
# configured model provider on every turn -- leave it unset to tell the agent
|
||||
# nothing about who is running it.
|
||||
#
|
||||
# operator = "John Smith"
|
||||
|
||||
# `workspace` roots the chat agent's file and shell tools (read, write, edit,
|
||||
# shell, grep, find). Unset, those tools are not registered at all. Set it and
|
||||
# the agent can read, modify and execute inside that directory with the same
|
||||
# reach the daemon process has -- choose it deliberately.
|
||||
#
|
||||
# `max_steps` caps the model/tool round-trips in a single chat turn
|
||||
# (default 100). This is a task budget, not a safety limit: one question
|
||||
# about a codebase easily costs a read, several greps and a few edits, and
|
||||
# a turn that runs out stops mid-task looking like it gave up. To interrupt
|
||||
# a turn, send /stop -- that cancels it immediately and clears anything
|
||||
# queued behind it.
|
||||
# [chat]
|
||||
# operator = "Ada Lovelace"
|
||||
# shell, grep, find). If unser, the tools aren't registered.
|
||||
# Set it to let the agent read, modify and execute inside that directory
|
||||
# choose it deliberately
|
||||
# workspace = "~/.local/share/archie/workspace"
|
||||
|
||||
# `max_steps` caps the model/tool round-trips in a single chat turn
|
||||
# (default 100). This is a task budget, not a safety limit.
|
||||
# max_steps = 100
|
||||
|
||||
# Let read/write/edit/find/grep tools reach absolute paths outside the
|
||||
# workspace jail. Relative paths still resolve against workspace.
|
||||
# The shell tool is never confined, so a jail only pushes the agent into
|
||||
# using shell for everything, losing truncation, line numbering, and
|
||||
# read-before-write protection. Enable when the agent needs to work
|
||||
# cross-filesystem (disk ops, system edits, etc.). Grant deliberately.
|
||||
# unrestricted_filesystem = true
|
||||
|
||||
# Optional interactive-chat catalog. /provider groups these references by
|
||||
# their first path segment, and /model shows only the selected provider's
|
||||
# entries. When omitted, Archie uses the distinct refs in [models].
|
||||
# models = [
|
||||
# "openai/gpt-5.6-sol",
|
||||
# "openrouter/openai/gpt-5.6-sol",
|
||||
@@ -91,20 +112,36 @@ class = "ollama"
|
||||
# work_dir = "/path/to/workspace"
|
||||
|
||||
[agent]
|
||||
mode = "inprocess" # "subprocess" runs each stage through archie-agent (stdin/stdout); "nats" sends stages over NATS
|
||||
command = "archie-agent" # executable path for subprocess mode (not used in nats mode)
|
||||
# Subprocess mode isolates the protocol and process lifecycle, not OS privileges.
|
||||
# The worker still runs as the daemon user until the Docker sandbox phase lands.
|
||||
# env = ["GOCACHE"] # extra environment variable names forwarded to the worker
|
||||
# How the daemon invokes the agent:
|
||||
# "inprocess" – run agent logic directly in the daemon (default)
|
||||
# "subprocess" – spawn `command` as a child, communicating over stdin/stdout
|
||||
# "nats" – dispatch tasks over NATS (requires [nats]; add [containers] for Docker sandboxing)
|
||||
mode = "inprocess"
|
||||
# Binary to launch when mode = "subprocess".
|
||||
command = "archie-agent"
|
||||
# Environment variables forwarded to the agent process (subprocess/nats modes).
|
||||
# env = ["GOCACHE"]
|
||||
|
||||
[indexing] # workspace codesearch index; both paths default under work_dir
|
||||
# index_dir = "/var/lib/archie/indexes" # codesearch sidecar files
|
||||
# db_path = "/var/lib/archie/workspace-indexes.db" # index lifecycle metadata
|
||||
# Workspace code-search index. Paths default under work_dir when unset.
|
||||
[indexing]
|
||||
# Code-search index files (default: <work_dir>/indexes).
|
||||
# index_dir = "/var/lib/archie/indexes"
|
||||
# Per-index lifecycle metadata DB (default: <work_dir>/workspace-indexes.db).
|
||||
# db_path = "/var/lib/archie/workspace-indexes.db"
|
||||
|
||||
[web] # observability dashboard (read-only, no auth -- keep it local/tailnet)
|
||||
listen = "127.0.0.1:8484" # "off" disables
|
||||
# Web dashboard and API: task board, activity stream, chat, config,
|
||||
# logs, memory, SSE events. Served as an embedded SPA with a full REST
|
||||
# and streaming API. Auth is token-based for non-loopback addresses;
|
||||
# loopback binds (127.0.0.1, ::1, localhost) skip auth automatically.
|
||||
# Set to "off" (or leave empty) to disable.
|
||||
[web]
|
||||
listen = "127.0.0.1:8484"
|
||||
|
||||
[notify] # optional webhook for human-in-the-loop moments (n8n -> email)
|
||||
# Notifications for human-in-the-loop moments
|
||||
# (approval requests, gate failures, parked tasks).
|
||||
# Archie POSTs a JSON payload to the webhook
|
||||
# wire it to n8n, email, Slack, or any HTTP endpoint.
|
||||
[notify]
|
||||
# webhook = "https://n8n.example.com/webhook/archie"
|
||||
|
||||
[budgets]
|
||||
@@ -157,3 +194,37 @@ gate_max_failures = 5
|
||||
# # (e.g. different base branches or packages per task). Still bounded by
|
||||
# # [containers].max_concurrency globally.
|
||||
# # persistent_storage = true # reuse a per-repo Docker volume and Git object cache until volume_ttl
|
||||
|
||||
# ── Tools ───────────────────────────────────────────────────────────────────
|
||||
# Limits on what a tool may return. These bound how much of the context window
|
||||
# one tool call can spend: the workspace file tools truncate themselves, but
|
||||
# skill bodies and MCP server results otherwise arrive whole.
|
||||
#
|
||||
# Zero (or absent) takes the default. A NEGATIVE value disables the limit --
|
||||
# zero cannot mean "off" because it is indistinguishable from an unset key.
|
||||
# [tools.tool_policy]
|
||||
# max_result_chars = 50000 # cap on one tool result; -1 for no cap
|
||||
# turn_budget_chars = 200000 # cap on all tool results in one chat turn; -1 for no cap
|
||||
# spill_dir = "" # unset by default, which truncates oversized results
|
||||
# # inline. When set, a result over the cap is written
|
||||
# # here in full and the model is handed the path.
|
||||
# # It MUST be inside chat.workspace: the read tool
|
||||
# # refuses paths outside it, so a spill anywhere else
|
||||
# # is a reference the model cannot open -- worse than
|
||||
# # truncating. Startup warns if it is outside.
|
||||
# # Task agents work in their own worktree and cannot
|
||||
# # read it at all; they always truncate.
|
||||
|
||||
# The web_fetch tool: retrieve a URL and return readable text.
|
||||
# [tools.web_fetch]
|
||||
# enabled = true # set false to withdraw the tool entirely
|
||||
# timeout = "30s"
|
||||
# max_bytes = 2000000
|
||||
# allow_private_networks = false
|
||||
# # Off by default, and worth leaving off. archied's own dashboard, NATS and
|
||||
# # the Docker API answer on loopback and private addresses, and the URL to
|
||||
# # fetch arrives through chat -- an untrusted path, since a forge issue body
|
||||
# # or an inbound email can be quoted into a turn. The address is checked at
|
||||
# # dial time rather than on the URL string, so a public name that resolves to
|
||||
# # a private address is refused too. Turn this on only for a homelab endpoint
|
||||
# # you intend Archie to reach.
|
||||
@@ -1,42 +1,42 @@
|
||||
module github.com/samcharles93/archie-core
|
||||
|
||||
go 1.26.3
|
||||
go 1.26.5
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.6.0
|
||||
github.com/google/go-github/v78 v78.0.0
|
||||
modernc.org/sqlite v1.54.0
|
||||
modernc.org/sqlite v1.56.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/42wim/httpsig v1.2.4 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/ProtonMail/go-crypto v1.4.1 // indirect
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.2 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cloudflare/circl v1.6.3 // indirect
|
||||
github.com/cloudflare/circl v1.6.4 // indirect
|
||||
github.com/containerd/errdefs v1.0.0 // indirect
|
||||
github.com/containerd/errdefs/pkg v0.3.0 // indirect
|
||||
github.com/davidmz/go-pageant v1.0.2 // indirect
|
||||
github.com/distribution/reference v0.6.0 // indirect
|
||||
github.com/docker/go-connections v0.7.0 // indirect
|
||||
github.com/docker/go-connections v0.8.1 // indirect
|
||||
github.com/docker/go-units v0.5.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/emirpasic/gods v1.18.1 // indirect
|
||||
github.com/felixge/httpsnoop v1.0.4 // indirect
|
||||
github.com/felixge/httpsnoop v1.1.0 // indirect
|
||||
github.com/go-fed/httpsig v1.1.0 // indirect
|
||||
github.com/go-git/gcfg/v2 v2.0.2 // indirect
|
||||
github.com/go-git/go-billy/v6 v6.0.0-alpha.1 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-git/go-billy/v6 v6.0.0-alpha.2 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/google/go-querystring v1.1.0 // indirect
|
||||
github.com/google/go-querystring v1.2.0 // indirect
|
||||
github.com/google/go-tpm v0.9.8 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/hashicorp/go-version v1.9.0 // indirect
|
||||
github.com/kevinburke/ssh_config v1.6.0 // indirect
|
||||
github.com/klauspost/compress v1.18.6 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/klauspost/compress v1.19.1 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/minio/highwayhash v1.0.4 // indirect
|
||||
github.com/moby/docker-image-spec v1.3.1 // indirect
|
||||
github.com/nats-io/jwt/v2 v2.8.2 // indirect
|
||||
@@ -50,33 +50,33 @@ require (
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/sergi/go-diff v1.4.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 // indirect
|
||||
go.opentelemetry.io/otel v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.44.0 // indirect
|
||||
golang.org/x/crypto v0.53.0 // indirect
|
||||
golang.org/x/net v0.55.0 // indirect
|
||||
golang.org/x/sync v0.21.0 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 // indirect
|
||||
go.opentelemetry.io/otel v1.45.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.45.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.45.0 // indirect
|
||||
golang.org/x/crypto v0.54.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
modernc.org/libc v1.74.1 // indirect
|
||||
modernc.org/libc v1.74.4 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
code.gitea.io/sdk/gitea v0.25.1
|
||||
github.com/go-git/go-git/v6 v6.0.0-alpha.4
|
||||
github.com/go-telegram/bot v1.22.0
|
||||
github.com/go-git/go-git/v6 v6.0.0-alpha.5
|
||||
github.com/go-telegram/bot v1.23.0
|
||||
github.com/google/codesearch v1.3.0-rc.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/moby/moby/api v1.55.0
|
||||
github.com/moby/moby/client v0.5.0
|
||||
github.com/nats-io/nats-server/v2 v2.14.3
|
||||
github.com/moby/moby/client v0.5.1
|
||||
github.com/nats-io/nats-server/v2 v2.14.4
|
||||
github.com/nats-io/nats.go v1.52.0
|
||||
github.com/samcharles93/NellDB v0.3.0
|
||||
github.com/samcharles93/ai-sdk v0.1.19
|
||||
github.com/samcharles93/NellDB v0.3.1
|
||||
github.com/samcharles93/ai-sdk v0.1.20
|
||||
github.com/traefik/yaegi v0.16.1
|
||||
golang.org/x/term v0.44.0
|
||||
golang.org/x/net v0.57.0
|
||||
golang.org/x/term v0.45.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
@@ -12,6 +12,8 @@ github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFI
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op h1:Z/MZK75wC/NSrkgqeNIa7jexam9uWzhLmFTSCPI/kn0=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.2 h1:oEEedg1Xgi8drRjqB0f9tfjhLoInE0IYZfZ6zAhQUbY=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.2/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI=
|
||||
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
|
||||
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
@@ -20,6 +22,8 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
|
||||
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
|
||||
github.com/cloudflare/circl v1.6.4 h1:pOXuDTCEYyzydgUpQ0CQz3LsinKjiSk6nNP5Lt5K64U=
|
||||
github.com/cloudflare/circl v1.6.4/go.mod h1:YxarevkLlbaHuWsxG6vmYNWBEsSp4pnp7j+4VljMavY=
|
||||
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
|
||||
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
||||
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
|
||||
@@ -33,6 +37,8 @@ github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5Qvfr
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
|
||||
github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
|
||||
github.com/docker/go-connections v0.8.1 h1:JibmG5hULs5qXSr/cp/w3Pw5fZuStt4MOHMUExb29/M=
|
||||
github.com/docker/go-connections v0.8.1/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
@@ -41,6 +47,8 @@ github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc
|
||||
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
|
||||
github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
|
||||
github.com/go-fed/httpsig v1.1.0 h1:9M+hb0jkEICD8/cAiNqEB66R87tTINszBRTjwjQzWcI=
|
||||
@@ -49,26 +57,37 @@ github.com/go-git/gcfg/v2 v2.0.2 h1:MY5SIIfTGGEMhdA7d7JePuVVxtKL7Hp+ApGDJAJ7dpo=
|
||||
github.com/go-git/gcfg/v2 v2.0.2/go.mod h1:/lv2NsxvhepuMrldsFilrgct6pxzpGdSRC13ydTLSLs=
|
||||
github.com/go-git/go-billy/v6 v6.0.0-alpha.1 h1:xVjAR4oUvrKy7/Xuw/lLlV3gkxR3KO2H8W+MamuVVsQ=
|
||||
github.com/go-git/go-billy/v6 v6.0.0-alpha.1/go.mod h1:eaCUpHbedW7//EwcYmUDfJe2N6sJC9O12AT0OTqJR1E=
|
||||
github.com/go-git/go-billy/v6 v6.0.0-alpha.2 h1:1Sv5WemXL8CxKrAx1gioJ+uHNb2bZJhiQLfwSZ4Et8c=
|
||||
github.com/go-git/go-billy/v6 v6.0.0-alpha.2/go.mod h1:r/bsv9i/iDyyEU8/Z6mjC+YraOVwie1ddfUqBCElKXQ=
|
||||
github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1 h1:gmqi2jvsreu0s8JMLylYDFq4sbjHwwlhktMw0DUg3mA=
|
||||
github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1/go.mod h1:ECf1MqJlBdYpKggBrOXjo/0EnvRZx6D++I86UYjPgAQ=
|
||||
github.com/go-git/go-git/v6 v6.0.0-alpha.4 h1:aDTc2UGanmaE7FkGLSlBEB9nohMnQ+RKXcfq/D+esDQ=
|
||||
github.com/go-git/go-git/v6 v6.0.0-alpha.4/go.mod h1:4ODa/G7hPWrh4Y+7lmt59Ij3zW38IEfvRoAZxLYYBhc=
|
||||
github.com/go-git/go-git/v6 v6.0.0-alpha.5 h1:sE+OlkHgYWNMVmN1s9sR7uyFgsWLtxcNWse/vBYKxRE=
|
||||
github.com/go-git/go-git/v6 v6.0.0-alpha.5/go.mod h1:3IjhiZnM+uBmUrOGSeqrJpsmi4Vd0H2NZO/uK2a7d0s=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-telegram/bot v1.22.0 h1:zK29OoTYMmR5emJrCtGa2SjaGleeZiUB/C1i7kc2lXE=
|
||||
github.com/go-telegram/bot v1.22.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
|
||||
github.com/go-telegram/bot v1.23.0 h1:CKKQq115G/GUGBG8uuWl5uXbiBHyVjZBp/qqOLWZjJk=
|
||||
github.com/go-telegram/bot v1.23.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
|
||||
github.com/google/codesearch v1.3.0-rc.1 h1:vSFGuF5wS3sjimuLzqPG+PGjWQ9VvEtPFbxdZD7YuuQ=
|
||||
github.com/google/codesearch v1.3.0-rc.1/go.mod h1:hKdpx7wOsvk2WLT/D6NLPxFeLT8jKCehZu21JpA2rIY=
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/go-github/v78 v78.0.0 h1:b1tytzFE8i//lRVDx5Qh/EdJbtTPtSVD3nF7hraEs9w=
|
||||
github.com/google/go-github/v78 v78.0.0/go.mod h1:Uxvdzy82AkNlC6JQ57se9TqvmgBT7RF0ouHDNg2jd6g=
|
||||
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
|
||||
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
|
||||
github.com/google/go-querystring v1.2.0 h1:yhqkPbu2/OH+V9BfpCVPZkNmUXhb2gBxJArfhIxNtP0=
|
||||
github.com/google/go-querystring v1.2.0/go.mod h1:8IFJqpSRITyJ8QhQ13bmbeMBDfmeEJZD5A0egEOmkqU=
|
||||
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
|
||||
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
@@ -87,8 +106,12 @@ github.com/kevinburke/ssh_config v1.6.0 h1:J1FBfmuVosPHf5GRdltRLhPJtJpTlMdKTBjRg
|
||||
github.com/kevinburke/ssh_config v1.6.0/go.mod h1:q2RIzfka+BXARoNexmF9gkxEX7DmvbW9P4hIVx2Kg4M=
|
||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
@@ -98,6 +121,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4=
|
||||
@@ -108,12 +133,16 @@ github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc=
|
||||
github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
|
||||
github.com/moby/moby/client v0.5.0 h1:5XhyPk2fuOWf6RlSFa3MkIIgDZkF25xToXW8Q/BH7cc=
|
||||
github.com/moby/moby/client v0.5.0/go.mod h1:rcVpF8ncl9vo5gaIBdol6CnbEtSj1uxMvEV/UrykF/s=
|
||||
github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw=
|
||||
github.com/moby/moby/client v0.5.1/go.mod h1:odLstlZ6uSnfvAgVxMpvgmb8SUdd+siH2T0GBuxVAlM=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
|
||||
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
|
||||
github.com/nats-io/nats-server/v2 v2.14.3 h1:+xjydPt7rkit67G+04TN0mcO2n+8nveZE7tK/PPV53A=
|
||||
github.com/nats-io/nats-server/v2 v2.14.3/go.mod h1:5IlCtBzfwyzQzPMjmoJ9W2/LKmnJRtNyuOs/OT+NHDY=
|
||||
github.com/nats-io/nats-server/v2 v2.14.4 h1:efgjZ8cdExAKRuqSg8UPJFprb+l7NlBtSDPhDlw3rO4=
|
||||
github.com/nats-io/nats-server/v2 v2.14.4/go.mod h1:BltdpOYestjbtQSnVO2zGHdg5SGBZjt+GYTgB9LZq/I=
|
||||
github.com/nats-io/nats.go v1.52.0 h1:n3avV4VBsCgsdwh71TppsTwtv+QdPs7ntSKM8qJLGsc=
|
||||
github.com/nats-io/nats.go v1.52.0/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno=
|
||||
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
|
||||
@@ -148,8 +177,12 @@ github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0t
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/samcharles93/NellDB v0.3.0 h1:xRBJZhO0iuGuMFl5jxPAROw7tD+VdWU8kljbaNz9AwQ=
|
||||
github.com/samcharles93/NellDB v0.3.0/go.mod h1:vyfd6/T2Cp5U0acoh2LrebJteZqoFObedDZTxP0j4W0=
|
||||
github.com/samcharles93/NellDB v0.3.1 h1:3Glxr0xjpyOYIzMjVo3bm2cVhSGAeuM4WV80/NEpHF4=
|
||||
github.com/samcharles93/NellDB v0.3.1/go.mod h1:vyfd6/T2Cp5U0acoh2LrebJteZqoFObedDZTxP0j4W0=
|
||||
github.com/samcharles93/ai-sdk v0.1.19 h1:j/F4pRx9CEjsZmW41FLaM48P+1WRitMLLTqnvlJuBLI=
|
||||
github.com/samcharles93/ai-sdk v0.1.19/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o=
|
||||
github.com/samcharles93/ai-sdk v0.1.20 h1:Z52dyMN293aV8Cpgjdyyd2zw6oNF5FSXKWfCuxY/3UA=
|
||||
github.com/samcharles93/ai-sdk v0.1.20/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o=
|
||||
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
||||
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
@@ -162,18 +195,28 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 h1:sbiXRNDSWJOTobXh5HyQKjq6wUC5tNybqjIqDpAY4CU=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0/go.mod h1:69uWxva0WgAA/4bu2Yy70SLDBwZXuQ6PbBpbsa5iZrQ=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 h1:LMuyCAyfalSjDyjdC65nK6N0zoTT63+E/u95X0JovZI=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0/go.mod h1:085m8qbm4hgc8rZWGDEa4vmyyo2c3nPxUslYUKUIU04=
|
||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||
go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
|
||||
go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
|
||||
go.opentelemetry.io/otel/exporters/prometheus v0.66.0 h1:vkrK8PAznv2NKt2r+kdu252ccGzkEqLc2aSXbQIALYQ=
|
||||
go.opentelemetry.io/otel/exporters/prometheus v0.66.0/go.mod h1:V/UB6D3vMF/UBOL5igAsAYnk1nG/bzYYTzvsB16cy7o=
|
||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||
go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
|
||||
go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
||||
go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
|
||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
|
||||
go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
@@ -181,14 +224,20 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
|
||||
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
|
||||
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
|
||||
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -197,13 +246,18 @@ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
|
||||
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
|
||||
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
|
||||
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
@@ -236,6 +290,8 @@ modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ=
|
||||
modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os=
|
||||
modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k=
|
||||
modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
@@ -246,6 +302,8 @@ modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
|
||||
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
|
||||
modernc.org/sqlite v1.56.0 h1:/D8e2RfFqoy/Zc6PuC76U28zFwmI/sYx1Kjm4yEn9e0=
|
||||
modernc.org/sqlite v1.56.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
|
||||
@@ -32,6 +32,10 @@ type InProcessRunner struct {
|
||||
log *slog.Logger
|
||||
run loopFunc
|
||||
tools *tools.Registry
|
||||
|
||||
// Limits bounds the size of tool results fed back into the stage. The
|
||||
// zero value applies no limits.
|
||||
Limits ToolLimits
|
||||
}
|
||||
|
||||
func NewInProcessRunner(
|
||||
@@ -46,6 +50,18 @@ func NewInProcessRunner(
|
||||
return runner
|
||||
}
|
||||
|
||||
// workspaceToolset names the central-registry toolset a task agent must not
|
||||
// inherit. Those tools are rooted at the chat workspace, not the task's
|
||||
// worktree, and they reach the filesystem through their own handlers -- so
|
||||
// agentloop's ReadOnly and ProtectPaths, which gate only the tools agentloop
|
||||
// registers itself, do not apply to them. A feasibility stage running
|
||||
// ReadOnly could otherwise write, and a TDD fix stage could edit the very
|
||||
// tests it is being graded against.
|
||||
//
|
||||
// This is an invariant of task execution rather than a deployment choice, so
|
||||
// it is not configurable.
|
||||
const workspaceToolset = "workspace"
|
||||
|
||||
func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request) (Result, error) {
|
||||
if err := req.Validate(); err != nil {
|
||||
return Result{}, err
|
||||
@@ -59,7 +75,7 @@ func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request
|
||||
|
||||
notes := &memoryNotes{initial: req.Notes}
|
||||
captures := make(map[string][]json.RawMessage)
|
||||
centralTools, err := BuildToolSet(r.tools)
|
||||
centralTools, err := BuildToolSet(r.tools, r.Limits.Options(workspaceToolset))
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("build central tool set: %w", err)
|
||||
}
|
||||
|
||||
@@ -4,12 +4,94 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
|
||||
aicore "github.com/samcharles93/ai-sdk/core"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// ToolLimits are the configured result limits for one chat turn or agent
|
||||
// stage. It holds only settings, never accumulated state, so it is safe to
|
||||
// store on a long-lived runner and share across tasks.
|
||||
//
|
||||
// A negative limit means no limit; see config.ToolPolicy for why zero cannot
|
||||
// carry that meaning.
|
||||
type ToolLimits struct {
|
||||
MaxResultChars int
|
||||
TurnBudgetChars int
|
||||
SpillDir string
|
||||
}
|
||||
|
||||
// EnsureSpillDir creates the spill directory if one is configured.
|
||||
//
|
||||
// Call it once at startup. Without it the directory never exists, and because
|
||||
// TurnBudget's write failure is silent every oversized result falls back to
|
||||
// inline truncation -- spilling looks configured and does nothing. An empty
|
||||
// SpillDir is not an error: it selects inline truncation deliberately.
|
||||
func (l ToolLimits) EnsureSpillDir() error {
|
||||
if l.SpillDir == "" {
|
||||
return nil
|
||||
}
|
||||
// 0700: spill files are verbatim tool output and may hold anything the
|
||||
// tools could read.
|
||||
if err := os.MkdirAll(l.SpillDir, 0o700); err != nil {
|
||||
return fmt.Errorf("create tool spill directory %s: %w", l.SpillDir, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Options builds the tool-set options for a single turn or stage, minting a
|
||||
// fresh TurnBudget each time.
|
||||
//
|
||||
// The budget must never outlive one turn: a shared counter would let one
|
||||
// task's tool output exhaust another's allowance, and nothing would reset it.
|
||||
func (l ToolLimits) Options(excludeToolsets ...string) ToolSetOptions {
|
||||
opts := ToolSetOptions{
|
||||
MaxResultChars: l.MaxResultChars,
|
||||
ExcludeToolsets: excludeToolsets,
|
||||
}
|
||||
if l.TurnBudgetChars > 0 {
|
||||
opts.Budget = tools.NewTurnBudget(l.TurnBudgetChars, l.SpillDir)
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
// ToolSetOptions bounds what a built tool set may do and return.
|
||||
//
|
||||
// The zero value builds every available tool with no result limits, which is
|
||||
// the behaviour this package had before the options existed.
|
||||
type ToolSetOptions struct {
|
||||
// Budget accounts for the aggregate size of tool results across one chat
|
||||
// turn or agent stage, and supplies the spill directory oversized results
|
||||
// are displaced to. Nil disables budget accounting entirely.
|
||||
Budget *tools.TurnBudget
|
||||
|
||||
// MaxResultChars caps a single tool result. Entries setting
|
||||
// ToolEntry.MaxResultSizeChars override it. Zero or negative means no cap.
|
||||
MaxResultChars int
|
||||
|
||||
// ExcludeToolsets omits entries whose ToolEntry.Toolset matches. Task
|
||||
// agents use it to drop the chat workspace's file and shell tools, which
|
||||
// are rooted at a directory that is not the task's worktree and which
|
||||
// bypass the agent loop's read-only and protected-path enforcement.
|
||||
ExcludeToolsets []string
|
||||
}
|
||||
|
||||
// resultLimit returns the cap that applies to one entry.
|
||||
func (o ToolSetOptions) resultLimit(entry tools.ToolEntry) int {
|
||||
if entry.MaxResultSizeChars != 0 {
|
||||
return entry.MaxResultSizeChars
|
||||
}
|
||||
return o.MaxResultChars
|
||||
}
|
||||
|
||||
// excludes reports whether an entry's toolset is omitted.
|
||||
func (o ToolSetOptions) excludes(entry tools.ToolEntry) bool {
|
||||
return slices.Contains(o.ExcludeToolsets, entry.Toolset)
|
||||
}
|
||||
|
||||
// BuildToolSet converts every currently-available entry in reg into an
|
||||
// ai-sdk core.ToolSet, ready to pass as core.GenerateOptions.Tools for a
|
||||
// multi-step chat turn. A nil registry (memory/tools disabled) returns
|
||||
@@ -20,12 +102,31 @@ import (
|
||||
// tools.Handler exchanges a decoded map. The returned Execute functions
|
||||
// do the JSON <-> map translation and surface decode failures as errors
|
||||
// rather than silently dropping malformed model input.
|
||||
func BuildToolSet(reg *tools.Registry) (aicore.ToolSet, error) {
|
||||
set := aicore.ToolSet{}
|
||||
//
|
||||
// This is the only path from a registered tools.ToolEntry to a model, so it is
|
||||
// also where result limits are enforced. The model runtime owns the tool loop
|
||||
// and decides what to invoke, so archie cannot gate a batch -- but it builds
|
||||
// every Execute closure here, which makes per-call accounting reachable.
|
||||
func BuildToolSet(reg *tools.Registry, opts ToolSetOptions) (aicore.ToolSet, error) {
|
||||
if reg == nil {
|
||||
return set, nil
|
||||
return aicore.ToolSet{}, nil
|
||||
}
|
||||
for _, entry := range reg.All() {
|
||||
return BuildToolSetFrom(reg.All(), opts)
|
||||
}
|
||||
|
||||
// BuildToolSetFrom converts a loose slice of entries under the same rules as
|
||||
// [BuildToolSet].
|
||||
//
|
||||
// It exists for tools that are bound per turn rather than registered globally
|
||||
// -- the task tools carry the calling gateway's identity, so there is one set
|
||||
// of them per gateway and they cannot live in the process-wide registry. Pass
|
||||
// the same ToolSetOptions to both calls so a single turn shares one budget.
|
||||
func BuildToolSetFrom(entries []tools.ToolEntry, opts ToolSetOptions) (aicore.ToolSet, error) {
|
||||
set := aicore.ToolSet{}
|
||||
for _, entry := range entries {
|
||||
if opts.excludes(entry) {
|
||||
continue
|
||||
}
|
||||
available, err := safeToolAvailable(entry)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tool %s availability: %w", entry.Name, err)
|
||||
@@ -47,7 +148,7 @@ func BuildToolSet(reg *tools.Registry) (aicore.ToolSet, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tool %s schema: %w", entry.Name, err)
|
||||
}
|
||||
set[entry.Name] = aicore.NewTool(entry.Name, entry.Description, params, toolExecute(entry))
|
||||
set[entry.Name] = aicore.NewTool(entry.Name, entry.Description, params, toolExecute(entry, opts))
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
@@ -71,9 +172,23 @@ func safeResolvedSchema(entry tools.ToolEntry) (schema tools.JSONSchema, err err
|
||||
}
|
||||
|
||||
// toolExecute adapts a tools.ToolEntry's Handler to core.Tool's
|
||||
// Execute(ctx, jsonInput string) (jsonOutput string, err error) shape.
|
||||
func toolExecute(entry tools.ToolEntry) func(context.Context, string) (string, error) {
|
||||
// Execute(ctx, jsonInput string) (jsonOutput string, err error) shape, and
|
||||
// applies the turn's result accounting.
|
||||
//
|
||||
// The cap is applied to the marshalled payload rather than to the handler's
|
||||
// return value, because the marshalled form is what actually reaches the
|
||||
// model: JSON escaping can change the length materially, so capping the Go
|
||||
// value would bound the wrong string.
|
||||
func toolExecute(entry tools.ToolEntry, opts ToolSetOptions) func(context.Context, string) (string, error) {
|
||||
limit := opts.resultLimit(entry)
|
||||
return func(ctx context.Context, input string) (string, error) {
|
||||
// A turn that has spent its budget must say so. Returning an error
|
||||
// tells the model it has run out; returning an empty result would
|
||||
// read as "the tool found nothing" and invite it to try again.
|
||||
if opts.Budget != nil && opts.Budget.Exceeded() {
|
||||
return "", fmt.Errorf("tool %s: turn budget exceeded (%d chars)", entry.Name, opts.Budget.MaxChars)
|
||||
}
|
||||
|
||||
var args map[string]any
|
||||
if input != "" {
|
||||
if err := json.Unmarshal([]byte(input), &args); err != nil {
|
||||
@@ -88,6 +203,11 @@ func toolExecute(entry tools.ToolEntry) func(context.Context, string) (string, e
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("tool %s: encode output: %w", entry.Name, err)
|
||||
}
|
||||
return string(data), nil
|
||||
|
||||
payload := tools.CapPayload(entry.Name, string(data), limit, opts.Budget)
|
||||
if opts.Budget != nil {
|
||||
opts.Budget.Consume(len(payload))
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
aicore "github.com/samcharles93/ai-sdk/core"
|
||||
@@ -214,7 +217,7 @@ func TestBuildToolSetReportsInvalidDynamicSchemas(t *testing.T) {
|
||||
)
|
||||
func() {
|
||||
defer func() { panicked = recover() }()
|
||||
_, err = BuildToolSet(registry)
|
||||
_, err = BuildToolSet(registry, ToolSetOptions{})
|
||||
}()
|
||||
if panicked != nil {
|
||||
t.Fatalf("BuildToolSet() panicked: %v", panicked)
|
||||
@@ -228,9 +231,243 @@ func TestBuildToolSetReportsInvalidDynamicSchemas(t *testing.T) {
|
||||
|
||||
func mustBuildToolSet(t *testing.T, registry *tools.Registry) map[string]*aicore.Tool {
|
||||
t.Helper()
|
||||
set, err := BuildToolSet(registry)
|
||||
return mustBuildToolSetWith(t, registry, ToolSetOptions{})
|
||||
}
|
||||
|
||||
func mustBuildToolSetWith(t *testing.T, registry *tools.Registry, opts ToolSetOptions) map[string]*aicore.Tool {
|
||||
t.Helper()
|
||||
set, err := BuildToolSet(registry, opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
// registryReturning builds a single-entry registry whose tool returns payload.
|
||||
func registryReturning(t *testing.T, entry tools.ToolEntry, payload string) *tools.Registry {
|
||||
t.Helper()
|
||||
reg := tools.NewRegistry()
|
||||
entry.Handler = func(context.Context, map[string]any) (any, error) { return payload, nil }
|
||||
if err := reg.Register(entry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return reg
|
||||
}
|
||||
|
||||
// TestToolSetCapsResults covers the limit that decides how much of a tool
|
||||
// result reaches the model. The workspace tools truncate themselves, so the
|
||||
// entries that matter here are the ones that do not: skill bodies and MCP
|
||||
// results were previously handed over whole.
|
||||
func TestToolSetCapsResults(t *testing.T) {
|
||||
const payloadSize = 4000
|
||||
payload := strings.Repeat("z", payloadSize)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
entryLimit int // ToolEntry.MaxResultSizeChars
|
||||
defaultLimit int // ToolSetOptions.MaxResultChars
|
||||
wantTruncated bool
|
||||
}{
|
||||
{name: "under the default passes through", defaultLimit: payloadSize * 2},
|
||||
{name: "over the default is capped", defaultLimit: 100, wantTruncated: true},
|
||||
{name: "per-entry limit overrides a larger default", entryLimit: 100, defaultLimit: payloadSize * 2, wantTruncated: true},
|
||||
{name: "per-entry limit overrides a smaller default", entryLimit: payloadSize * 2, defaultLimit: 100},
|
||||
{name: "negative default disables capping", defaultLimit: -1},
|
||||
{name: "zero default disables capping", defaultLimit: 0},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
reg := registryReturning(t, tools.ToolEntry{
|
||||
Name: "big",
|
||||
MaxResultSizeChars: tc.entryLimit,
|
||||
}, payload)
|
||||
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: tc.defaultLimit})
|
||||
out, err := set["big"].Execute(context.Background(), "{}")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
truncated := strings.Contains(out, "truncated")
|
||||
if truncated != tc.wantTruncated {
|
||||
t.Fatalf("truncated = %v, want %v (result %d bytes)", truncated, tc.wantTruncated, len(out))
|
||||
}
|
||||
if !tc.wantTruncated && len(out) < payloadSize {
|
||||
t.Errorf("result is %d bytes, want the whole %d-byte payload", len(out), payloadSize)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolSetSpillsOversizeResults proves an oversized result is displaced to
|
||||
// disk rather than lost: the model gets a path it can read back with the read
|
||||
// tool, which is the whole point of spilling instead of truncating.
|
||||
func TestToolSetSpillsOversizeResults(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
budget := tools.NewTurnBudget(1_000_000, dir)
|
||||
payload := strings.Repeat("q", 4000)
|
||||
|
||||
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, payload)
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, Budget: budget})
|
||||
|
||||
out, err := set["big"].Execute(context.Background(), "{}")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out, "spilled") {
|
||||
t.Fatalf("result = %q, want a spill reference", out)
|
||||
}
|
||||
|
||||
spilled := budget.Spilled()
|
||||
if len(spilled) != 1 || spilled[0].Path == "" {
|
||||
t.Fatalf("Spilled() = %+v, want one spill with a path", spilled)
|
||||
}
|
||||
if !strings.Contains(out, spilled[0].Path) {
|
||||
t.Errorf("result %q does not name the spill path %q", out, spilled[0].Path)
|
||||
}
|
||||
body, err := os.ReadFile(spilled[0].Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(body), payload) {
|
||||
t.Error("spill file does not hold the full payload")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolLimitsCreatesSpillDir covers the gap that made spilling dead code in
|
||||
// production: the configured directory defaults to <work_dir>/tool-spill and
|
||||
// nothing ever created it, while TurnBudget.Spill swallows the write error. So
|
||||
// every oversized result silently fell back to inline truncation and the spill
|
||||
// path was never exercised outside tests that made their own directory.
|
||||
func TestToolLimitsCreatesSpillDir(t *testing.T) {
|
||||
// A nested path proves the whole tree is created, not just a leaf.
|
||||
dir := filepath.Join(t.TempDir(), "work", "tool-spill")
|
||||
limits := ToolLimits{MaxResultChars: 100, TurnBudgetChars: 1_000_000, SpillDir: dir}
|
||||
|
||||
if err := limits.EnsureSpillDir(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, err := os.Stat(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("spill directory was not created: %v", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
t.Fatalf("%s is not a directory", dir)
|
||||
}
|
||||
|
||||
// And a spill actually lands there once it exists.
|
||||
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, strings.Repeat("z", 5000))
|
||||
set := mustBuildToolSetWith(t, reg, limits.Options())
|
||||
if _, err := set["big"].Execute(context.Background(), "{}"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
t.Error("no spill file was written into the created directory")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolLimitsEnsureSpillDirNoop covers the disabled case: no directory
|
||||
// configured is not an error, it selects inline truncation.
|
||||
func TestToolLimitsEnsureSpillDirNoop(t *testing.T) {
|
||||
if err := (ToolLimits{}).EnsureSpillDir(); err != nil {
|
||||
t.Errorf("EnsureSpillDir() with no directory = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolSetChargesBudgetOnce pins the invariant that makes the turn budget
|
||||
// mean anything: a turn is charged exactly the bytes it was shown.
|
||||
//
|
||||
// Displacing an oversized result to disk used to charge the full displaced
|
||||
// size AND the short reference handed back, so two 60 KB results burned more
|
||||
// than the 200 K default budget while the model saw about 200 characters.
|
||||
func TestToolSetChargesBudgetOnce(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
spillDir bool
|
||||
}{
|
||||
{name: "results spilled to disk", spillDir: true},
|
||||
{name: "results truncated inline", spillDir: false},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := ""
|
||||
if tc.spillDir {
|
||||
dir = t.TempDir()
|
||||
}
|
||||
budget := tools.NewTurnBudget(1_000_000, dir)
|
||||
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, strings.Repeat("q", 60_000))
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, Budget: budget})
|
||||
|
||||
delivered := 0
|
||||
for range 2 {
|
||||
out, err := set["big"].Execute(context.Background(), "{}")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
delivered += len(out)
|
||||
}
|
||||
|
||||
if used := budget.Used(); used != delivered {
|
||||
t.Errorf("budget charged %d for %d delivered characters", used, delivered)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolSetBudgetStopsFurtherCalls checks the aggregate cap: once a turn has
|
||||
// spent its budget the next tool call must fail loudly, so the model is told it
|
||||
// has run out rather than silently receiving nothing.
|
||||
func TestToolSetBudgetStopsFurtherCalls(t *testing.T) {
|
||||
budget := tools.NewTurnBudget(50, "")
|
||||
reg := registryReturning(t, tools.ToolEntry{Name: "chatty"}, strings.Repeat("w", 200))
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{Budget: budget})
|
||||
|
||||
if _, err := set["chatty"].Execute(context.Background(), "{}"); err != nil {
|
||||
t.Fatalf("first call: %v", err)
|
||||
}
|
||||
if !budget.Exceeded() {
|
||||
t.Fatal("budget should be exceeded after a 200-byte result against a 50-byte cap")
|
||||
}
|
||||
_, err := set["chatty"].Execute(context.Background(), "{}")
|
||||
if err == nil {
|
||||
t.Fatal("second call succeeded, want a budget-exceeded error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "budget") {
|
||||
t.Errorf("error = %v, want it to name the budget", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolSetExcludesToolsets covers the task-agent case: a task runs in its
|
||||
// own worktree, so the chat workspace's file and shell tools must not follow it
|
||||
// in and bypass the agent loop's read-only and protected-path enforcement.
|
||||
func TestToolSetExcludesToolsets(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
for _, e := range []tools.ToolEntry{
|
||||
{Name: "shell", Toolset: "workspace"},
|
||||
{Name: "memory_edit", Toolset: "memory"},
|
||||
} {
|
||||
e.Handler = func(context.Context, map[string]any) (any, error) { return "ok", nil }
|
||||
if err := reg.Register(e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
full := mustBuildToolSetWith(t, reg, ToolSetOptions{})
|
||||
if len(full) != 2 {
|
||||
t.Fatalf("with no exclusions the set has %d tools, want 2", len(full))
|
||||
}
|
||||
|
||||
limited := mustBuildToolSetWith(t, reg, ToolSetOptions{ExcludeToolsets: []string{"workspace"}})
|
||||
if _, ok := limited["shell"]; ok {
|
||||
t.Error("workspace tool survived the exclusion")
|
||||
}
|
||||
if _, ok := limited["memory_edit"]; !ok {
|
||||
t.Error("memory tool was dropped, want only the workspace toolset excluded")
|
||||
}
|
||||
}
|
||||
@@ -284,15 +284,57 @@ type MCPServer struct {
|
||||
}
|
||||
|
||||
// ToolPolicy holds tool execution limits.
|
||||
//
|
||||
// The size limits use a negative value for "no limit". Defaulting cannot
|
||||
// distinguish an explicit 0 from an absent key, so zero has to stay available
|
||||
// as "unset, give me the default" -- which leaves negative as the only way an
|
||||
// operator can turn a cap off deliberately.
|
||||
type ToolPolicy struct {
|
||||
MaxResultChars int `yaml:"max_result_chars" json:"max_result_chars"`
|
||||
ParallelExecution bool `yaml:"parallel_execution" json:"parallel_execution"`
|
||||
// MaxResultChars caps a single tool result before it reaches the model.
|
||||
// Tools that set ToolEntry.MaxResultSizeChars override it.
|
||||
MaxResultChars int `toml:"max_result_chars" yaml:"max_result_chars" json:"max_result_chars"`
|
||||
// TurnBudgetChars caps the aggregate size of all tool results in one
|
||||
// chat turn or agent stage.
|
||||
TurnBudgetChars int `toml:"turn_budget_chars" yaml:"turn_budget_chars" json:"turn_budget_chars"`
|
||||
// SpillDir is where results too large to inline are written so the model
|
||||
// can be handed a path instead of losing the content. Empty disables
|
||||
// spilling, leaving inline truncation as the only option.
|
||||
SpillDir string `toml:"spill_dir" yaml:"spill_dir" json:"spill_dir"`
|
||||
ParallelExecution bool `toml:"parallel_execution" yaml:"parallel_execution" json:"parallel_execution"`
|
||||
}
|
||||
|
||||
// WebFetchConfig controls the web_fetch tool.
|
||||
type WebFetchConfig struct {
|
||||
// Enabled advertises the tool to the model. Nil means unset, which
|
||||
// defaults to true.
|
||||
//
|
||||
// This is a pointer rather than a bool because defaulting cannot tell
|
||||
// `enabled = false` from an absent key, and turning the tool off has to
|
||||
// be expressible. Use IsEnabled rather than reading it directly.
|
||||
Enabled *bool `toml:"enabled" yaml:"enabled" json:"enabled"`
|
||||
|
||||
// Timeout bounds one fetch including redirects.
|
||||
Timeout Duration `toml:"timeout" yaml:"timeout" json:"timeout"`
|
||||
|
||||
// MaxBytes bounds how much of a response body is read.
|
||||
MaxBytes int64 `toml:"max_bytes" yaml:"max_bytes" json:"max_bytes"`
|
||||
|
||||
// AllowPrivateNetworks permits fetching loopback, private and
|
||||
// link-local addresses. Off by default: this daemon's own dashboard,
|
||||
// NATS and the Docker API answer on those, and the URL to fetch
|
||||
// arrives through chat, which is an untrusted path.
|
||||
AllowPrivateNetworks bool `toml:"allow_private_networks" yaml:"allow_private_networks" json:"allow_private_networks"`
|
||||
}
|
||||
|
||||
// IsEnabled reports whether the fetch tool should be registered, treating an
|
||||
// absent setting as enabled.
|
||||
func (c WebFetchConfig) IsEnabled() bool { return c.Enabled == nil || *c.Enabled }
|
||||
|
||||
// ToolsConfig holds MCP server and tool policy configuration.
|
||||
type ToolsConfig struct {
|
||||
MCPServers []MCPServer `toml:"mcp_servers" yaml:"mcp_servers" json:"mcp_servers"`
|
||||
Policy ToolPolicy `toml:"tool_policy" yaml:"tool_policy" json:"tool_policy"`
|
||||
MCPServers []MCPServer `toml:"mcp_servers" yaml:"mcp_servers" json:"mcp_servers"`
|
||||
Policy ToolPolicy `toml:"tool_policy" yaml:"tool_policy" json:"tool_policy"`
|
||||
WebFetch WebFetchConfig `toml:"web_fetch" yaml:"web_fetch" json:"web_fetch"`
|
||||
}
|
||||
|
||||
// Config is the daemon configuration.
|
||||
@@ -526,6 +568,24 @@ type ChatConfig struct {
|
||||
// they read, write and execute, so the directory must be a deliberate
|
||||
// choice rather than whatever the daemon happens to start in.
|
||||
Workspace string `toml:"workspace" yaml:"workspace"`
|
||||
// UnrestrictedFilesystem lifts the workspace jail from the chat agent's
|
||||
// read, write, edit, find and grep tools, letting them reach any absolute
|
||||
// path. Relative paths still resolve against Workspace.
|
||||
//
|
||||
// Off by default. Turn it on when the agent is a general-purpose operator
|
||||
// rather than an assistant scoped to one project: partitioning and
|
||||
// mounting a disk, migrating data between filesystems, or editing service
|
||||
// units are all cross-filesystem by nature, and a jail makes them
|
||||
// impossible.
|
||||
//
|
||||
// This widens which TOOL can do the work, not what the agent can reach.
|
||||
// The shell tool has never been confined, so a jailed deployment only
|
||||
// pushed the agent into doing everything through shell -- losing the
|
||||
// truncation, line numbering and read-before-write protection the
|
||||
// dedicated tools give it. Grant it deliberately all the same: it is the
|
||||
// difference between an agent that can edit /etc directly and one that has
|
||||
// to be asked to.
|
||||
UnrestrictedFilesystem bool `toml:"unrestricted_filesystem" yaml:"unrestricted_filesystem"`
|
||||
// MaxSteps caps how many model/tool round-trips one chat turn may take
|
||||
// before the runtime stops and returns what it has. Zero uses the
|
||||
// default.
|
||||
|
||||
@@ -370,7 +370,7 @@ func TestRuntimeMaxConcurrentPasses(t *testing.T) {
|
||||
// b is woken, but the slot is taken: b's pass count cannot advance
|
||||
// past its initial run while a is in flight.
|
||||
before := b.passCalls.Load()
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
rt.Nudge("b")
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
@@ -47,7 +47,7 @@ func TestWakeOnPrimaryInputForwardsOnlyPrimaryKinds(t *testing.T) {
|
||||
|
||||
// Derived curator output and unrelated events must not wake the
|
||||
// curator: no check, no pass.
|
||||
for i := 0; i < 3; i++ {
|
||||
for range 3 {
|
||||
bus.Publish(events.Event{Kind: events.KindCuratorRun})
|
||||
bus.Publish(events.Event{Kind: events.KindCuratorAction})
|
||||
bus.Publish(events.Event{Kind: events.KindCuratorError})
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultTaskListLimit is how many tasks a bare task_list returns.
|
||||
defaultTaskListLimit = 20
|
||||
|
||||
// maxTaskListLimit bounds what the model can ask for. A queue of a few
|
||||
// hundred tasks would otherwise land in the context window whole.
|
||||
maxTaskListLimit = 100
|
||||
)
|
||||
|
||||
// ChatTaskSummary is the per-task view the task tools return. It is
|
||||
// deliberately narrower than a store task: notes, plan and body are the bulk
|
||||
// of a row and none of them help answer "what are you working on?".
|
||||
type ChatTaskSummary struct {
|
||||
ID int64 `json:"id"`
|
||||
Repo string `json:"repo"` // "owner/name"
|
||||
Title string `json:"title"`
|
||||
Status string `json:"status"`
|
||||
Workflow string `json:"workflow,omitempty"`
|
||||
PRNumber int `json:"pr_number,omitempty"`
|
||||
}
|
||||
|
||||
// ChatTaskLister is the read surface the task tools need. It mirrors the
|
||||
// existing chatTaskWriter/chatTaskController pattern: gateway states what it
|
||||
// needs and the daemon supplies an adapter over the store, so this package
|
||||
// keeps its independence from internal/store.
|
||||
type ChatTaskLister interface {
|
||||
ListChatTasks(ctx context.Context, identity string, limit int) ([]ChatTaskSummary, error)
|
||||
}
|
||||
|
||||
// TaskListResult is what task_list returns.
|
||||
type TaskListResult struct {
|
||||
Tasks []ChatTaskSummary `json:"tasks"`
|
||||
}
|
||||
|
||||
// TaskSpawnResult is what task_spawn returns.
|
||||
type TaskSpawnResult struct {
|
||||
ID int64 `json:"id"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// TaskTools builds the chat tools that let Archie see and add to its own work
|
||||
// queue. Until these existed, /spawn and the task list were slash commands only
|
||||
// a human could type, so "what are you working on?" had no tool path at all.
|
||||
//
|
||||
// Both tools are bound to identity at construction. The model never supplies
|
||||
// it: a model that could name an identity could read or file work belonging to
|
||||
// another instance on the same host.
|
||||
//
|
||||
// A nil backend omits its tool rather than registering one that always fails,
|
||||
// so a daemon without chat task support advertises nothing.
|
||||
//
|
||||
// Deliberately absent: task_approve and task_cancel. waiting_human is the one
|
||||
// point in the task lifecycle where a person must act, and /approve is that
|
||||
// gate. The text reaching a chat turn is untrusted -- a forge issue body or an
|
||||
// inbound email can be quoted into it -- so a tool that approves Archie's own
|
||||
// work would remove the only human checkpoint in the lifecycle. Cancel is
|
||||
// destructive on the same untrusted path. Both remain slash commands.
|
||||
func TaskTools(lister ChatTaskLister, creator TaskCreator, identity string) []tools.ToolEntry {
|
||||
var entries []tools.ToolEntry
|
||||
if lister != nil {
|
||||
entries = append(entries, taskListTool(lister, identity))
|
||||
}
|
||||
if creator != nil {
|
||||
entries = append(entries, taskSpawnTool(creator, identity))
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
func taskListTool(lister ChatTaskLister, identity string) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: "task_list",
|
||||
Toolset: "tasks",
|
||||
Description: "List the tasks this instance is working on, most recent first. " +
|
||||
"Use it to answer questions about current, queued, parked or finished work. " +
|
||||
"Optionally filter by status (queued, running, waiting_human, parked, pr_open, merged, rejected).",
|
||||
Classification: tools.ClassIdempotent,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"status": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Only return tasks with this status. Omit for all statuses.",
|
||||
},
|
||||
"limit": map[string]any{
|
||||
"type": "integer",
|
||||
"description": fmt.Sprintf(
|
||||
"Maximum tasks to return. Defaults to %d, capped at %d.",
|
||||
defaultTaskListLimit, maxTaskListLimit),
|
||||
},
|
||||
},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
limit := taskListLimit(input)
|
||||
|
||||
// The bound identity, never input["identity"].
|
||||
all, err := lister.ListChatTasks(ctx, identity, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("task_list: %w", err)
|
||||
}
|
||||
|
||||
status := strings.TrimSpace(strings.ToLower(asString(input["status"])))
|
||||
// Non-nil even when empty: an empty queue is an answer, and a
|
||||
// null would read to the model as a failed call worth retrying.
|
||||
filtered := make([]ChatTaskSummary, 0, len(all))
|
||||
for _, task := range all {
|
||||
if status != "" && !strings.EqualFold(task.Status, status) {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, task)
|
||||
}
|
||||
return TaskListResult{Tasks: filtered}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func taskSpawnTool(creator TaskCreator, identity string) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: "task_spawn",
|
||||
Toolset: "tasks",
|
||||
Description: "Queue a new task for this instance to work on in its own worktree, " +
|
||||
"opening a pull request for review when it finishes. " +
|
||||
"Use it when the user asks for work to be carried out rather than answered in chat.",
|
||||
Classification: tools.ClassMutating,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"title": map[string]any{
|
||||
"type": "string",
|
||||
"description": "What the task should accomplish, as a single instruction.",
|
||||
},
|
||||
"repo": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Target repository as \"owner/name\". Omit to use this instance's default repository. A repository this instance is not configured for is refused.",
|
||||
},
|
||||
"workflow": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Workflow to run (e.g. implement, tdd, feasibility). Omit to let the daemon route it.",
|
||||
},
|
||||
},
|
||||
"required": []any{"title"},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
title := strings.TrimSpace(asString(input["title"]))
|
||||
if title == "" {
|
||||
return nil, fmt.Errorf("task_spawn: title is required")
|
||||
}
|
||||
|
||||
id, err := creator.CreateTask(ctx, SpawnRequest{
|
||||
Title: title,
|
||||
Repo: strings.TrimSpace(asString(input["repo"])),
|
||||
Workflow: strings.TrimSpace(asString(input["workflow"])),
|
||||
// The bound identity, never input["identity"]. CreateTask
|
||||
// enforces the repository allow-list for it.
|
||||
Identity: identity,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("task_spawn: %w", err)
|
||||
}
|
||||
return TaskSpawnResult{
|
||||
ID: id,
|
||||
Message: fmt.Sprintf("queued task %d: %s", id, title),
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// taskListLimit resolves the requested limit, falling back to the default for
|
||||
// anything absent or non-positive and clamping the rest.
|
||||
//
|
||||
// JSON numbers decode as float64, but a model that emits an integer through a
|
||||
// different provider path can arrive as int, so both are accepted.
|
||||
func taskListLimit(input map[string]any) int {
|
||||
var limit int
|
||||
switch v := input["limit"].(type) {
|
||||
case float64:
|
||||
limit = int(v)
|
||||
case int:
|
||||
limit = v
|
||||
}
|
||||
if limit <= 0 {
|
||||
return defaultTaskListLimit
|
||||
}
|
||||
return min(limit, maxTaskListLimit)
|
||||
}
|
||||
|
||||
// asString reads a string field, tolerating an absent or wrongly-typed value
|
||||
// rather than failing the call over it.
|
||||
func asString(v any) string {
|
||||
s, _ := v.(string)
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
type fakeLister struct {
|
||||
tasks []ChatTaskSummary
|
||||
err error
|
||||
|
||||
gotIdentity string
|
||||
gotLimit int
|
||||
}
|
||||
|
||||
func (f *fakeLister) ListChatTasks(_ context.Context, identity string, limit int) ([]ChatTaskSummary, error) {
|
||||
f.gotIdentity, f.gotLimit = identity, limit
|
||||
return f.tasks, f.err
|
||||
}
|
||||
|
||||
type fakeCreator struct {
|
||||
id int64
|
||||
err error
|
||||
|
||||
got SpawnRequest
|
||||
}
|
||||
|
||||
func (f *fakeCreator) CreateTask(_ context.Context, req SpawnRequest) (int64, error) {
|
||||
f.got = req
|
||||
return f.id, f.err
|
||||
}
|
||||
|
||||
// toolNamed pulls one entry out of the built set.
|
||||
func toolNamed(t *testing.T, entries []tools.ToolEntry, name string) tools.ToolEntry {
|
||||
t.Helper()
|
||||
for _, e := range entries {
|
||||
if e.Name == name {
|
||||
return e
|
||||
}
|
||||
}
|
||||
t.Fatalf("TaskTools() has no %q entry", name)
|
||||
return tools.ToolEntry{}
|
||||
}
|
||||
|
||||
func TestTaskToolsValidate(t *testing.T) {
|
||||
entries := TaskTools(&fakeLister{}, &fakeCreator{}, "archie")
|
||||
if len(entries) == 0 {
|
||||
t.Fatal("TaskTools() returned nothing")
|
||||
}
|
||||
for _, e := range entries {
|
||||
if err := e.Validate(); err != nil {
|
||||
t.Errorf("entry %q: %v", e.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskToolsOmitNilBackends checks that a daemon without chat task support
|
||||
// advertises nothing, rather than offering a tool that always fails.
|
||||
func TestTaskToolsOmitNilBackends(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
lister ChatTaskLister
|
||||
creator TaskCreator
|
||||
want []string
|
||||
}{
|
||||
{name: "both", lister: &fakeLister{}, creator: &fakeCreator{}, want: []string{"task_list", "task_spawn"}},
|
||||
{name: "lister only", lister: &fakeLister{}, want: []string{"task_list"}},
|
||||
{name: "creator only", creator: &fakeCreator{}, want: []string{"task_spawn"}},
|
||||
{name: "neither"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
entries := TaskTools(tc.lister, tc.creator, "archie")
|
||||
var got []string
|
||||
for _, e := range entries {
|
||||
got = append(got, e.Name)
|
||||
}
|
||||
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
|
||||
t.Errorf("tools = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskListUsesBoundIdentity is the authorization property: the identity
|
||||
// comes from the gateway that built the tool, never from the model. A model
|
||||
// that could name an identity could read another instance's work.
|
||||
func TestTaskListUsesBoundIdentity(t *testing.T) {
|
||||
lister := &fakeLister{tasks: []ChatTaskSummary{{ID: 7, Title: "wire the thing", Status: "running"}}}
|
||||
entry := toolNamed(t, TaskTools(lister, nil, "archie"), "task_list")
|
||||
|
||||
// The model supplies an identity; it must be ignored.
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{"identity": "someone-else"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if lister.gotIdentity != "archie" {
|
||||
t.Errorf("listed identity %q, want the bound %q", lister.gotIdentity, "archie")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskListLimit(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input map[string]any
|
||||
want int
|
||||
}{
|
||||
{name: "default when absent", input: map[string]any{}, want: defaultTaskListLimit},
|
||||
{name: "explicit", input: map[string]any{"limit": float64(5)}, want: 5},
|
||||
{name: "clamped to the maximum", input: map[string]any{"limit": float64(10_000)}, want: maxTaskListLimit},
|
||||
{name: "non-positive falls back to the default", input: map[string]any{"limit": float64(0)}, want: defaultTaskListLimit},
|
||||
{name: "negative falls back to the default", input: map[string]any{"limit": float64(-3)}, want: defaultTaskListLimit},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
lister := &fakeLister{}
|
||||
entry := toolNamed(t, TaskTools(lister, nil, "archie"), "task_list")
|
||||
if _, err := entry.Handler(context.Background(), tc.input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if lister.gotLimit != tc.want {
|
||||
t.Errorf("limit = %d, want %d", lister.gotLimit, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskListFiltersByStatus(t *testing.T) {
|
||||
lister := &fakeLister{tasks: []ChatTaskSummary{
|
||||
{ID: 1, Status: "running"},
|
||||
{ID: 2, Status: "queued"},
|
||||
{ID: 3, Status: "running"},
|
||||
}}
|
||||
entry := toolNamed(t, TaskTools(lister, nil, "archie"), "task_list")
|
||||
|
||||
out, err := entry.Handler(context.Background(), map[string]any{"status": "running"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, ok := out.(TaskListResult)
|
||||
if !ok {
|
||||
t.Fatalf("handler returned %T, want TaskListResult", out)
|
||||
}
|
||||
if len(result.Tasks) != 2 {
|
||||
t.Fatalf("got %d tasks, want the 2 running ones", len(result.Tasks))
|
||||
}
|
||||
for _, task := range result.Tasks {
|
||||
if task.Status != "running" {
|
||||
t.Errorf("task %d has status %q, want only running", task.ID, task.Status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskListEmptyIsNotAnError guards against the model reading an empty
|
||||
// queue as a broken tool and retrying.
|
||||
func TestTaskListEmptyIsNotAnError(t *testing.T) {
|
||||
entry := toolNamed(t, TaskTools(&fakeLister{}, nil, "archie"), "task_list")
|
||||
|
||||
out, err := entry.Handler(context.Background(), map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatalf("empty list returned an error: %v", err)
|
||||
}
|
||||
result, ok := out.(TaskListResult)
|
||||
if !ok {
|
||||
t.Fatalf("handler returned %T, want TaskListResult", out)
|
||||
}
|
||||
if result.Tasks == nil {
|
||||
t.Error("Tasks is nil, want an empty slice so it marshals as [] not null")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskListPropagatesStoreError(t *testing.T) {
|
||||
lister := &fakeLister{err: errors.New("database is gone")}
|
||||
entry := toolNamed(t, TaskTools(lister, nil, "archie"), "task_list")
|
||||
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{}); err == nil {
|
||||
t.Fatal("handler error = nil, want the store failure surfaced")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskSpawn(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input map[string]any
|
||||
creator *fakeCreator
|
||||
wantErr bool
|
||||
wantTitle string
|
||||
wantRepo string
|
||||
}{
|
||||
{
|
||||
name: "title only",
|
||||
input: map[string]any{"title": "fix the parser"},
|
||||
creator: &fakeCreator{id: 42},
|
||||
wantTitle: "fix the parser",
|
||||
},
|
||||
{
|
||||
name: "with repo and workflow",
|
||||
input: map[string]any{"title": "port it", "repo": "acme/app", "workflow": "tdd"},
|
||||
creator: &fakeCreator{id: 43},
|
||||
wantTitle: "port it",
|
||||
wantRepo: "acme/app",
|
||||
},
|
||||
{
|
||||
name: "missing title is refused",
|
||||
input: map[string]any{},
|
||||
creator: &fakeCreator{id: 44},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "blank title is refused",
|
||||
input: map[string]any{"title": " "},
|
||||
creator: &fakeCreator{id: 45},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "creator rejection surfaces",
|
||||
input: map[string]any{"title": "x", "repo": "not/allowed"},
|
||||
creator: &fakeCreator{err: fmt.Errorf("repo %q is not configured for this identity", "not/allowed")},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
entry := toolNamed(t, TaskTools(nil, tc.creator, "archie"), "task_spawn")
|
||||
out, err := entry.Handler(context.Background(), tc.input)
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("handler error = nil, want a refusal")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tc.creator.got.Title != tc.wantTitle {
|
||||
t.Errorf("title = %q, want %q", tc.creator.got.Title, tc.wantTitle)
|
||||
}
|
||||
if tc.creator.got.Repo != tc.wantRepo {
|
||||
t.Errorf("repo = %q, want %q", tc.creator.got.Repo, tc.wantRepo)
|
||||
}
|
||||
// Identity is bound, never taken from the model.
|
||||
if tc.creator.got.Identity != "archie" {
|
||||
t.Errorf("identity = %q, want the bound %q", tc.creator.got.Identity, "archie")
|
||||
}
|
||||
result, ok := out.(TaskSpawnResult)
|
||||
if !ok {
|
||||
t.Fatalf("handler returned %T, want TaskSpawnResult", out)
|
||||
}
|
||||
if result.ID != tc.creator.id {
|
||||
t.Errorf("id = %d, want %d", result.ID, tc.creator.id)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskSpawnIgnoresModelIdentity is the counterpart to the list case: a
|
||||
// model must not be able to file work under another instance's identity.
|
||||
func TestTaskSpawnIgnoresModelIdentity(t *testing.T) {
|
||||
creator := &fakeCreator{id: 1}
|
||||
entry := toolNamed(t, TaskTools(nil, creator, "archie"), "task_spawn")
|
||||
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{
|
||||
"title": "sneaky",
|
||||
"identity": "other-archie",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if creator.got.Identity != "archie" {
|
||||
t.Errorf("identity = %q, want the bound %q", creator.got.Identity, "archie")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskToolsExcludeApprovalTools records a deliberate omission: approving a
|
||||
// waiting_human task is the one human checkpoint in the lifecycle, and chat is
|
||||
// an untrusted input path. If these are ever added they must be a considered
|
||||
// decision, not an accident.
|
||||
func TestTaskToolsExcludeApprovalTools(t *testing.T) {
|
||||
entries := TaskTools(&fakeLister{}, &fakeCreator{}, "archie")
|
||||
for _, e := range entries {
|
||||
switch e.Name {
|
||||
case "task_approve", "task_cancel":
|
||||
t.Errorf("%q is exposed to the model; approval must stay a human action", e.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// Defaults applied to absent input. Named so a reader can find the value
|
||||
@@ -25,6 +26,19 @@ const (
|
||||
defaultContainerUptime = 60 * time.Minute
|
||||
defaultVolumeTTL = 72 * time.Hour
|
||||
defaultPullPolicy = "missing"
|
||||
|
||||
// defaultMaxResultChars bounds one tool result. It matches the 50KB the
|
||||
// lifted workspace tools already truncate themselves at
|
||||
// (tools/builtin.DefaultMaxBytes), so those stay the binding limit and
|
||||
// only tools with no truncation of their own -- skill bodies, MCP
|
||||
// results -- see a change.
|
||||
defaultMaxResultChars = 50_000
|
||||
|
||||
defaultWebFetchTimeout = 30 * time.Second
|
||||
// defaultWebFetchMaxBytes bounds a fetched body before the result limit
|
||||
// above trims it further. Generous enough for a documentation page,
|
||||
// small enough that a large download cannot occupy the daemon.
|
||||
defaultWebFetchMaxBytes = 2_000_000
|
||||
)
|
||||
|
||||
// applyDefaults fills in every absent value. It never reports an error and
|
||||
@@ -43,6 +57,43 @@ func (l *Loader) applyDefaults(cfg *config.Config) {
|
||||
applyDispatchDefaults(cfg)
|
||||
applyIdentityDefaults(cfg)
|
||||
applyContainerDefaults(cfg)
|
||||
applyToolPolicyDefaults(cfg)
|
||||
}
|
||||
|
||||
// applyToolPolicyDefaults fills the tool result limits.
|
||||
//
|
||||
// Zero means "unset" and takes the default; a negative value is the operator
|
||||
// saying "no limit" and is left alone. See [config.ToolPolicy].
|
||||
func applyToolPolicyDefaults(cfg *config.Config) {
|
||||
if cfg.Tools.Policy.MaxResultChars == 0 {
|
||||
cfg.Tools.Policy.MaxResultChars = defaultMaxResultChars
|
||||
}
|
||||
if cfg.Tools.Policy.TurnBudgetChars == 0 {
|
||||
cfg.Tools.Policy.TurnBudgetChars = tools.DefaultTurnBudgetChars
|
||||
}
|
||||
// SpillDir is deliberately NOT defaulted.
|
||||
//
|
||||
// Spilling hands the model a file path to read back, and the read tool is
|
||||
// confined to chat.workspace. A default under work_dir is outside that for
|
||||
// any workspace narrower than the whole home directory, and always outside
|
||||
// a task agent's worktree -- so the model would be given a path it cannot
|
||||
// open and the result would be lost rather than displaced. Truncating
|
||||
// inline at least shows the first part of the result and says so.
|
||||
//
|
||||
// An operator who wants spilling points this at a directory inside the
|
||||
// workspace; startup warns when it is not (see cmd/archied).
|
||||
applyWebFetchDefaults(cfg)
|
||||
}
|
||||
|
||||
// applyWebFetchDefaults fills the fetch tool's settings. Enabled is left alone
|
||||
// when the operator set it either way; see [config.WebFetchConfig].
|
||||
func applyWebFetchDefaults(cfg *config.Config) {
|
||||
if cfg.Tools.WebFetch.Timeout == 0 {
|
||||
cfg.Tools.WebFetch.Timeout = config.Duration(defaultWebFetchTimeout)
|
||||
}
|
||||
if cfg.Tools.WebFetch.MaxBytes == 0 {
|
||||
cfg.Tools.WebFetch.MaxBytes = defaultWebFetchMaxBytes
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultWorkDir returns the work directory an unset work_dir would have been
|
||||
|
||||
@@ -151,6 +151,143 @@ func TestLoadAgentDefaultsAndOverrides(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadToolPolicyDefaultsAndOverrides covers the result-size and turn-budget
|
||||
// limits end to end from TOML. Before these fields carried toml tags they could
|
||||
// not be set from the daemon's config at all, so a test that only exercised
|
||||
// defaulting would have passed against a setting no operator could reach.
|
||||
//
|
||||
// A negative value means "disabled" rather than zero: defaulting cannot tell an
|
||||
// explicit 0 from an absent key, so zero has to stay available as "unset".
|
||||
func TestLoadToolPolicyDefaultsAndOverrides(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
policy string
|
||||
wantMaxResult int
|
||||
wantTurnBudget int
|
||||
wantSpillDir string
|
||||
}{
|
||||
{
|
||||
// SpillDir has no default on purpose: a path outside
|
||||
// chat.workspace is one the read tool refuses, so the model would
|
||||
// be handed a reference it cannot open. Absent means truncate
|
||||
// inline.
|
||||
name: "defaults",
|
||||
wantMaxResult: 50_000,
|
||||
wantTurnBudget: 200_000,
|
||||
wantSpillDir: "",
|
||||
},
|
||||
{
|
||||
name: "explicit values",
|
||||
policy: "[tools.tool_policy]\nmax_result_chars = 1234\nturn_budget_chars = 5678\nspill_dir = \"/var/spool/archie\"\n",
|
||||
wantMaxResult: 1234,
|
||||
wantTurnBudget: 5678,
|
||||
wantSpillDir: "/var/spool/archie",
|
||||
},
|
||||
{
|
||||
name: "negative disables both caps",
|
||||
policy: "[tools.tool_policy]\nmax_result_chars = -1\nturn_budget_chars = -1\n",
|
||||
wantMaxResult: -1,
|
||||
wantTurnBudget: -1,
|
||||
wantSpillDir: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" + tt.policy +
|
||||
"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
policy := cfg.Tools.Policy
|
||||
if policy.MaxResultChars != tt.wantMaxResult {
|
||||
t.Errorf("MaxResultChars = %d, want %d", policy.MaxResultChars, tt.wantMaxResult)
|
||||
}
|
||||
if policy.TurnBudgetChars != tt.wantTurnBudget {
|
||||
t.Errorf("TurnBudgetChars = %d, want %d", policy.TurnBudgetChars, tt.wantTurnBudget)
|
||||
}
|
||||
if policy.SpillDir != tt.wantSpillDir {
|
||||
t.Errorf("SpillDir = %q, want %q", policy.SpillDir, tt.wantSpillDir)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadWebFetchDefaultsAndOverrides covers the fetch tool's settings.
|
||||
//
|
||||
// The enabled case matters most: it is a pointer precisely so an operator can
|
||||
// turn the tool off, which a plain bool could not express because defaulting
|
||||
// cannot tell `enabled = false` from an absent key.
|
||||
func TestLoadWebFetchDefaultsAndOverrides(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
webFetch string
|
||||
wantEnabled bool
|
||||
wantTimeout time.Duration
|
||||
wantMaxBytes int64
|
||||
wantPrivate bool
|
||||
}{
|
||||
{
|
||||
name: "defaults",
|
||||
wantEnabled: true,
|
||||
wantTimeout: 30 * time.Second,
|
||||
wantMaxBytes: 2_000_000,
|
||||
},
|
||||
{
|
||||
name: "explicitly disabled",
|
||||
webFetch: "[tools.web_fetch]\nenabled = false\n",
|
||||
wantEnabled: false,
|
||||
wantTimeout: 30 * time.Second,
|
||||
wantMaxBytes: 2_000_000,
|
||||
},
|
||||
{
|
||||
name: "overrides",
|
||||
webFetch: "[tools.web_fetch]\ntimeout = \"5s\"\nmax_bytes = 4096\nallow_private_networks = true\n",
|
||||
wantEnabled: true,
|
||||
wantTimeout: 5 * time.Second,
|
||||
wantMaxBytes: 4096,
|
||||
wantPrivate: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" + tt.webFetch +
|
||||
"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
wf := cfg.Tools.WebFetch
|
||||
if got := wf.IsEnabled(); got != tt.wantEnabled {
|
||||
t.Errorf("IsEnabled() = %v, want %v", got, tt.wantEnabled)
|
||||
}
|
||||
if got := wf.Timeout.Std(); got != tt.wantTimeout {
|
||||
t.Errorf("Timeout = %s, want %s", got, tt.wantTimeout)
|
||||
}
|
||||
if wf.MaxBytes != tt.wantMaxBytes {
|
||||
t.Errorf("MaxBytes = %d, want %d", wf.MaxBytes, tt.wantMaxBytes)
|
||||
}
|
||||
if wf.AllowPrivateNetworks != tt.wantPrivate {
|
||||
t.Errorf("AllowPrivateNetworks = %v, want %v", wf.AllowPrivateNetworks, tt.wantPrivate)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadContainerVolumeTTL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -123,7 +123,7 @@ func (a Announcer) detectChanged(state map[string]string, prefix string) (change
|
||||
changed[component.ID] = true
|
||||
}
|
||||
}
|
||||
return
|
||||
return changed, stateChanged
|
||||
}
|
||||
|
||||
// sendAndRecord sends the announcement and updates state on success.
|
||||
|
||||
@@ -79,7 +79,7 @@ type Service struct {
|
||||
}
|
||||
|
||||
func (s *Service) Check(ctx context.Context, recipient int64) (Snapshot, error) {
|
||||
if s.Catalog == nil {
|
||||
if s == nil || s.Catalog == nil {
|
||||
return Snapshot{}, errors.New("update discovery is not configured")
|
||||
}
|
||||
snapshot, err := s.Catalog.Check(ctx)
|
||||
@@ -109,7 +109,7 @@ func (s *Service) Check(ctx context.Context, recipient int64) (Snapshot, error)
|
||||
// Defer records only the exact versions the caller displayed. It refuses a
|
||||
// changed catalog rather than silently suppressing a release the user never saw.
|
||||
func (s *Service) Defer(ctx context.Context, recipient int64, expected Snapshot) error {
|
||||
if s.Catalog == nil {
|
||||
if s == nil || s.Catalog == nil {
|
||||
return errors.New("update discovery is not configured")
|
||||
}
|
||||
if s.StatePath == "" {
|
||||
@@ -139,13 +139,13 @@ func (s *Service) Defer(ctx context.Context, recipient int64, expected Snapshot)
|
||||
}
|
||||
|
||||
func (s *Service) Install(ctx context.Context, progress func(string)) error {
|
||||
if s.Installer == nil {
|
||||
if s == nil || s.Installer == nil {
|
||||
return errors.New("update installation is not configured")
|
||||
}
|
||||
return s.Installer.Install(ctx, progress)
|
||||
}
|
||||
|
||||
func (s *Service) CanInstall() bool { return s.Installer != nil }
|
||||
func (s *Service) CanInstall() bool { return s != nil && s.Installer != nil }
|
||||
|
||||
type deferrals map[string]map[string]string
|
||||
|
||||
|
||||
@@ -61,6 +61,23 @@ func TestServiceInstallForwardsProgressAndFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNilServiceReturnsConfigurationErrors(t *testing.T) {
|
||||
var service *Service
|
||||
|
||||
if _, err := service.Check(context.Background(), 0); err == nil {
|
||||
t.Fatal("nil service check returned nil error")
|
||||
}
|
||||
if err := service.Defer(context.Background(), 0, Snapshot{}); err == nil {
|
||||
t.Fatal("nil service defer returned nil error")
|
||||
}
|
||||
if err := service.Install(context.Background(), nil); err == nil {
|
||||
t.Fatal("nil service install returned nil error")
|
||||
}
|
||||
if service.CanInstall() {
|
||||
t.Fatal("nil service reports that installation is available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatSnapshotReportsAvailableAndUnchangedComponents(t *testing.T) {
|
||||
got := FormatSnapshot(Snapshot{Components: []Component{
|
||||
{Label: "THE GATEWAY", Installed: "v1", Available: "v2", Changelog: "- safer updates"},
|
||||
|
||||
@@ -284,7 +284,7 @@ func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail s
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
res, err := tx.ExecContext(ctx,
|
||||
`UPDATE tasks SET status=?, updated_at=datetime('now') WHERE id=? AND status=?`, to, taskID, from)
|
||||
@@ -366,7 +366,7 @@ func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, workflow
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
res, err := tx.ExecContext(ctx, `
|
||||
UPDATE tasks SET status='queued',
|
||||
|
||||
+133
-14
@@ -3,8 +3,9 @@ package tools
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// DefaultTurnBudgetChars is the default per-turn aggregate output budget
|
||||
@@ -84,25 +85,143 @@ func (b *TurnBudget) Spill(toolName string, content []byte) SpillRef {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
sizeChars := len(content)
|
||||
ref := SpillRef{SizeChars: sizeChars}
|
||||
|
||||
if b.spillDir != "" {
|
||||
path := filepath.Join(b.spillDir, fmt.Sprintf("spill-%s-%d", toolName, b.used))
|
||||
if err := os.WriteFile(path, content, 0o644); err == nil {
|
||||
ref.Path = path
|
||||
}
|
||||
}
|
||||
|
||||
b.spilled = append(b.spilled, ref)
|
||||
b.used += sizeChars
|
||||
ref := b.writeSpillLocked(toolName, content)
|
||||
b.used += ref.SizeChars
|
||||
if b.used > b.MaxChars {
|
||||
b.exceeded = true
|
||||
}
|
||||
|
||||
return ref
|
||||
}
|
||||
|
||||
// WriteSpill writes content to the spill directory and records the reference
|
||||
// without charging the budget.
|
||||
//
|
||||
// It exists so that displacing a result to disk and billing for it are separate
|
||||
// decisions. A caller that hands the model a short spill reference has shown it
|
||||
// only those few characters and should be charged for those; charging the full
|
||||
// displaced size as well bills a turn twice for one result and exhausts it
|
||||
// early. [CapPayload] uses this; the batch-dispatch path uses [TurnBudget.Spill],
|
||||
// which still charges, because it accounts for the result separately.
|
||||
func (b *TurnBudget) WriteSpill(toolName string, content []byte) SpillRef {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.writeSpillLocked(toolName, content)
|
||||
}
|
||||
|
||||
// writeSpillLocked performs the write. Must be called with b.mu held.
|
||||
func (b *TurnBudget) writeSpillLocked(toolName string, content []byte) SpillRef {
|
||||
ref := SpillRef{SizeChars: len(content)}
|
||||
|
||||
if b.spillDir != "" {
|
||||
ref.Path = writeSpillFile(b.spillDir, toolName, content)
|
||||
}
|
||||
|
||||
b.spilled = append(b.spilled, ref)
|
||||
return ref
|
||||
}
|
||||
|
||||
// writeSpillFile writes content to a fresh file in dir, returning its path or
|
||||
// "" when the write fails. A failure is not an error here: the caller falls
|
||||
// back to inline truncation, which is degraded but correct.
|
||||
//
|
||||
// The name comes from CreateTemp rather than from budget state. A budget is
|
||||
// minted per turn and every turn shares one directory, so any within-budget
|
||||
// counter restarts at zero each turn and the second turn would overwrite the
|
||||
// first turn's file, handing one session a reference that resolves to another
|
||||
// session's output.
|
||||
//
|
||||
// 0600 because this is verbatim tool output -- shell stdout, file contents, MCP
|
||||
// responses. It is the first place archie persists that material and it can
|
||||
// hold anything the tools could read.
|
||||
func writeSpillFile(dir, toolName string, content []byte) string {
|
||||
f, err := os.CreateTemp(dir, "spill-"+sanitiseToolName(toolName)+"-*")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if err := f.Chmod(0o600); err != nil {
|
||||
return ""
|
||||
}
|
||||
if _, err := f.Write(content); err != nil {
|
||||
return ""
|
||||
}
|
||||
return f.Name()
|
||||
}
|
||||
|
||||
// sanitiseToolName strips path separators and other characters that must not
|
||||
// reach a filename. MCP tool names are supplied by a third-party server, so a
|
||||
// name like "../../etc/passwd" is reachable input rather than a hypothetical.
|
||||
func sanitiseToolName(name string) string {
|
||||
var b strings.Builder
|
||||
b.Grow(len(name))
|
||||
for _, r := range name {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_', r == '-':
|
||||
b.WriteRune(r)
|
||||
default:
|
||||
b.WriteByte('_')
|
||||
}
|
||||
}
|
||||
if b.Len() == 0 {
|
||||
return "tool"
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// CapPayload bounds one tool result to max bytes before it reaches the model.
|
||||
// It is the single definition of that rule: [enforcePerToolLimit] applies it on
|
||||
// the batch-dispatch path, and the agent tool set applies it to the marshalled
|
||||
// payload it hands back to the model.
|
||||
//
|
||||
// When budget has a spill directory the whole result is written there and the
|
||||
// model is given the path, so an oversized result is displaced rather than
|
||||
// lost. Without one -- or when the write fails -- the result is truncated
|
||||
// inline on a rune boundary.
|
||||
//
|
||||
// Either way the return value carries a notice naming the tool and the full
|
||||
// size. Shortening a result silently is how a model concludes a file is empty
|
||||
// or a search found nothing, so the fact of truncation is never implicit.
|
||||
//
|
||||
// max <= 0 disables capping.
|
||||
func CapPayload(toolName, payload string, limit int, budget *TurnBudget) string {
|
||||
if limit <= 0 || len(payload) <= limit {
|
||||
return payload
|
||||
}
|
||||
|
||||
if budget != nil {
|
||||
// WriteSpill, not Spill: the caller charges for what it actually
|
||||
// hands the model, which is the short reference below, not the
|
||||
// displaced payload.
|
||||
if ref := budget.WriteSpill(toolName, []byte(payload)); ref.Path != "" {
|
||||
return fmt.Sprintf(
|
||||
"[%s: result spilled to %s (%d characters); too large to inline]",
|
||||
toolName, ref.Path, ref.SizeChars,
|
||||
)
|
||||
}
|
||||
// Spill was disabled or failed -- fall through to inline truncation.
|
||||
}
|
||||
|
||||
return truncateAtRuneBoundary(payload, limit) + fmt.Sprintf(
|
||||
"\n\n[%s: result truncated, showing the first %d of %d characters]",
|
||||
toolName, limit, len(payload),
|
||||
)
|
||||
}
|
||||
|
||||
// truncateAtRuneBoundary cuts s to at most max bytes without splitting a
|
||||
// multi-byte rune. A half rune is invalid UTF-8: some providers reject the
|
||||
// request outright and others render a replacement character mid-word, so the
|
||||
// cut always retreats to a boundary even when that costs a few bytes.
|
||||
func truncateAtRuneBoundary(s string, limit int) string {
|
||||
if limit >= len(s) {
|
||||
return s
|
||||
}
|
||||
for limit > 0 && !utf8.RuneStart(s[limit]) {
|
||||
limit--
|
||||
}
|
||||
return s[:limit]
|
||||
}
|
||||
|
||||
// Used reports the total characters consumed so far.
|
||||
func (b *TurnBudget) Used() int {
|
||||
b.mu.Lock()
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func TestDefaultTurnBudgetChars(t *testing.T) {
|
||||
@@ -205,6 +206,278 @@ func TestTurnBudgetSpillFileNaming(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapPayload(t *testing.T) {
|
||||
const (
|
||||
toolName = "skill_activate"
|
||||
short = "abcdefghij" // 10 bytes
|
||||
)
|
||||
long := strings.Repeat("x", 500)
|
||||
// oversize begins with short, so a truncation at len(short) is
|
||||
// recognisable in the result rather than being an opaque prefix.
|
||||
oversize := short + long
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
// budget selects how the TurnBudget is built: "none" passes nil,
|
||||
// "spill" gives it a usable directory, "nospill" gives it none,
|
||||
// "badspill" gives it a directory that cannot be written.
|
||||
budget string
|
||||
payload string
|
||||
max int
|
||||
wantPayload string // exact result, when the payload passes through
|
||||
wantContain []string // substrings the capped result must carry
|
||||
}{
|
||||
{
|
||||
name: "no cap when max is zero",
|
||||
budget: "none",
|
||||
payload: long,
|
||||
max: 0,
|
||||
wantPayload: long,
|
||||
},
|
||||
{
|
||||
name: "no cap when max is negative",
|
||||
budget: "none",
|
||||
payload: long,
|
||||
max: -1,
|
||||
wantPayload: long,
|
||||
},
|
||||
{
|
||||
name: "under the cap passes through",
|
||||
budget: "none",
|
||||
payload: short,
|
||||
max: len(short) + 1,
|
||||
wantPayload: short,
|
||||
},
|
||||
{
|
||||
name: "exactly at the cap passes through",
|
||||
budget: "none",
|
||||
payload: short,
|
||||
max: len(short),
|
||||
wantPayload: short,
|
||||
},
|
||||
{
|
||||
name: "over the cap without a budget truncates and names the tool",
|
||||
budget: "none",
|
||||
payload: oversize,
|
||||
max: len(short),
|
||||
wantContain: []string{short, toolName, "510"},
|
||||
},
|
||||
{
|
||||
name: "over the cap with no spill directory truncates",
|
||||
budget: "nospill",
|
||||
payload: oversize,
|
||||
max: len(short),
|
||||
wantContain: []string{short, toolName, "510"},
|
||||
},
|
||||
{
|
||||
name: "over the cap with a spill directory reports the path",
|
||||
budget: "spill",
|
||||
payload: oversize,
|
||||
max: len(short),
|
||||
wantContain: []string{toolName, "spill-"},
|
||||
},
|
||||
{
|
||||
name: "spill write failure falls back to truncation",
|
||||
budget: "badspill",
|
||||
payload: oversize,
|
||||
max: len(short),
|
||||
wantContain: []string{short, toolName, "510"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var budget *TurnBudget
|
||||
switch tc.budget {
|
||||
case "spill":
|
||||
budget = NewTurnBudget(1_000_000, t.TempDir())
|
||||
case "nospill":
|
||||
budget = NewTurnBudget(1_000_000, "")
|
||||
case "badspill":
|
||||
f, err := os.CreateTemp(t.TempDir(), "spill-blocker")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
budget = NewTurnBudget(1_000_000, filepath.Join(f.Name(), "sub"))
|
||||
}
|
||||
|
||||
got := CapPayload(toolName, tc.payload, tc.max, budget)
|
||||
|
||||
if tc.wantPayload != "" {
|
||||
if got != tc.wantPayload {
|
||||
t.Errorf("CapPayload() = %q, want it returned unchanged", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, want := range tc.wantContain {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("CapPayload() = %q, want it to contain %q", got, want)
|
||||
}
|
||||
}
|
||||
if len(got) >= len(tc.payload) {
|
||||
t.Errorf("CapPayload() returned %d bytes, want fewer than the %d-byte payload", len(got), len(tc.payload))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCapPayloadDoesNotChargeBudget pins the accounting boundary.
|
||||
//
|
||||
// CapPayload displaces an oversized result to disk; it must not also bill for
|
||||
// it. Spill used to charge the FULL uncapped length while the caller charged
|
||||
// the capped length on top, so a turn was billed for far more than it was ever
|
||||
// shown and ran out of budget early.
|
||||
func TestCapPayloadDoesNotChargeBudget(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
spillDir bool
|
||||
}{
|
||||
{name: "spilled to disk", spillDir: true},
|
||||
{name: "truncated inline", spillDir: false},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := ""
|
||||
if tc.spillDir {
|
||||
dir = t.TempDir()
|
||||
}
|
||||
budget := NewTurnBudget(1_000_000, dir)
|
||||
|
||||
CapPayload("big", strings.Repeat("x", 5000), 100, budget)
|
||||
|
||||
if used := budget.Used(); used != 0 {
|
||||
t.Errorf("Used() = %d after CapPayload, want 0: accounting belongs to the caller", used)
|
||||
}
|
||||
if budget.Exceeded() {
|
||||
t.Error("budget reports exceeded after a single capped result")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSpillChargesBudget is the other half: the batch-dispatch path calls Spill
|
||||
// directly and relies on it charging, so that behaviour must not drift.
|
||||
func TestSpillChargesBudget(t *testing.T) {
|
||||
budget := NewTurnBudget(1_000_000, t.TempDir())
|
||||
content := []byte(strings.Repeat("y", 300))
|
||||
|
||||
budget.Spill("tool", content)
|
||||
|
||||
if used := budget.Used(); used != len(content) {
|
||||
t.Errorf("Used() = %d, want %d", used, len(content))
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteSpillUniquePaths guards a collision the previous naming scheme hid:
|
||||
// the file name was derived from the budget's consumed count, so two spills
|
||||
// that did not change it would overwrite each other.
|
||||
func TestWriteSpillUniquePaths(t *testing.T) {
|
||||
budget := NewTurnBudget(1_000_000, t.TempDir())
|
||||
|
||||
first := budget.WriteSpill("tool", []byte("first"))
|
||||
second := budget.WriteSpill("tool", []byte("second"))
|
||||
|
||||
if first.Path == "" || second.Path == "" {
|
||||
t.Fatalf("spill paths empty: %q %q", first.Path, second.Path)
|
||||
}
|
||||
if first.Path == second.Path {
|
||||
t.Fatalf("both spills wrote to %q; the second overwrote the first", first.Path)
|
||||
}
|
||||
for _, want := range []struct {
|
||||
ref SpillRef
|
||||
body string
|
||||
}{{first, "first"}, {second, "second"}} {
|
||||
got, err := os.ReadFile(want.ref.Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != want.body {
|
||||
t.Errorf("%s holds %q, want %q", want.ref.Path, got, want.body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteSpillUniqueAcrossBudgets is the collision that matters in practice.
|
||||
// A TurnBudget is minted per chat turn and per agent stage while every one of
|
||||
// them shares a single spill directory, so a name derived from within-budget
|
||||
// state restarts each turn and the second turn silently overwrites the first --
|
||||
// leaving one session holding a reference to another session's output.
|
||||
func TestWriteSpillUniqueAcrossBudgets(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
firstTurn := NewTurnBudget(1_000_000, dir)
|
||||
secondTurn := NewTurnBudget(1_000_000, dir)
|
||||
|
||||
a := firstTurn.WriteSpill("read", []byte("first turn output"))
|
||||
b := secondTurn.WriteSpill("read", []byte("second turn output"))
|
||||
|
||||
if a.Path == "" || b.Path == "" {
|
||||
t.Fatalf("spill paths empty: %q %q", a.Path, b.Path)
|
||||
}
|
||||
if a.Path == b.Path {
|
||||
t.Fatalf("both turns wrote to %q", a.Path)
|
||||
}
|
||||
got, err := os.ReadFile(a.Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != "first turn output" {
|
||||
t.Errorf("first turn's spill holds %q; a later turn overwrote it", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteSpillFilePermissions checks the mode on the first place archie
|
||||
// persists verbatim tool output. It can hold anything the tools could read --
|
||||
// file contents, shell stdout, MCP responses -- so it must not be world- or
|
||||
// group-readable.
|
||||
func TestWriteSpillFilePermissions(t *testing.T) {
|
||||
budget := NewTurnBudget(1_000_000, t.TempDir())
|
||||
|
||||
ref := budget.WriteSpill("shell", []byte("secret output"))
|
||||
if ref.Path == "" {
|
||||
t.Fatal("spill was not written")
|
||||
}
|
||||
info, err := os.Stat(ref.Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if perm := info.Mode().Perm(); perm != 0o600 {
|
||||
t.Errorf("spill file mode = %04o, want 0600", perm)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteSpillSanitisesToolName covers a name reaching the filesystem. MCP
|
||||
// tool names come from a third-party server, so a name carrying path
|
||||
// separators is reachable input rather than a hypothetical.
|
||||
func TestWriteSpillSanitisesToolName(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
budget := NewTurnBudget(1_000_000, dir)
|
||||
|
||||
ref := budget.WriteSpill("../../etc/passwd", []byte("payload"))
|
||||
if ref.Path == "" {
|
||||
t.Fatal("spill was not written")
|
||||
}
|
||||
if filepath.Dir(ref.Path) != dir {
|
||||
t.Errorf("spill escaped to %q, want it inside %q", ref.Path, dir)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCapPayloadKeepsRunesIntact guards the truncation boundary: cutting a
|
||||
// multi-byte rune in half hands the model invalid UTF-8, which some providers
|
||||
// reject outright and others render as a replacement character mid-word.
|
||||
func TestCapPayloadKeepsRunesIntact(t *testing.T) {
|
||||
payload := strings.Repeat("é", 100) // 2 bytes per rune
|
||||
|
||||
for max := 1; max <= 20; max++ {
|
||||
got := CapPayload("read", payload, max, nil)
|
||||
if !utf8.ValidString(got) {
|
||||
t.Errorf("max=%d: CapPayload() returned invalid UTF-8: %q", max, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTurnBudgetSpillDirPermissions(t *testing.T) {
|
||||
// Create a regular file and use a sub-path as the spill directory.
|
||||
// Even root cannot write a file when a path component is a regular
|
||||
|
||||
@@ -4,6 +4,13 @@
|
||||
// Mutations from upstream:
|
||||
// - package renamed tools -> builtin (archie-core already has an
|
||||
// internal/tools package holding the registry these are registered into).
|
||||
// - path confinement is switchable (SetPathConfinement). tau's agent is a
|
||||
// coding assistant scoped to one project, where a workspace jail is always
|
||||
// right. archie's chat agent is also used as a general-purpose operator --
|
||||
// partitioning a disk and mounting it, migrating data between filesystems,
|
||||
// editing unit files -- and a jail makes that impossible. The shell tool
|
||||
// was never confined anyway, so the jail only ever shaped which tool got
|
||||
// used, not what the agent could reach.
|
||||
//
|
||||
// Refresh by diffing against that path at a newer tau commit. Do not
|
||||
// edit without recording the change above.
|
||||
@@ -14,6 +21,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -70,9 +78,41 @@ func isReadConfined(base, target string) bool {
|
||||
return cache != "" && isConfined(cache, target)
|
||||
}
|
||||
|
||||
// pathConfinement gates the workspace jail on the file tools. It defaults to
|
||||
// on; see SetPathConfinement.
|
||||
//
|
||||
// Process-wide rather than per-tool because it is a deployment posture, not a
|
||||
// property of one tool: a daemon either trusts its agent with the filesystem or
|
||||
// it does not, and there is one builtin tool set per process.
|
||||
var pathConfinement atomic.Bool
|
||||
|
||||
func init() { pathConfinement.Store(true) }
|
||||
|
||||
// SetPathConfinement turns the workspace jail on the read, write, edit, find
|
||||
// and grep tools on or off. It is set once at startup from configuration.
|
||||
//
|
||||
// Disabling it makes those tools reach any absolute path. That is the point:
|
||||
// an agent asked to partition a new disk, mount it and migrate data onto it is
|
||||
// working across the filesystem by definition, and a jail turns a capable
|
||||
// operator into a useless one.
|
||||
//
|
||||
// It widens which TOOL can do the work, not what the agent can reach. The shell
|
||||
// tool has never been confined -- it can cd anywhere, and only command.Hardline
|
||||
// screens it -- so a jailed deployment simply pushed the agent into doing
|
||||
// everything through shell, losing the truncation, line numbering,
|
||||
// read-before-write tracking and structured errors the dedicated tools provide.
|
||||
//
|
||||
// Relative paths still resolve against the workspace either way (see
|
||||
// resolvePath), so turning this off does not silently move where an existing
|
||||
// relative path lands.
|
||||
func SetPathConfinement(enabled bool) { pathConfinement.Store(enabled) }
|
||||
|
||||
// isConfined checks whether target is within (or equal to) the base directory.
|
||||
// Returns false if target escapes via ../ or is an unrelated absolute path.
|
||||
func isConfined(base, target string) bool {
|
||||
if !pathConfinement.Load() {
|
||||
return true // confinement disabled by configuration
|
||||
}
|
||||
if base == "" {
|
||||
return true // no confinement if cwd is unset
|
||||
}
|
||||
|
||||
@@ -9,6 +9,65 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestPathConfinementToggle covers the escape hatch for deployments where the
|
||||
// agent is a general-purpose operator rather than a coding assistant scoped to
|
||||
// one project -- formatting and mounting a new disk, migrating data between
|
||||
// filesystems, editing service units. Confining those to one directory makes
|
||||
// the agent useless, so the jail has to be switchable.
|
||||
//
|
||||
// Not parallel: the toggle is process-wide.
|
||||
func TestPathConfinementToggle(t *testing.T) {
|
||||
const workspace = "/home/sam"
|
||||
outside := []string{"/etc/fstab", "/mnt/newdisk/data", "/srv"}
|
||||
|
||||
t.Run("confined by default", func(t *testing.T) {
|
||||
for _, target := range outside {
|
||||
if isConfined(workspace, target) {
|
||||
t.Errorf("isConfined(%q, %q) = true, want false by default", workspace, target)
|
||||
}
|
||||
if isReadConfined(workspace, target) {
|
||||
t.Errorf("isReadConfined(%q, %q) = true, want false by default", workspace, target)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unconfined when disabled", func(t *testing.T) {
|
||||
SetPathConfinement(false)
|
||||
t.Cleanup(func() { SetPathConfinement(true) })
|
||||
|
||||
for _, target := range outside {
|
||||
if !isConfined(workspace, target) {
|
||||
t.Errorf("isConfined(%q, %q) = false with confinement disabled", workspace, target)
|
||||
}
|
||||
if !isReadConfined(workspace, target) {
|
||||
t.Errorf("isReadConfined(%q, %q) = false with confinement disabled", workspace, target)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("restored after re-enabling", func(t *testing.T) {
|
||||
if isConfined(workspace, "/etc/fstab") {
|
||||
t.Error("confinement did not come back after being re-enabled")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestResolvePathUnaffectedByConfinement pins the property that makes the
|
||||
// toggle safe to flip: relative paths stay rooted at the workspace either way,
|
||||
// so turning the jail off widens what an ABSOLUTE path can reach without
|
||||
// silently changing where a relative one lands.
|
||||
func TestResolvePathUnaffectedByConfinement(t *testing.T) {
|
||||
SetPathConfinement(false)
|
||||
t.Cleanup(func() { SetPathConfinement(true) })
|
||||
|
||||
if got := resolvePath("/home/sam", "notes.md"); got != "/home/sam/notes.md" {
|
||||
t.Errorf("resolvePath relative = %q, want it still rooted at the workspace", got)
|
||||
}
|
||||
if got := resolvePath("/home/sam", "/etc/fstab"); got != "/etc/fstab" {
|
||||
t.Errorf("resolvePath absolute = %q, want it untouched", got)
|
||||
}
|
||||
}
|
||||
|
||||
// withGoModCache points the module-cache lookup at a temp dir for the duration
|
||||
// of a test, so these tests never depend on the host's real GOMODCACHE.
|
||||
func withGoModCache(t *testing.T, dir string) {
|
||||
|
||||
+36
-39
@@ -329,6 +329,11 @@ func firstParallelSafeIdx(groups []gatedGroup) (int, bool) {
|
||||
|
||||
// dispatchOne runs a single call with budget, guardrail, and per-tool
|
||||
// limit checks.
|
||||
//
|
||||
// Callers that do not own the batch cannot use this: it caps
|
||||
// DispatchResult.Preview, whereas a caller handing the result straight to a
|
||||
// model has to cap the payload it actually sends. [CapPayload] is the shared
|
||||
// rule between the two; this sequence is specific to batch dispatch.
|
||||
func dispatchOne(
|
||||
ctx context.Context,
|
||||
call ToolCall,
|
||||
@@ -353,7 +358,7 @@ func dispatchOne(
|
||||
result := invokeTool(ctx, call)
|
||||
|
||||
// Enforce per-tool result size limit (17.4).
|
||||
enforcePerToolLimit(&result, call.Entry, budget)
|
||||
capped := enforcePerToolLimit(&result, call.Entry, budget)
|
||||
|
||||
// Track guardrail.
|
||||
if guardrail != nil {
|
||||
@@ -366,63 +371,55 @@ func dispatchOne(
|
||||
|
||||
// Consume budget.
|
||||
if budget != nil && !result.IsError() {
|
||||
consumeBudgetForResult(&result, call.Entry, budget)
|
||||
consumeBudgetForResult(&result, call.Entry, budget, capped)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// enforcePerToolLimit checks whether the result exceeds the tool's
|
||||
// MaxResultSizeChars and spills or truncates accordingly. When a budget
|
||||
// is available, the full output is spilled to disk; otherwise it is
|
||||
// truncated inline. If spill-to-disk fails, falls back to inline
|
||||
// truncation.
|
||||
func enforcePerToolLimit(result *DispatchResult, entry ToolEntry, budget *TurnBudget) {
|
||||
// enforcePerToolLimit replaces the preview when the result exceeds the tool's
|
||||
// MaxResultSizeChars, spilling to disk when the budget offers a directory and
|
||||
// truncating inline otherwise. [CapPayload] owns that rule; this only decides
|
||||
// whether it applies.
|
||||
//
|
||||
// Returns whether the result was capped, so the budget accounting below does
|
||||
// not spill the same output a second time.
|
||||
func enforcePerToolLimit(result *DispatchResult, entry ToolEntry, budget *TurnBudget) bool {
|
||||
if result.IsError() || entry.MaxResultSizeChars <= 0 || result.Output == nil {
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
fullOutput := fmt.Sprint(result.Output)
|
||||
if len(fullOutput) <= entry.MaxResultSizeChars {
|
||||
return
|
||||
}
|
||||
|
||||
// Result exceeds per-tool limit.
|
||||
if budget != nil {
|
||||
ref := budget.Spill(entry.Name, []byte(fullOutput))
|
||||
if ref.Path != "" {
|
||||
result.Preview = fmt.Sprintf("[spilled to %s, %d chars]", ref.Path, ref.SizeChars)
|
||||
return
|
||||
}
|
||||
// Spill failed -- fall through to inline truncation.
|
||||
}
|
||||
|
||||
// Truncate inline when no spill directory or spill failed.
|
||||
if entry.MaxResultSizeChars > 0 && len(fullOutput) > entry.MaxResultSizeChars {
|
||||
result.Preview = fullOutput[:entry.MaxResultSizeChars] +
|
||||
"... [truncated (per-tool limit)]"
|
||||
capped := CapPayload(entry.Name, fullOutput, entry.MaxResultSizeChars, budget)
|
||||
if capped == fullOutput {
|
||||
return false
|
||||
}
|
||||
result.Preview = capped
|
||||
return true
|
||||
}
|
||||
|
||||
// consumeBudgetForResult accounts for the result against the turn budget.
|
||||
// When the budget is exceeded during consumption, the full output is
|
||||
// spilled to disk and the preview is replaced with a spill reference.
|
||||
func consumeBudgetForResult(result *DispatchResult, entry ToolEntry, budget *TurnBudget) {
|
||||
func consumeBudgetForResult(result *DispatchResult, entry ToolEntry, budget *TurnBudget, alreadyCapped bool) {
|
||||
if budget == nil || result.IsError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Only consume budget for fresh results (not already spilled by
|
||||
// per-tool limit enforcement).
|
||||
if !budget.Consume(len(result.Preview)) {
|
||||
// Budget exceeded on this result -- spill the full output.
|
||||
if result.Output != nil {
|
||||
fullOutput := fmt.Sprint(result.Output)
|
||||
ref := budget.Spill(entry.Name, []byte(fullOutput))
|
||||
if ref.Path != "" {
|
||||
result.Preview = fmt.Sprintf("[spilled to %s, %d chars]", ref.Path, ref.SizeChars)
|
||||
}
|
||||
}
|
||||
if budget.Consume(len(result.Preview)) {
|
||||
return
|
||||
}
|
||||
|
||||
// Budget exhausted on this result. Spill the full output so it is
|
||||
// displaced rather than lost -- unless the per-tool limit already did,
|
||||
// in which case repeating it would write a second identical file and
|
||||
// orphan the first, whose path the preview already names.
|
||||
if alreadyCapped || result.Output == nil {
|
||||
return
|
||||
}
|
||||
fullOutput := fmt.Sprint(result.Output)
|
||||
if ref := budget.WriteSpill(entry.Name, []byte(fullOutput)); ref.Path != "" {
|
||||
result.Preview = fmt.Sprintf("[spilled to %s, %d chars]", ref.Path, ref.SizeChars)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,11 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// maxTruncationNotice bounds the explanatory notice CapPayload appends when it
|
||||
// truncates inline. Tests assert the capped payload plus this allowance, so a
|
||||
// notice that grew without bound would fail rather than quietly eat context.
|
||||
const maxTruncationNotice = 128
|
||||
|
||||
func TestExecutionClassString(t *testing.T) {
|
||||
tests := []struct {
|
||||
c ExecutionClass
|
||||
@@ -612,10 +617,12 @@ func TestDispatchPerToolLimitSpillFailureFallback(t *testing.T) {
|
||||
}
|
||||
|
||||
// Should be truncated to MaxResultSizeChars even though spill failed.
|
||||
if !strings.Contains(results[0].Preview, "truncated (per-tool limit)") {
|
||||
if !strings.Contains(results[0].Preview, "truncated") {
|
||||
t.Errorf("expected inline truncation fallback, got: %s", results[0].Preview)
|
||||
}
|
||||
maxPreview := len("[... truncated (per-tool limit)]") + e.MaxResultSizeChars
|
||||
// The payload is cut to the limit; the notice explaining the cut is the
|
||||
// only thing allowed past it.
|
||||
maxPreview := e.MaxResultSizeChars + maxTruncationNotice
|
||||
if len(results[0].Preview) > maxPreview {
|
||||
t.Errorf("preview too long (%d chars), expected at most %d", len(results[0].Preview), maxPreview)
|
||||
}
|
||||
@@ -667,7 +674,7 @@ func TestDispatchPerToolLimitNoBudgetTruncates(t *testing.T) {
|
||||
if len(results) != 1 {
|
||||
t.Fatalf("expected 1 result, got %d", len(results))
|
||||
}
|
||||
if !strings.Contains(results[0].Preview, "truncated (per-tool limit)") {
|
||||
if !strings.Contains(results[0].Preview, "truncated") {
|
||||
t.Errorf("expected truncation with nil budget, got: %s", results[0].Preview)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,10 @@ type Provider struct {
|
||||
// workspace is the directory file and shell operations are rooted at.
|
||||
workspace string
|
||||
|
||||
// unrestricted lifts the workspace jail from the file tools. See
|
||||
// config.ChatConfig.UnrestrictedFilesystem for when that is wanted.
|
||||
unrestricted bool
|
||||
|
||||
// registry holds the constructed tools. Built once in Start so
|
||||
// Discover cannot partially fail.
|
||||
registry *toolsbuiltin.Registry
|
||||
@@ -36,8 +40,11 @@ type Provider struct {
|
||||
// New creates a provider rooted at workspace. An empty workspace is a
|
||||
// configuration error, reported by Start rather than silently defaulting to
|
||||
// the daemon's own working directory.
|
||||
func New(workspace string) *Provider {
|
||||
return &Provider{workspace: workspace}
|
||||
//
|
||||
// unrestricted lets the file tools reach absolute paths outside workspace;
|
||||
// relative paths still resolve against it either way.
|
||||
func New(workspace string, unrestricted bool) *Provider {
|
||||
return &Provider{workspace: workspace, unrestricted: unrestricted}
|
||||
}
|
||||
|
||||
// Manifest declares the adapter's tool capability.
|
||||
@@ -59,6 +66,11 @@ func (p *Provider) Start(ctx context.Context) error {
|
||||
if p.workspace == "" {
|
||||
return errors.New("workspace tool provider: workspace directory is not configured")
|
||||
}
|
||||
// Set before the tools are built. Confinement is consulted per call, so
|
||||
// ordering only matters in that it must precede the first tool call, but
|
||||
// keeping it next to construction is where a reader will look for it.
|
||||
toolsbuiltin.SetPathConfinement(!p.unrestricted)
|
||||
|
||||
registry := toolsbuiltin.NewRegistry()
|
||||
if err := toolsbuiltin.RegisterBuiltins(registry, p.workspace); err != nil {
|
||||
return fmt.Errorf("workspace tool provider: register builtins: %w", err)
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
func startedProvider(t *testing.T, workspace string) *provider.Provider {
|
||||
t.Helper()
|
||||
p := provider.New(workspace)
|
||||
p := provider.New(workspace, false)
|
||||
if err := p.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
@@ -155,7 +155,80 @@ func shellHandler(t *testing.T, workspace string) func(context.Context, map[stri
|
||||
func TestUnconfiguredWorkspaceIsRejected(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if err := provider.New("").Start(context.Background()); err == nil {
|
||||
if err := provider.New("", false).Start(context.Background()); err == nil {
|
||||
t.Error("a provider with no workspace started successfully")
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnrestrictedFilesystemReachesOutsideWorkspace covers the operator
|
||||
// posture end to end, through a real read of a real file.
|
||||
//
|
||||
// A deployment whose agent partitions disks, mounts them and migrates data is
|
||||
// working across the filesystem by definition. Confined, every one of those
|
||||
// touches has to go through shell -- which was never confined anyway -- so the
|
||||
// jail only ever decided which tool did the work, not what the agent reached.
|
||||
//
|
||||
// Not parallel: confinement is process-wide, so these two subtests must not
|
||||
// run beside tests that assume the default.
|
||||
func TestUnrestrictedFilesystemReachesOutsideWorkspace(t *testing.T) {
|
||||
// A file deliberately outside the workspace, as /etc or a fresh mount
|
||||
// would be.
|
||||
outside := filepath.Join(t.TempDir(), "fstab")
|
||||
if err := os.WriteFile(outside, []byte("UUID=1234 /mnt/newdisk ext4 defaults 0 2\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
unrestricted bool
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "confined refuses", unrestricted: false, wantErr: true},
|
||||
{name: "unrestricted reads", unrestricted: true},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p := provider.New(t.TempDir(), tc.unrestricted)
|
||||
if err := p.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
|
||||
entries, err := p.Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var read func(context.Context, map[string]any) (any, error)
|
||||
for _, e := range entries {
|
||||
if e.Name == "read" {
|
||||
read = e.Handler
|
||||
}
|
||||
}
|
||||
if read == nil {
|
||||
t.Fatal("no read tool discovered")
|
||||
}
|
||||
|
||||
out, err := read(context.Background(), map[string]any{"path": outside})
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("read reached outside the workspace while confined")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("read was refused with confinement disabled: %v", err)
|
||||
}
|
||||
if text, ok := out.(string); !ok || !strings.Contains(text, "/mnt/newdisk") {
|
||||
t.Errorf("read returned %#v, want the file contents", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Leave the process as we found it for any test that runs after.
|
||||
t.Cleanup(func() {
|
||||
p := provider.New(t.TempDir(), false)
|
||||
_ = p.Start(context.Background())
|
||||
_ = p.Stop(context.Background())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package webfetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// ToolName is the registry name of the fetch tool.
|
||||
const ToolName = "web_fetch"
|
||||
|
||||
// Tool builds the registry entry for cfg, or nil when the fetcher is
|
||||
// disabled. Returning nil rather than an entry that always refuses keeps a
|
||||
// capability the operator turned off out of the model's tool list entirely --
|
||||
// an advertised tool that never works costs a round trip to discover.
|
||||
func Tool(cfg Config) *tools.ToolEntry {
|
||||
if !cfg.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
client := New(cfg)
|
||||
|
||||
return &tools.ToolEntry{
|
||||
Name: ToolName,
|
||||
Toolset: "web",
|
||||
Description: "Fetch a web page or API response over http/https and return its readable text. " +
|
||||
"HTML is reduced to text; JSON, XML and plain text are returned as received. " +
|
||||
"Use it to read documentation, changelogs, issues or any URL the user provides.",
|
||||
// Reading a URL has no side effect on this host, so it is safe to
|
||||
// run alongside other reads.
|
||||
Classification: tools.ClassIdempotent,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"url": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Absolute http:// or https:// URL to fetch.",
|
||||
},
|
||||
"raw": map[string]any{
|
||||
"type": "boolean",
|
||||
"description": "Return the response body unchanged instead of extracting readable text from HTML. Defaults to false.",
|
||||
},
|
||||
},
|
||||
"required": []any{"url"},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
target, _ := input["url"].(string)
|
||||
if strings.TrimSpace(target) == "" {
|
||||
return nil, fmt.Errorf("%s: url is required", ToolName)
|
||||
}
|
||||
raw, _ := input["raw"].(bool)
|
||||
|
||||
body, err := client.Fetch(ctx, target, raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", ToolName, err)
|
||||
}
|
||||
return body, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
// Package webfetch retrieves a URL on the model's behalf and returns readable
|
||||
// text.
|
||||
//
|
||||
// The interesting part is not the fetch, it is the refusals. archied runs on a
|
||||
// host where the Docker API, NATS and its own dashboard answer on private
|
||||
// addresses, and the URL it is asked to fetch arrives in chat -- an untrusted
|
||||
// path, since a forge issue body or an inbound email can end up quoted into a
|
||||
// turn. So the address is vetted at dial time rather than by inspecting the
|
||||
// URL: a name that looks public can resolve to a private address, and only the
|
||||
// resolved address tells the truth.
|
||||
package webfetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxRedirects bounds a redirect chain. Each hop is re-vetted by the
|
||||
// dialer, so this only stops a loop from spending the timeout.
|
||||
maxRedirects = 5
|
||||
|
||||
// statusExcerpt is how much of a failed response body is quoted back.
|
||||
// Enough to tell an API error message from an HTML error page.
|
||||
statusExcerpt = 200
|
||||
)
|
||||
|
||||
// Config controls the fetcher. The zero value is disabled.
|
||||
type Config struct {
|
||||
// Enabled advertises the tool. When false, Tool returns nil so the
|
||||
// model is never shown a capability the operator turned off.
|
||||
Enabled bool
|
||||
|
||||
// Timeout bounds one fetch, redirects included.
|
||||
Timeout time.Duration
|
||||
|
||||
// MaxBytes bounds how much of a response body is read.
|
||||
MaxBytes int64
|
||||
|
||||
// AllowPrivateNetworks permits loopback, private, link-local and
|
||||
// carrier-grade-NAT addresses. Off by default: leaving it off is what
|
||||
// keeps the daemon's own control surfaces out of reach.
|
||||
AllowPrivateNetworks bool
|
||||
}
|
||||
|
||||
// Client fetches URLs under a Config.
|
||||
type Client struct {
|
||||
cfg Config
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
// New builds a Client whose transport refuses disallowed addresses at dial
|
||||
// time.
|
||||
func New(cfg Config) *Client {
|
||||
c := &Client{cfg: cfg}
|
||||
transport := &http.Transport{
|
||||
DialContext: c.dialContext,
|
||||
TLSHandshakeTimeout: cfg.Timeout,
|
||||
ResponseHeaderTimeout: cfg.Timeout,
|
||||
DisableKeepAlives: true,
|
||||
}
|
||||
c.http = &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: cfg.Timeout,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= maxRedirects {
|
||||
return fmt.Errorf("stopped after %d redirects", maxRedirects)
|
||||
}
|
||||
return checkScheme(req.URL)
|
||||
},
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// Fetch retrieves rawURL and returns its readable content. When raw is true
|
||||
// the body is returned as received rather than reduced to text.
|
||||
func (c *Client) Fetch(ctx context.Context, rawURL string, raw bool) (string, error) {
|
||||
parsed, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid url %q: %w", rawURL, err)
|
||||
}
|
||||
if err := checkScheme(parsed); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
// Some sites serve a different, poorer page to an unidentified client,
|
||||
// and a few refuse one outright.
|
||||
req.Header.Set("User-Agent", "archie-webfetch/1.0 (+https://github.com/samcharles93/archie-core)")
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,text/plain,application/json;q=0.9,*/*;q=0.1")
|
||||
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return "", unwrapFetchError(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, truncated, err := c.readBody(resp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("%s returned %d %s: %s",
|
||||
parsed.Redacted(), resp.StatusCode, http.StatusText(resp.StatusCode), excerpt(body))
|
||||
}
|
||||
|
||||
mediaType := contentType(resp)
|
||||
rendered, err := render(mediaType, body, raw, len(body))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if truncated {
|
||||
rendered += fmt.Sprintf("\n\n[webfetch: response truncated at %d bytes]", c.cfg.MaxBytes)
|
||||
}
|
||||
return rendered, nil
|
||||
}
|
||||
|
||||
// readBody reads at most MaxBytes, reporting whether more was available.
|
||||
func (c *Client) readBody(resp *http.Response) (string, bool, error) {
|
||||
limit := c.cfg.MaxBytes
|
||||
if limit <= 0 {
|
||||
limit = 1 << 20
|
||||
}
|
||||
// One byte past the limit distinguishes "exactly at the limit" from
|
||||
// "there was more".
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return string(data[:limit]), true, nil
|
||||
}
|
||||
return string(data), false, nil
|
||||
}
|
||||
|
||||
// render turns a body into what the model sees, refusing anything that is not
|
||||
// text. Returning binary would spend the context window on bytes the model
|
||||
// cannot read.
|
||||
func render(mediaType, body string, raw bool, size int) (string, error) {
|
||||
switch {
|
||||
case raw:
|
||||
return body, nil
|
||||
case mediaType == "text/html", mediaType == "application/xhtml+xml":
|
||||
return htmlToText(body), nil
|
||||
case strings.HasPrefix(mediaType, "text/"),
|
||||
mediaType == "application/json",
|
||||
mediaType == "application/xml",
|
||||
strings.HasSuffix(mediaType, "+json"),
|
||||
strings.HasSuffix(mediaType, "+xml"):
|
||||
return body, nil
|
||||
default:
|
||||
return "", fmt.Errorf("refusing %s (%d bytes): only text, html, json and xml are readable", mediaType, size)
|
||||
}
|
||||
}
|
||||
|
||||
// contentType returns the media type without parameters, defaulting to plain
|
||||
// text when the server sends nothing.
|
||||
func contentType(resp *http.Response) string {
|
||||
raw := resp.Header.Get("Content-Type")
|
||||
if raw == "" {
|
||||
return "text/plain"
|
||||
}
|
||||
if i := strings.IndexByte(raw, ';'); i >= 0 {
|
||||
raw = raw[:i]
|
||||
}
|
||||
return strings.ToLower(strings.TrimSpace(raw))
|
||||
}
|
||||
|
||||
// excerpt quotes the start of a failed response so the model can tell an API
|
||||
// error message from a generic error page.
|
||||
func excerpt(body string) string {
|
||||
body = strings.TrimSpace(body)
|
||||
if len(body) <= statusExcerpt {
|
||||
return body
|
||||
}
|
||||
return body[:statusExcerpt] + "..."
|
||||
}
|
||||
|
||||
// checkScheme allows only http and https. Anything else -- file:, data:,
|
||||
// gopher: -- reaches something that is not a web server.
|
||||
func checkScheme(u *url.URL) error {
|
||||
switch u.Scheme {
|
||||
case "http", "https":
|
||||
return nil
|
||||
case "":
|
||||
return fmt.Errorf("url %q has no scheme: give an absolute http:// or https:// url", u.String())
|
||||
default:
|
||||
return fmt.Errorf("refusing scheme %q: only http and https are fetched", u.Scheme)
|
||||
}
|
||||
}
|
||||
|
||||
// unwrapFetchError strips the url.Error wrapper so the refusal the dialer or
|
||||
// the redirect check produced is what the model reads, rather than being
|
||||
// buried behind Go's transport prose.
|
||||
func unwrapFetchError(err error) error {
|
||||
var urlErr *url.Error
|
||||
if errors.As(err, &urlErr) && urlErr.Err != nil {
|
||||
return urlErr.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// dialContext resolves the host and refuses addresses the daemon must not be
|
||||
// talked into reaching, then dials a vetted address directly.
|
||||
//
|
||||
// Vetting here rather than on the URL is the whole point: between a pre-flight
|
||||
// check and the connection, a name can resolve to something else. Dialing the
|
||||
// address that was actually approved closes that window.
|
||||
func (c *Client) dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid address %q: %w", addr, err)
|
||||
}
|
||||
|
||||
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dialer := &net.Dialer{Timeout: c.cfg.Timeout}
|
||||
var refused []string
|
||||
for _, ip := range ips {
|
||||
if !c.addressAllowed(ip.IP) {
|
||||
refused = append(refused, ip.IP.String())
|
||||
continue
|
||||
}
|
||||
conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(ip.IP.String(), port))
|
||||
if err == nil {
|
||||
return conn, nil
|
||||
}
|
||||
}
|
||||
|
||||
if len(refused) > 0 {
|
||||
return nil, fmt.Errorf(
|
||||
"refusing to connect to %s: it resolves to the private or loopback address %s, which is where this host's own services live; set tools.web_fetch.allow_private_networks to permit it",
|
||||
host, strings.Join(refused, ", "))
|
||||
}
|
||||
return nil, fmt.Errorf("could not connect to %s", host)
|
||||
}
|
||||
|
||||
// addressAllowed reports whether an address may be reached.
|
||||
func (c *Client) addressAllowed(ip net.IP) bool {
|
||||
if c.cfg.AllowPrivateNetworks {
|
||||
return true
|
||||
}
|
||||
switch {
|
||||
case ip.IsLoopback(), ip.IsPrivate(), ip.IsUnspecified(),
|
||||
ip.IsLinkLocalUnicast(), ip.IsLinkLocalMulticast(),
|
||||
ip.IsInterfaceLocalMulticast(), ip.IsMulticast():
|
||||
return false
|
||||
case isCarrierGradeNAT(ip):
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// isCarrierGradeNAT reports whether ip is in 100.64.0.0/10, which net.IP has
|
||||
// no predicate for and which routes to infrastructure rather than the public
|
||||
// internet.
|
||||
func isCarrierGradeNAT(ip net.IP) bool {
|
||||
v4 := ip.To4()
|
||||
return v4 != nil && v4[0] == 100 && v4[1] >= 64 && v4[1] <= 127
|
||||
}
|
||||
|
||||
// blockedElements hold text that is markup machinery rather than content.
|
||||
var blockedElements = map[string]bool{
|
||||
"script": true, "style": true, "noscript": true,
|
||||
"head": true, "template": true, "svg": true,
|
||||
}
|
||||
|
||||
// htmlToText reduces a document to the text a reader would see. It is
|
||||
// deliberately simple: the goal is to spend the context window on prose
|
||||
// instead of markup, not to reproduce a browser.
|
||||
func htmlToText(body string) string {
|
||||
doc, err := html.Parse(strings.NewReader(body))
|
||||
if err != nil {
|
||||
// Unparseable markup still has readable text in it; handing back
|
||||
// the raw document beats returning nothing.
|
||||
return body
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
var walk func(*html.Node)
|
||||
walk = func(n *html.Node) {
|
||||
if n.Type == html.ElementNode && blockedElements[n.Data] {
|
||||
return
|
||||
}
|
||||
if n.Type == html.TextNode {
|
||||
if text := strings.TrimSpace(n.Data); text != "" {
|
||||
b.WriteString(text)
|
||||
b.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
for child := n.FirstChild; child != nil; child = child.NextSibling {
|
||||
walk(child)
|
||||
}
|
||||
// Block-level elements end a line so headings and paragraphs do not
|
||||
// run together into one wall of text.
|
||||
if n.Type == html.ElementNode && breaksLine(n.Data) {
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
}
|
||||
walk(doc)
|
||||
|
||||
return collapseBlankLines(b.String())
|
||||
}
|
||||
|
||||
// breaksLine reports whether an element should end the current line.
|
||||
func breaksLine(tag string) bool {
|
||||
switch tag {
|
||||
case "p", "div", "br", "li", "tr", "section", "article", "header", "footer",
|
||||
"h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "pre":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// collapseBlankLines trims each line and squeezes runs of blank lines, which
|
||||
// nested markup produces in quantity.
|
||||
func collapseBlankLines(s string) string {
|
||||
lines := strings.Split(s, "\n")
|
||||
out := make([]string, 0, len(lines))
|
||||
blank := false
|
||||
for _, line := range lines {
|
||||
line = strings.Join(strings.Fields(line), " ")
|
||||
if line == "" {
|
||||
if blank {
|
||||
continue
|
||||
}
|
||||
blank = true
|
||||
} else {
|
||||
blank = false
|
||||
}
|
||||
out = append(out, line)
|
||||
}
|
||||
return strings.TrimSpace(strings.Join(out, "\n"))
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package webfetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// testConfig is the base every case starts from. Private networks are allowed
|
||||
// because httptest binds loopback; the cases that exercise the SSRF control
|
||||
// override it explicitly.
|
||||
func testConfig() Config {
|
||||
return Config{
|
||||
Enabled: true,
|
||||
Timeout: 5 * time.Second,
|
||||
MaxBytes: 1 << 20,
|
||||
AllowPrivateNetworks: true,
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchExtractsContent(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
contentType string
|
||||
body string
|
||||
raw bool
|
||||
wantContain []string
|
||||
wantAbsent []string
|
||||
}{
|
||||
{
|
||||
name: "html is reduced to readable text",
|
||||
contentType: "text/html; charset=utf-8",
|
||||
body: `<html><head><title>T</title>
|
||||
<style>body{color:red}</style>
|
||||
<script>var x = "should not appear";</script></head>
|
||||
<body><h1>Heading</h1><p>Body text here.</p></body></html>`,
|
||||
wantContain: []string{"Heading", "Body text here."},
|
||||
wantAbsent: []string{"should not appear", "color:red", "<p>"},
|
||||
},
|
||||
{
|
||||
name: "raw returns the html unmodified",
|
||||
contentType: "text/html",
|
||||
body: `<p>markup</p>`,
|
||||
raw: true,
|
||||
wantContain: []string{"<p>markup</p>"},
|
||||
},
|
||||
{
|
||||
name: "json passes through untouched",
|
||||
contentType: "application/json",
|
||||
body: `{"key":"value"}`,
|
||||
wantContain: []string{`{"key":"value"}`},
|
||||
},
|
||||
{
|
||||
name: "plain text passes through untouched",
|
||||
contentType: "text/plain",
|
||||
body: "just words",
|
||||
wantContain: []string{"just words"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", tc.contentType)
|
||||
fmt.Fprint(w, tc.body)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
got, err := New(testConfig()).Fetch(context.Background(), srv.URL, tc.raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range tc.wantContain {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("result %q does not contain %q", got, want)
|
||||
}
|
||||
}
|
||||
for _, absent := range tc.wantAbsent {
|
||||
if strings.Contains(got, absent) {
|
||||
t.Errorf("result %q should not contain %q", got, absent)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchRejectsUnsupportedContentType(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
fmt.Fprint(w, "\x89PNG\r\n\x1a\n")
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() error = nil, want a refusal naming the content type")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "image/png") {
|
||||
t.Errorf("error = %v, want it to name the content type", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchCapsBodySize(t *testing.T) {
|
||||
const limit = 512
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
fmt.Fprint(w, strings.Repeat("a", limit*10))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cfg := testConfig()
|
||||
cfg.MaxBytes = limit
|
||||
got, err := New(cfg).Fetch(context.Background(), srv.URL, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) > limit*2 { // body plus a truncation notice, nowhere near 10x
|
||||
t.Errorf("result is %d bytes, want it bounded near the %d-byte limit", len(got), limit)
|
||||
}
|
||||
if !strings.Contains(got, "truncated") {
|
||||
t.Errorf("result %q should say it was truncated", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchReportsHTTPStatus(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{name: "not found", status: http.StatusNotFound, body: "no such page"},
|
||||
{name: "forbidden", status: http.StatusForbidden, body: "denied"},
|
||||
{name: "rate limited", status: http.StatusTooManyRequests, body: "slow down"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(tc.status)
|
||||
fmt.Fprint(w, tc.body)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatalf("Fetch() error = nil, want the %d reported", tc.status)
|
||||
}
|
||||
// The model has to tell 404 from 403 from a rate limit to decide
|
||||
// whether retrying or rewording the URL is worth it.
|
||||
if !strings.Contains(err.Error(), fmt.Sprint(tc.status)) {
|
||||
t.Errorf("error = %v, want it to carry status %d", err, tc.status)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.body) {
|
||||
t.Errorf("error = %v, want it to carry a body excerpt", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchCapsRedirects(t *testing.T) {
|
||||
var srv *httptest.Server
|
||||
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, srv.URL+"/next", http.StatusFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() error = nil, want a redirect-limit refusal")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "redirect") {
|
||||
t.Errorf("error = %v, want it to name the redirect limit", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchRejectsUnsupportedSchemes(t *testing.T) {
|
||||
tests := []string{
|
||||
"file:///etc/passwd",
|
||||
"ftp://example.com/x",
|
||||
"gopher://example.com",
|
||||
"data:text/plain,hello",
|
||||
"not-a-url",
|
||||
}
|
||||
|
||||
for _, target := range tests {
|
||||
t.Run(target, func(t *testing.T) {
|
||||
_, err := New(testConfig()).Fetch(context.Background(), target, false)
|
||||
if err == nil {
|
||||
t.Fatalf("Fetch(%q) error = nil, want a scheme refusal", target)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchBlocksPrivateAddresses is the SSRF control. archied runs on a host
|
||||
// where the Docker API, NATS and its own dashboard are reachable on private
|
||||
// addresses, so a model that can be talked into fetching one of those is a
|
||||
// real hole. httptest binds loopback, which makes it exactly the case to
|
||||
// assert against.
|
||||
func TestFetchBlocksPrivateAddresses(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
fmt.Fprint(w, "internal service")
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
t.Run("blocked by default", func(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.AllowPrivateNetworks = false
|
||||
_, err := New(cfg).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() reached a loopback address, want a refusal")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "private") && !strings.Contains(err.Error(), "loopback") {
|
||||
t.Errorf("error = %v, want it to explain the address was refused", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allowed when configured", func(t *testing.T) {
|
||||
cfg := testConfig() // AllowPrivateNetworks is true
|
||||
got, err := New(cfg).Fetch(context.Background(), srv.URL, false)
|
||||
if err != nil {
|
||||
t.Fatalf("Fetch() with private networks allowed: %v", err)
|
||||
}
|
||||
if !strings.Contains(got, "internal service") {
|
||||
t.Errorf("result = %q, want the body", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestFetchBlocksAtDialTime proves the check is on the resolved address rather
|
||||
// than on the URL string. A hostname that looks public but resolves to a
|
||||
// private address must still be refused, which a pre-flight URL check cannot
|
||||
// do and which is how DNS-rebinding defeats one.
|
||||
func TestFetchBlocksAtDialTime(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.AllowPrivateNetworks = false
|
||||
|
||||
// localtest.me and its subdomains are a public DNS name resolving to
|
||||
// 127.0.0.1. Resolution may be unavailable in a sandbox, so a lookup
|
||||
// failure is not a test failure -- but a success must be a refusal.
|
||||
_, err := New(cfg).Fetch(context.Background(), "http://localtest.me/", false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() reached a public name resolving to loopback, want a refusal")
|
||||
}
|
||||
if strings.Contains(err.Error(), "scheme") {
|
||||
t.Errorf("error = %v, want an address refusal rather than a scheme refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolDisabledReturnsNil(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.Enabled = false
|
||||
if Tool(cfg) != nil {
|
||||
t.Error("Tool() returned an entry while disabled, want nil so it is not advertised")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolRejectsMissingURL(t *testing.T) {
|
||||
entry := Tool(testConfig())
|
||||
if entry == nil {
|
||||
t.Fatal("Tool() = nil, want an entry when enabled")
|
||||
}
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{}); err == nil {
|
||||
t.Error("Handler() error = nil, want a refusal when url is absent")
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
@@ -70,7 +71,7 @@ func (s *Server) chatReady(w http.ResponseWriter) (*ChatService, bool) {
|
||||
http.Error(w, "chat is not configured", http.StatusNotImplemented)
|
||||
return nil, false
|
||||
}
|
||||
if s.Chat.Router.Updates == nil && s.Chat.Updates != nil {
|
||||
if !chatUpdateServiceConfigured(s.Chat.Router.Updates) && chatUpdateServiceConfigured(s.Chat.Updates) {
|
||||
s.Chat.Router.Updates = s.Chat.Updates
|
||||
}
|
||||
if s.Chat.Router.Dangerous == nil && s.Chat.Dangerous != nil {
|
||||
@@ -79,6 +80,19 @@ func (s *Server) chatReady(w http.ResponseWriter) (*ChatService, bool) {
|
||||
return s.Chat, true
|
||||
}
|
||||
|
||||
func chatUpdateServiceConfigured(updates ChatUpdateService) bool {
|
||||
if updates == nil {
|
||||
return false
|
||||
}
|
||||
value := reflect.ValueOf(updates)
|
||||
switch value.Kind() {
|
||||
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
|
||||
return !value.IsNil()
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
if !ok {
|
||||
@@ -329,7 +343,7 @@ func (s *Server) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if chat.Updates == nil {
|
||||
if !chatUpdateServiceConfigured(chat.Updates) {
|
||||
http.Error(w, "updates are not configured", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
@@ -350,7 +364,7 @@ func (s *Server) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if chat.Updates == nil {
|
||||
if !chatUpdateServiceConfigured(chat.Updates) {
|
||||
http.Error(w, "updates are not configured", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
@@ -371,7 +385,7 @@ func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if chat.Updates == nil || !chat.Updates.CanInstall() {
|
||||
if !chatUpdateServiceConfigured(chat.Updates) || !chat.Updates.CanInstall() {
|
||||
http.Error(w, "update installation is not configured", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -256,6 +256,20 @@ func TestChatUpdateEndpoints(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatUpdateEndpointRejectsTypedNilService(t *testing.T) {
|
||||
var updates *releaseupdate.Service
|
||||
sessions := gateway.NewSessionStoreMemory("test")
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
|
||||
server := &Server{Chat: &ChatService{Router: router, Sessions: sessions, Updates: updates}}
|
||||
|
||||
res := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(res, httptest.NewRequest(http.MethodGet, "/api/chat/update", nil))
|
||||
if res.Code != http.StatusNotImplemented {
|
||||
t.Fatalf("typed-nil update service status = %d, body = %s", res.Code, res.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatDangerousApprovalEndpoints(t *testing.T) {
|
||||
sessions := gateway.NewSessionStoreMemory("test")
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);padding-right:var(--sp-4);font-weight:500}.nav-item .nav-label{display:none}.nav-item[aria-current=page] .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;baLine truncated
|
||||
:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);padding-right:var(--sp-4);font-weight:500}.nav-item .nav-label{display:none}.nav-item[aria-current=page] .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;baLine truncated
|
||||
Vendored
+70
-5
@@ -6,10 +6,75 @@
|
||||
stroke-width="12" stroke-linecap="round"
|
||||
stroke-dasharray="${c}"
|
||||
stroke-dashoffset="${c*(1-i/100)}"
|
||||
class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function y(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}function b(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),_=e(`h1.hero-title`,C()),v=r(`connecting`,`idle`),y=[],b=new Map;D(),k();let S=h(e=>{y.unshift(e),y.splice(50),O()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,S);function D(){n(t,e(`div.hero`,e(`div`,_,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),O()}function O(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>x(e,b)))}async function k(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);O(),A(e),_.textContent=t?.operator?`${C()}, ${t.operator}`:C(),j(e),M(t),N(e,n),P(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:k},l(`refresh`,{size:15}),`Retry`))}}function A(t){let r=t?.statuses||{},i=(r.parked||0)+(r.waiting_human||0),a=r.running||0;n(p,i>0&&e(`a.btn.btn-attention`,{href:`#/tasks`},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:`#/tasks`},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:k},l(`refresh`,{size:15}),`Refresh`))}function j(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,g({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),g({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),g({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),g({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:E(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function M(t){let r=!t?.steps?.length;if(d.classList.toggle(`dash-top-standalone`,r),r)return n(c);let i=t.steps.filter(e=>!e.done);if(i.length){let r=Math.round((t.steps.length-i.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(F))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`span.setup-pct`,l(`check`,{size:16})))))}function N(e,t){w(u,e,t)}function P(e){T(f,e)}function F(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function x(t,n){let r=S(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function S(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function C(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good eveLine truncated
|
||||
`),i=[],a=null,o=null,s=()=>{i.length&&(n.append(e(`p`,X(i.join(` `)))),i=[])},c=()=>{a&&n.append(a),a=null};for(let t=0;t<r.length;t++){let l=r[t];if(l.startsWith("```")){s(),c(),o?(n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=Z(l),d=t+1<r.length?Z(r[t+1]):null;if(u&&d&&_e(d)&&u.length===d.length){s(),c();let i=[];for(t+=2;t<r.length;t++){let e=Z(r[t]);if(!e||e.length!==u.length){t--;break}i.push(e)}let a=e(`tbody`);for(let t of i)a.append(e(`tr`,...t.map(t=>e(`td`,X(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,X(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,X(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,X((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,X(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),n}function Z(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function _e(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function ve(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?ge(r):e(`div.chat-bubble-text`,r)))}function ye(){let t=e(`div.chat-page`),r=e(`div.chat-session-list`),i=e(`div.chat-transcript`),a=e(`textarea.chat-composer`,{rows:3,placeholder:`Message Archie… (commands like /status and /new work here)`,"aria-label":`Message Archie`}),o=e(`button.btn.btn-primary`,`Send`),s=e(`button.btn`,{disabled:!0},`Stop`),c=e(`span.chat-status`,`Ready`),l=e(`select.chat-select`,{"aria-label":`Personality`}),u=e(`select.chat-select`,{"aria-label":`Provider`,hidden:!0}),d=e(`select.chat-select`,{"aria-label":`Model`}),f=e(`button.btn`,{hidden:!0,onclick:()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,K())}},`Reload Telegram`),p=``,h=[],g=!1,_=null,v=null,y={},b=[],x=[],S=0,C=e(`div.chat-empty-state`,e(`span.chat-empty-mark`,`A`),e(`h2`,`What are we working on?`),e(`p`,`Ask Archie anything, or start with one of these prompts.`),e(`div.chat-prompt-grid`,...[`Summarise active tasks`,`Show running agents`,`Check system status`].map(t=>e(`button.chat-prompt`,{onclick:()=>{a.value=t,a.focus()}},t))));function w(e){C.remove(),i.append(ve(e)),i.scrollTop=i.scrollHeight}function T(){if(r.replaceChildren(),M.hidden=!p,!h.length){r.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let t of h){let n=e(`button.chat-session`,{class:p===t.session_id?`active`:``,onclick:()=>G(t.session_id)},e(`strong`,he(t)),e(`span`,new Date(t.last_active_at).toLocaleString()));r.append(n)}}function E(t){y=t,l.replaceChildren(e(`option`,{value:``},`Personality`));for(let n of t.personas||[])l.append(e(`option`,{value:n},n));l.value=t.active_persona||``;let n=t.providers||[];u.hidden=n.length===0,u.replaceChildren(e(`option`,{value:``},`Provider`));for(let t of n)u.append(e(`option`,{value:t},t));u.value=t.active_provider||n[0]||``,D(u.value),f.hidden=!t.restart_available,A.hidden=!t.dangerous_available,t.dangerous_available&&V()}function D(t){let n=y.models_by_provider||{},r=t&&n[t]?n[t]:y.models||[];d.replaceChildren(e(`option`,{value:``},`Model`));for(let t of r)d.append(e(`option`,{value:t},t));d.value=y.active_model||``}function O(t){let n=t.commands||[];b=n.map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);let r=e(`div.chat-command-list`);n.length||r.append(e(`span`,`Send a message to begin.`));for(let t of n){let n=typeof t==`string`?{command:t,usage:t,description:``}:t;r.append(e(`div.chat-command-item`,e(`code`,n.usage||n.command),e(`span`,n.description||``)))}J.replaceChildren(e(`summary`,`Available commands (${n.length})`),r)}let k=e(`div.chat-update-panel`),A=e(`div.chat-dangerous-panel`,{hidden:!0}),j=e(`div.chat-command-menu`,{hidden:!0,role:`listbox`,"aria-label":`Commands`}),M=e(`details.chat-session-tools`,{hidden:!0});function N(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function P(){j.hidden=!0,x=[],S=0}function F(){let t=N();if(t===null){P();return}if(x=b.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!x.length){P();return}S=Math.min(S,x.length-1),j.replaceChildren(...x.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":n===S,onmousedown:e=>e.preventDefault(),onclick:()=>I(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),j.hidden=!1}function I(e){let t=x[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),P(),a.focus()}function L(t){k.replaceChildren(),v=t?.snapshot||null;let n=t?.available||[];if(!n.length){k.append(e(`span`,t?.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`));return}k.append(e(`div`,e(`strong`,`Update available`),e(`span`,n.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:async()=>{await m.chatUpdateDefer(v),L({snapshot:{deferred:!0},available:[]}),c.textContent=`Update deferred`}},`Defer`),t.can_install?e(`button.btn.btn-primary`,{onclick:async()=>{c.textContent=`Installing…`,await m.chatUpdateInstall(v),c.textContent=`Update started`,R()}},`Install update`):null))}async function R(){try{L(await m.chatUpdate())}catch(t){k.replaceChildren(e(`span`,t.message||`Updates unavailable`))}}function z(t,n,r){return e(`button.btn`,{onclick:async()=>{try{await m.chatDangerousDecision(t,n),c.textContent=n===`deny`?`Action denied`:`Action approved`,aw
Line truncated
|
||||
class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function y(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}function b(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),_=e(`h1.hero-title`,C()),v=r(`connecting`,`idle`),y=[],b=new Map;D(),k();let S=h(e=>{y.unshift(e),y.splice(50),O()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,S);function D(){n(t,e(`div.hero`,e(`div`,_,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),O()}function O(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>x(e,b)))}async function k(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);O(),A(e),_.textContent=t?.operator?`${C()}, ${t.operator}`:C(),j(e),M(t),N(e,n),P(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:k},l(`refresh`,{size:15}),`Retry`))}}function A(t){let r=t?.statuses||{},i=(r.parked||0)+(r.waiting_human||0),a=r.running||0;n(p,i>0&&e(`a.btn.btn-attention`,{href:`#/tasks`},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:`#/tasks`},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:k},l(`refresh`,{size:15}),`Refresh`))}function j(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,g({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),g({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),g({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),g({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:E(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function M(t){let r=!t?.steps?.length;if(d.classList.toggle(`dash-top-standalone`,r),r)return n(c);let i=t.steps.filter(e=>!e.done);if(i.length){let r=Math.round((t.steps.length-i.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(F))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`span.setup-pct`,l(`check`,{size:16})))))}function N(e,t){w(u,e,t)}function P(e){T(f,e)}function F(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function x(t,n){let r=S(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function S(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function C(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good eveLine truncated
|
||||
<div class="chat-page-content">
|
||||
<header class="chat-topbar">
|
||||
<div><span class="chat-kicker">ARCHIE WORKSPACE</span><h1 class="page-title">Chat</h1></div>
|
||||
<div class="chat-topbar-actions">
|
||||
<span class="chat-status" data-chat-ref="status">Ready</span>
|
||||
<button class="btn" data-chat-ref="restart" hidden>Reload Telegram</button>
|
||||
<button class="btn" data-chat-ref="checkUpdates">Check updates</button>
|
||||
<select class="chat-select" data-chat-ref="persona" aria-label="Personality"><option value="">Personality</option></select>
|
||||
<select class="chat-select" data-chat-ref="provider" aria-label="Provider" hidden><option value="">Provider</option></select>
|
||||
<select class="chat-select" data-chat-ref="model" aria-label="Model"><option value="">Model</option></select>
|
||||
</div>
|
||||
</header>
|
||||
<div class="chat-update-panel" data-chat-ref="updatePanel"></div>
|
||||
<div class="chat-dangerous-panel" data-chat-ref="dangerousPanel" hidden></div>
|
||||
<div class="chat-layout">
|
||||
<aside class="chat-sidebar">
|
||||
<div class="chat-sidebar-head">
|
||||
<strong>Conversations</strong>
|
||||
<button class="btn btn-primary" data-chat-ref="newChat" type="button">+ New chat</button>
|
||||
</div>
|
||||
<div class="chat-session-list" data-chat-ref="sessionList"></div>
|
||||
</aside>
|
||||
<section class="chat-workspace">
|
||||
<div class="chat-workspace-head">
|
||||
<span class="chat-workspace-label">PERSONAL ASSISTANT</span>
|
||||
<details class="chat-command-help" data-chat-ref="commandHelp"></details>
|
||||
<details class="chat-session-tools" data-chat-ref="sessionTools">
|
||||
<summary>Session actions</summary>
|
||||
<div class="chat-session-tool-list">
|
||||
<button class="btn" data-chat-action="retry" type="button">Retry</button>
|
||||
<button class="btn" data-chat-action="undo" type="button">Undo</button>
|
||||
<button class="btn" data-chat-action="title" type="button">Rename</button>
|
||||
<button class="btn" data-chat-action="branch" type="button">Branch</button>
|
||||
<button class="btn" data-chat-action="compress" type="button">Preview compression</button>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<div class="chat-transcript" data-chat-ref="transcript">
|
||||
<div class="chat-empty-state" data-chat-ref="emptyState">
|
||||
<span class="chat-empty-mark">A</span>
|
||||
<h2>What are we working on?</h2>
|
||||
<p>Ask Archie anything, or start with one of these prompts.</p>
|
||||
<div class="chat-prompt-grid">
|
||||
<button class="chat-prompt" data-chat-prompt="Summarise active tasks" type="button">Summarise active tasks</button>
|
||||
<button class="chat-prompt" data-chat-prompt="Show running agents" type="button">Show running agents</button>
|
||||
<button class="chat-prompt" data-chat-prompt="Check system status" type="button">Check system status</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chat-compose">
|
||||
<div class="chat-composer-shell">
|
||||
<textarea class="chat-composer" data-chat-ref="composer" rows="3" placeholder="Message Archie… (commands like /status and /new work here)" aria-label="Message Archie"></textarea>
|
||||
<div class="chat-command-menu" data-chat-ref="commandMenu" hidden role="listbox" aria-label="Commands"></div>
|
||||
<div class="chat-compose-actions">
|
||||
<span class="chat-hint">⌘/Ctrl + Enter to send</span>
|
||||
<button class="btn" data-chat-ref="stop" type="button" disabled>Stop</button>
|
||||
<button class="btn btn-primary" data-chat-ref="send" type="button">Send</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;function ye(){let e=document.createElement(`template`);e.innerHTML=ve.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function K(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i<t.length&&n.append(document.createTextNode(t.slice(i))),n}function be(t){let n=e(`div.chat-bubble-text`),r=String(t||``).split(`
|
||||
`),i=[],a=null,o=null,s=()=>{i.length&&(n.append(e(`p`,K(i.join(` `)))),i=[])},c=()=>{a&&n.append(a),a=null};for(let t=0;t<r.length;t++){let l=r[t];if(l.startsWith("```")){s(),c(),o?(n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=q(l),d=t+1<r.length?q(r[t+1]):null;if(u&&d&&xe(d)&&u.length===d.length){s(),c();let i=[];for(t+=2;t<r.length;t++){let e=q(r[t]);if(!e||e.length!==u.length){t--;break}i.push(e)}let a=e(`tbody`);for(let t of i)a.append(e(`tr`,...t.map(t=>e(`td`,K(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,K(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,K(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,K((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,K(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),n}function q(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function xe(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function Se(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Ce(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?be(r):e(`div.chat-bubble-text`,r)))}function J(e,t){let n=be(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}var we=`archie.web.chat.channel`;function Y(){let e=localStorage.getItem(we);return e||(e=crypto.randomUUID(),localStorage.setItem(we,e)),e}function Te({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,Se(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function Ee(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,X(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function X(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function De(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function Oe(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function ke(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function Ae(){let{root:t,refs:n}=ye(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:h,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(Ce(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function N(){_.hidden=!0,k=[],A=0}function P(){let t=M();if(t===null){N();return}if(k=O.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!k.length){N();return}A=Math.min(A,k.length-1),_.replaceChildren(...k.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":n===A,on
Line truncated
|
||||
|
||||
`);a=o.pop()||``;for(let e of o){let t=e.split(`
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(p=n.session_id),n.type===`delta`&&(r.textContent+=n.text),n.type===`done`&&!r.textContent&&(r.textContent=n.text),n.type===`error`)throw Error(n.text)}if(t)break}r.isConnected&&r.replaceWith(ge(r.textContent)),c.textContent=`Ready`,await H(),p&&await G(p)}catch(e){e.name===`AbortError`?(r.textContent=`Turn stopped.`,c.textContent=`Stopped`):(r.textContent=`Unable to complete that turn: ${e.message||e}`,c.textContent=`Error`)}finally{clearTimeout(l),_=null,g=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=K,s.onclick=()=>{let e=p;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),_?.abort()},a.oninput=F,a.onkeydown=e=>{if(!j.hidden&&x.length){if(e.key===`ArrowDown`){e.preventDefault(),S=(S+1)%x.length,F();return}if(e.key===`ArrowUp`){e.preventDefault(),S=(S+x.length-1)%x.length,F();return}if(e.key===`Enter`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),I(S);return}if(e.key===`Escape`){e.preventDefault(),P();return}}e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),K())},l.onchange=async()=>{!p||!l.value||(await m.chatPersona(p,l.value),y.active_personas={...y.active_personas||{},[p]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{D(u.value),u.value&&await q(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await q(`/model ${d.value}`)};async function q(e){try{let t=await m.chatMessage(Y(),e);c.textContent=t.reply||`Model updated`,await H()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}let J=e(`details.chat-command-help`),ee=e(`button.btn`,{onclick:R},`Check updates`),te=e(`div.chat-session-tool-list`,e(`button.btn`,{type:`button`,onclick:()=>U(`/retry`)},`Retry`),e(`button.btn`,{type:`button`,onclick:()=>U(`/undo`)},`Undo`),e(`button.btn`,{type:`button`,onclick:()=>W(`/title`,`Session title`)},`Rename`),e(`button.btn`,{type:`button`,onclick:()=>W(`/branch`,`Branch name (optional)`)},`Branch`),e(`button.btn`,{type:`button`,onclick:()=>U(`/compress --preview`)},`Preview compression`));return M.append(e(`summary`,`Session actions`),te),n(t,e(`div.chat-page-content`,e(`div.chat-topbar`,e(`div`,e(`span.chat-kicker`,`ARCHIE WORKSPACE`),e(`h1.page-title`,`Chat`)),e(`div.chat-topbar-actions`,e(`span.chat-status`,c),f,ee,l,u,d)),k,A,e(`div.chat-layout`,e(`aside.chat-sidebar`,e(`div.chat-sidebar-head`,e(`strong`,`Conversations`),e(`button.btn.btn-primary`,{onclick:()=>{a.value=`/new`,K()}},`+ New chat`)),r),e(`section.chat-workspace`,e(`div.chat-workspace-head`,e(`span.chat-workspace-label`,`PERSONAL ASSISTANT`),J,M),i,e(`div.chat-compose`,e(`div.chat-composer-shell`,a,j,e(`div.chat-compose-actions`,e(`span.chat-hint`,`⌘/Ctrl + Enter to send`),s,o))))))),i.append(C),H().catch(e=>{c.textContent=e.message||`Chat unavailable`}),R(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:b},{path:`/chat`,label:`Chat`,icon:`chat`,view:ye},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:k},{path:`/logs`,label:`Logs`,icon:`logs`,view:ae},{path:`/skills`,label:`Skills`,icon:`skills`,view:A},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:I},{path:`/memory`,label:`Memory`,icon:`memory`,view:de},{path:`/channels`,label:`Channels`,icon:`channels`,view:L},{path:`/settings`,label:`Configuration`,icon:`settings`,view:R}],be=`archie.theme`;function xe(e){document.documentElement.dataset.theme=e,localStorage.setItem(be,e)}function $(){return localStorage.getItem(be)||`dark`}function Se(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{xe($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur())}});return{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,e(`div.topbar-search`,l(`search`,{size:15}),o),e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function Ce(){xe($());let t=e(`main.main`),r=Se(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.spli
Line truncated
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(l+=n.text,r=J(r,l)),n.type===`done`&&!l&&(l=n.text,r=J(r,l)),n.type===`error`)throw Error(n.text)}if(t)break}r.isConnected&&(r=J(r,l)),c.textContent=`Ready`,await R(),S&&await V(S)}catch(e){e.name===`AbortError`?(r=J(r,`Turn stopped.`),c.textContent=`Stopped`):(r=J(r,`Unable to complete that turn: ${e.message||e}`),c.textContent=`Error`)}finally{clearTimeout(u),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=H,s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{X({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Y(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Z=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:b},{path:`/chat`,label:`Chat`,icon:`chat`,view:Ae},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:A},{path:`/logs`,label:`Logs`,icon:`logs`,view:ue},{path:`/skills`,label:`Skills`,icon:`skills`,view:j},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:L},{path:`/memory`,label:`Memory`,icon:`memory`,view:he},{path:`/channels`,label:`Channels`,icon:`channels`,view:R},{path:`/settings`,label:`Configuration`,icon:`settings`,view:z}],je=`archie.theme`;function Q(e){document.documentElement.dataset.theme=e,localStorage.setItem(je,e)}function $(){return localStorage.getItem(je)||`dark`}function Me(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Z.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Q($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Z.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur())}});return{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,e(`div.topbar-search`,l(`search`,{size:15}),o),e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function Ne(){Q($());let t=e(`main.main`),r=Me(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Z.find(e=>e.path===i)||Z[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):Pe(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function Pe(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}Ne();
|
||||
@@ -0,0 +1,51 @@
|
||||
import { el } from "../base/dom.js";
|
||||
import { sessionTitle } from "./chat-render.js";
|
||||
|
||||
export function renderSessions({ sessionList, sessionTools, sessions, currentSession, onSelect }) {
|
||||
sessionList.replaceChildren();
|
||||
sessionTools.hidden = !currentSession;
|
||||
if (!sessions.length) {
|
||||
sessionList.append(el("div.chat-empty", "Your conversations will appear here."));
|
||||
return;
|
||||
}
|
||||
for (const session of sessions) {
|
||||
sessionList.append(el(
|
||||
"button.chat-session",
|
||||
{ class: currentSession === session.session_id ? "active" : "", onclick: () => onSelect(session.session_id) },
|
||||
el("strong", sessionTitle(session)),
|
||||
el("span", new Date(session.last_active_at).toLocaleString()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
export function renderSelectors(refs, data, onDangerous) {
|
||||
refs.persona.replaceChildren(el("option", { value: "" }, "Personality"));
|
||||
for (const name of data.personas || []) refs.persona.append(el("option", { value: name }, name));
|
||||
refs.persona.value = data.active_persona || "";
|
||||
const providers = data.providers || [];
|
||||
refs.provider.hidden = providers.length === 0;
|
||||
refs.provider.replaceChildren(el("option", { value: "" }, "Provider"));
|
||||
for (const name of providers) refs.provider.append(el("option", { value: name }, name));
|
||||
refs.provider.value = data.active_provider || providers[0] || "";
|
||||
renderModels(refs, data, refs.provider.value);
|
||||
refs.restart.hidden = !data.restart_available;
|
||||
refs.dangerousPanel.hidden = !data.dangerous_available;
|
||||
if (data.dangerous_available) onDangerous();
|
||||
}
|
||||
|
||||
export function renderModels(refs, data, providerName) {
|
||||
const grouped = data.models_by_provider || {};
|
||||
const names = providerName && grouped[providerName] ? grouped[providerName] : data.models || [];
|
||||
refs.model.replaceChildren(el("option", { value: "" }, "Model"));
|
||||
for (const name of names) refs.model.append(el("option", { value: name }, name));
|
||||
refs.model.value = data.active_model || "";
|
||||
}
|
||||
|
||||
export function renderCommands(commandHelp, commands) {
|
||||
const specs = (commands || []).map((item) => typeof item === "string" ? { command: item, usage: item, description: "" } : item);
|
||||
const list = el("div.chat-command-list");
|
||||
if (!specs.length) list.append(el("span", "Send a message to begin."));
|
||||
for (const spec of specs) list.append(el("div.chat-command-item", el("code", spec.usage || spec.command), el("span", spec.description || "")));
|
||||
commandHelp.replaceChildren(el("summary", `Available commands (${specs.length})`), list);
|
||||
return specs;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { el } from "../base/dom.js";
|
||||
|
||||
export function renderUpdate(panel, data, { onDefer, onInstall }) {
|
||||
panel.replaceChildren();
|
||||
const snapshot = data?.snapshot || null;
|
||||
const available = data?.available || [];
|
||||
if (!available.length) {
|
||||
panel.append(el("span", snapshot?.deferred ? "Update deferred." : "Archie is up to date."));
|
||||
return;
|
||||
}
|
||||
panel.append(
|
||||
el("div", el("strong", "Update available"), el("span", available.map((component) => `${component.Label || component.label}: ${component.Available || component.available}`).join(" · "))),
|
||||
el("div.chat-update-actions",
|
||||
el("button.btn", { onclick: onDefer }, "Defer"),
|
||||
data.can_install ? el("button.btn.btn-primary", { onclick: onInstall }, "Install update") : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function renderDangerous(panel, data, { onRequest, onDecision }) {
|
||||
panel.replaceChildren();
|
||||
const checkpoints = data?.checkpoints || [];
|
||||
const pending = data?.pending || [];
|
||||
const checkpoint = el("select.chat-select", { "aria-label": "Checkpoint" },
|
||||
el("option", { value: "" }, "Select checkpoint"),
|
||||
...checkpoints.map((item) => el("option", { value: item.Number ?? item.number }, `${item.Number ?? item.number} — ${item.Label ?? item.label ?? "checkpoint"}`)),
|
||||
);
|
||||
const stopSpec = el("input.chat-dangerous-input", { placeholder: "Process name or id", "aria-label": "Process name or id" });
|
||||
const request = (kind, spec) => () => onRequest(kind, String(spec.value || spec).trim());
|
||||
const decisionButton = (id, decision, label) => el("button.btn", { onclick: () => onDecision(id, decision) }, label);
|
||||
const pendingRows = pending.length ? pending.map((action) => el("div.chat-dangerous-pending",
|
||||
el("span", action.description),
|
||||
el("div.chat-update-actions",
|
||||
decisionButton(action.id, "approve", "Approve"),
|
||||
decisionButton(action.id, "permanent", "Approve for 24h"),
|
||||
decisionButton(action.id, "deny", "Deny"),
|
||||
),
|
||||
)) : [el("span.chat-hint", "No pending dangerous actions.")];
|
||||
panel.append(
|
||||
el("div.chat-dangerous-head", el("strong", "Dangerous actions"), el("span.chat-hint", "Every action requires approval.")),
|
||||
el("div.chat-dangerous-controls",
|
||||
el("div", checkpoint, el("button.btn", { onclick: request("rollback", checkpoint) }, "Request rollback")),
|
||||
el("div", stopSpec, el("button.btn", { onclick: request("stop", stopSpec) }, "Request stop")),
|
||||
),
|
||||
el("div.chat-dangerous-pending-list", ...pendingRows),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { el } from "../base/dom.js";
|
||||
import { renderMarkdown } from "./markdown.js";
|
||||
|
||||
export function sessionTitle(session) {
|
||||
return session.title || session.branch_name || `Conversation ${session.session_id.slice(0, 8)}`;
|
||||
}
|
||||
|
||||
export function chatBubble(message) {
|
||||
const from = message.from ?? message.From ?? "";
|
||||
const text = message.text ?? message.Text ?? "";
|
||||
const isAssistant = from !== "web";
|
||||
return el(
|
||||
`div.chat-bubble-row.${isAssistant ? "assistant" : "user"}`,
|
||||
el(
|
||||
"div.chat-bubble",
|
||||
el("div.chat-bubble-meta", isAssistant ? "Archie" : "You"),
|
||||
isAssistant ? renderMarkdown(text) : el("div.chat-bubble-text", text),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
const CHANNEL_KEY = "archie.web.chat.channel";
|
||||
|
||||
export function channelID() {
|
||||
let id = localStorage.getItem(CHANNEL_KEY);
|
||||
if (!id) {
|
||||
id = crypto.randomUUID();
|
||||
localStorage.setItem(CHANNEL_KEY, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { renderMarkdown } from "./markdown.js";
|
||||
|
||||
export function updateStreamingReply(current, text) {
|
||||
const next = renderMarkdown(text);
|
||||
if (typeof current?.replaceWith === "function") current.replaceWith(next);
|
||||
else if (current?.parentNode) current.parentNode.replaceChild(next, current);
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import template from "./chat.html?raw";
|
||||
|
||||
export function createChatView() {
|
||||
const holder = document.createElement("template");
|
||||
holder.innerHTML = template.trim();
|
||||
const root = holder.content.firstElementChild;
|
||||
const refs = {};
|
||||
for (const node of root.querySelectorAll("[data-chat-ref]")) refs[node.dataset.chatRef] = node;
|
||||
return { root, refs };
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<div class="chat-page">
|
||||
<div class="chat-page-content">
|
||||
<header class="chat-topbar">
|
||||
<div><span class="chat-kicker">ARCHIE WORKSPACE</span><h1 class="page-title">Chat</h1></div>
|
||||
<div class="chat-topbar-actions">
|
||||
<span class="chat-status" data-chat-ref="status">Ready</span>
|
||||
<button class="btn" data-chat-ref="restart" hidden>Reload Telegram</button>
|
||||
<button class="btn" data-chat-ref="checkUpdates">Check updates</button>
|
||||
<select class="chat-select" data-chat-ref="persona" aria-label="Personality"><option value="">Personality</option></select>
|
||||
<select class="chat-select" data-chat-ref="provider" aria-label="Provider" hidden><option value="">Provider</option></select>
|
||||
<select class="chat-select" data-chat-ref="model" aria-label="Model"><option value="">Model</option></select>
|
||||
</div>
|
||||
</header>
|
||||
<div class="chat-update-panel" data-chat-ref="updatePanel"></div>
|
||||
<div class="chat-dangerous-panel" data-chat-ref="dangerousPanel" hidden></div>
|
||||
<div class="chat-layout">
|
||||
<aside class="chat-sidebar">
|
||||
<div class="chat-sidebar-head">
|
||||
<strong>Conversations</strong>
|
||||
<button class="btn btn-primary" data-chat-ref="newChat" type="button">+ New chat</button>
|
||||
</div>
|
||||
<div class="chat-session-list" data-chat-ref="sessionList"></div>
|
||||
</aside>
|
||||
<section class="chat-workspace">
|
||||
<div class="chat-workspace-head">
|
||||
<span class="chat-workspace-label">PERSONAL ASSISTANT</span>
|
||||
<details class="chat-command-help" data-chat-ref="commandHelp"></details>
|
||||
<details class="chat-session-tools" data-chat-ref="sessionTools">
|
||||
<summary>Session actions</summary>
|
||||
<div class="chat-session-tool-list">
|
||||
<button class="btn" data-chat-action="retry" type="button">Retry</button>
|
||||
<button class="btn" data-chat-action="undo" type="button">Undo</button>
|
||||
<button class="btn" data-chat-action="title" type="button">Rename</button>
|
||||
<button class="btn" data-chat-action="branch" type="button">Branch</button>
|
||||
<button class="btn" data-chat-action="compress" type="button">Preview compression</button>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<div class="chat-transcript" data-chat-ref="transcript">
|
||||
<div class="chat-empty-state" data-chat-ref="emptyState">
|
||||
<span class="chat-empty-mark">A</span>
|
||||
<h2>What are we working on?</h2>
|
||||
<p>Ask Archie anything, or start with one of these prompts.</p>
|
||||
<div class="chat-prompt-grid">
|
||||
<button class="chat-prompt" data-chat-prompt="Summarise active tasks" type="button">Summarise active tasks</button>
|
||||
<button class="chat-prompt" data-chat-prompt="Show running agents" type="button">Show running agents</button>
|
||||
<button class="chat-prompt" data-chat-prompt="Check system status" type="button">Check system status</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chat-compose">
|
||||
<div class="chat-composer-shell">
|
||||
<textarea class="chat-composer" data-chat-ref="composer" rows="3" placeholder="Message Archie… (commands like /status and /new work here)" aria-label="Message Archie"></textarea>
|
||||
<div class="chat-command-menu" data-chat-ref="commandMenu" hidden role="listbox" aria-label="Commands"></div>
|
||||
<div class="chat-compose-actions">
|
||||
<span class="chat-hint">⌘/Ctrl + Enter to send</span>
|
||||
<button class="btn" data-chat-ref="stop" type="button" disabled>Stop</button>
|
||||
<button class="btn btn-primary" data-chat-ref="send" type="button">Send</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+86
-354
@@ -1,183 +1,19 @@
|
||||
import { el, mount } from "../base/dom.js";
|
||||
import { el } from "../base/dom.js";
|
||||
import { api } from "../base/api.js";
|
||||
import { createChatView } from "./chat-view.js";
|
||||
import { chatBubble } from "./chat-render.js";
|
||||
import { updateStreamingReply } from "./chat-stream.js";
|
||||
import { channelID } from "./chat-state.js";
|
||||
import { renderCommands, renderModels, renderSelectors, renderSessions } from "./chat-catalog.js";
|
||||
import { renderDangerous, renderUpdate } from "./chat-panels.js";
|
||||
|
||||
import "./chat.css";
|
||||
|
||||
const CHANNEL_KEY = "archie.web.chat.channel";
|
||||
|
||||
function channelID() {
|
||||
let id = localStorage.getItem(CHANNEL_KEY);
|
||||
if (!id) {
|
||||
id = crypto.randomUUID();
|
||||
localStorage.setItem(CHANNEL_KEY, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
function sessionTitle(session) {
|
||||
return session.title || session.branch_name || `Conversation ${session.session_id.slice(0, 8)}`;
|
||||
}
|
||||
|
||||
function inlineMarkdown(text) {
|
||||
const fragment = document.createDocumentFragment();
|
||||
const pattern = /(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g;
|
||||
let cursor = 0;
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
if (match.index > cursor) fragment.append(document.createTextNode(text.slice(cursor, match.index)));
|
||||
const value = match[0];
|
||||
if (value.startsWith("~~")) fragment.append(el("del", value.slice(2, -2)));
|
||||
else if (value.startsWith("**") || value.startsWith("__")) fragment.append(el("strong", value.slice(2, -2)));
|
||||
else if (value.startsWith("`")) fragment.append(el("code", value.slice(1, -1)));
|
||||
else if (value.startsWith("[")) {
|
||||
const link = value.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);
|
||||
fragment.append(el("a", { href: link[2], target: "_blank", rel: "noreferrer" }, link[1]));
|
||||
} else fragment.append(el("em", value.slice(1, -1)));
|
||||
cursor = match.index + value.length;
|
||||
}
|
||||
if (cursor < text.length) fragment.append(document.createTextNode(text.slice(cursor)));
|
||||
return fragment;
|
||||
}
|
||||
|
||||
function renderMarkdown(text) {
|
||||
const root = el("div.chat-bubble-text");
|
||||
const lines = String(text || "").split("\n");
|
||||
let paragraph = [];
|
||||
let list = null;
|
||||
let code = null;
|
||||
const flushParagraph = () => {
|
||||
if (paragraph.length) {
|
||||
root.append(el("p", inlineMarkdown(paragraph.join(" "))));
|
||||
paragraph = [];
|
||||
}
|
||||
};
|
||||
const flushList = () => {
|
||||
if (list) root.append(list);
|
||||
list = null;
|
||||
};
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
const line = lines[index];
|
||||
if (line.startsWith("```")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) {
|
||||
root.append(el("pre", el("code", code.join("\n"))));
|
||||
code = null;
|
||||
} else code = [];
|
||||
continue;
|
||||
}
|
||||
if (code) {
|
||||
code.push(line);
|
||||
continue;
|
||||
}
|
||||
const headerCells = tableCells(line);
|
||||
const separatorCells = index + 1 < lines.length ? tableCells(lines[index + 1]) : null;
|
||||
if (headerCells && separatorCells && isTableSeparator(separatorCells) && headerCells.length === separatorCells.length) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
const rows = [];
|
||||
for (index += 2; index < lines.length; index++) {
|
||||
const cells = tableCells(lines[index]);
|
||||
if (!cells || cells.length !== headerCells.length) {
|
||||
index--;
|
||||
break;
|
||||
}
|
||||
rows.push(cells);
|
||||
}
|
||||
const body = el("tbody");
|
||||
for (const row of rows) {
|
||||
body.append(el("tr", ...row.map((cell) => el("td", inlineMarkdown(cell)))));
|
||||
}
|
||||
root.append(el(
|
||||
"table",
|
||||
el("thead", el("tr", ...headerCells.map((cell) => el("th", inlineMarkdown(cell))))),
|
||||
body,
|
||||
));
|
||||
continue;
|
||||
}
|
||||
if (!line.trim()) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
continue;
|
||||
}
|
||||
const heading = line.match(/^(#{1,3})\s+(.+)$/);
|
||||
if (heading) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
root.append(el(`h${heading[1].length}`, inlineMarkdown(heading[2])));
|
||||
continue;
|
||||
}
|
||||
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
|
||||
const ordered = line.match(/^\s*\d+[.)]\s+(.+)$/);
|
||||
if (bullet || ordered) {
|
||||
flushParagraph();
|
||||
const tag = ordered ? "ol" : "ul";
|
||||
if (!list || list.tagName.toLowerCase() !== tag) {
|
||||
flushList();
|
||||
list = el(tag);
|
||||
}
|
||||
list.append(el("li", inlineMarkdown((bullet || ordered)[1])));
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith(">")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
root.append(el("blockquote", inlineMarkdown(line.replace(/^>\s?/, ""))));
|
||||
continue;
|
||||
}
|
||||
paragraph.push(line);
|
||||
}
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) root.append(el("pre", el("code", code.join("\n"))));
|
||||
return root;
|
||||
}
|
||||
|
||||
function tableCells(line) {
|
||||
const value = String(line || "").trim();
|
||||
if (!value.includes("|")) return null;
|
||||
const unwrapped = value.replace(/^\|/, "").replace(/\|$/, "");
|
||||
const cells = unwrapped.split("|").map((cell) => cell.trim());
|
||||
return cells.length > 1 && cells.every((cell) => cell !== "") ? cells : null;
|
||||
}
|
||||
|
||||
function isTableSeparator(cells) {
|
||||
return cells.every((cell) => /^:?-{3,}:?$/.test(cell));
|
||||
}
|
||||
|
||||
function chatBubble(message) {
|
||||
const from = message.from ?? message.From ?? "";
|
||||
const text = message.text ?? message.Text ?? "";
|
||||
const isAssistant = from !== "web";
|
||||
return el(
|
||||
`div.chat-bubble-row.${isAssistant ? "assistant" : "user"}`,
|
||||
el(
|
||||
"div.chat-bubble",
|
||||
el("div.chat-bubble-meta", isAssistant ? "Archie" : "You"),
|
||||
isAssistant ? renderMarkdown(text) : el("div.chat-bubble-text", text),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function chatPage() {
|
||||
const root = el("div.chat-page");
|
||||
const sessionList = el("div.chat-session-list");
|
||||
const transcript = el("div.chat-transcript");
|
||||
const composer = el("textarea.chat-composer", {
|
||||
rows: 3,
|
||||
placeholder: "Message Archie… (commands like /status and /new work here)",
|
||||
"aria-label": "Message Archie",
|
||||
});
|
||||
const send = el("button.btn.btn-primary", "Send");
|
||||
const stop = el("button.btn", { disabled: true }, "Stop");
|
||||
const status = el("span.chat-status", "Ready");
|
||||
const persona = el("select.chat-select", { "aria-label": "Personality" });
|
||||
const provider = el("select.chat-select", { "aria-label": "Provider", hidden: true });
|
||||
const model = el("select.chat-select", { "aria-label": "Model" });
|
||||
const restart = el("button.btn", { hidden: true, onclick: () => {
|
||||
if (!window.confirm("Reload the Telegram chat adapter?")) return;
|
||||
composer.value = "/restart";
|
||||
sendMessage();
|
||||
} }, "Reload Telegram");
|
||||
const { root, refs } = createChatView();
|
||||
const { sessionList, transcript, composer, send, stop, status, persona, provider, model,
|
||||
restart, emptyState, updatePanel, dangerousPanel, commandMenu, sessionTools, commandHelp,
|
||||
checkUpdates, newChat } = refs;
|
||||
let currentSession = "";
|
||||
let sessions = [];
|
||||
let sending = false;
|
||||
@@ -188,16 +24,15 @@ export function chatPage() {
|
||||
let commandMatches = [];
|
||||
let commandSelection = 0;
|
||||
|
||||
const emptyState = el(
|
||||
"div.chat-empty-state",
|
||||
el("span.chat-empty-mark", "A"),
|
||||
el("h2", "What are we working on?"),
|
||||
el("p", "Ask Archie anything, or start with one of these prompts."),
|
||||
el("div.chat-prompt-grid",
|
||||
...["Summarise active tasks", "Show running agents", "Check system status"].map((prompt) =>
|
||||
el("button.chat-prompt", { onclick: () => { composer.value = prompt; composer.focus(); } }, prompt)),
|
||||
),
|
||||
);
|
||||
restart.onclick = () => {
|
||||
if (!window.confirm("Reload the Telegram chat adapter?")) return;
|
||||
composer.value = "/restart";
|
||||
sendMessage();
|
||||
};
|
||||
newChat.onclick = () => { composer.value = "/new"; sendMessage(); };
|
||||
for (const prompt of root.querySelectorAll("[data-chat-prompt]")) {
|
||||
prompt.onclick = () => { composer.value = prompt.dataset.chatPrompt; composer.focus(); };
|
||||
}
|
||||
|
||||
function appendMessage(message) {
|
||||
emptyState.remove();
|
||||
@@ -205,65 +40,6 @@ export function chatPage() {
|
||||
transcript.scrollTop = transcript.scrollHeight;
|
||||
}
|
||||
|
||||
function renderSessions() {
|
||||
sessionList.replaceChildren();
|
||||
sessionTools.hidden = !currentSession;
|
||||
if (!sessions.length) {
|
||||
sessionList.append(el("div.chat-empty", "Your conversations will appear here."));
|
||||
return;
|
||||
}
|
||||
for (const session of sessions) {
|
||||
const item = el(
|
||||
"button.chat-session",
|
||||
{ class: currentSession === session.session_id ? "active" : "", onclick: () => selectSession(session.session_id) },
|
||||
el("strong", sessionTitle(session)),
|
||||
el("span", new Date(session.last_active_at).toLocaleString()),
|
||||
);
|
||||
sessionList.append(item);
|
||||
}
|
||||
}
|
||||
|
||||
function renderSelectors(data) {
|
||||
selectorData = data;
|
||||
persona.replaceChildren(el("option", { value: "" }, "Personality"));
|
||||
for (const name of data.personas || []) persona.append(el("option", { value: name }, name));
|
||||
persona.value = data.active_persona || "";
|
||||
const providers = data.providers || [];
|
||||
provider.hidden = providers.length === 0;
|
||||
provider.replaceChildren(el("option", { value: "" }, "Provider"));
|
||||
for (const name of providers) provider.append(el("option", { value: name }, name));
|
||||
provider.value = data.active_provider || providers[0] || "";
|
||||
renderModelsForProvider(provider.value);
|
||||
restart.hidden = !data.restart_available;
|
||||
dangerousPanel.hidden = !data.dangerous_available;
|
||||
if (data.dangerous_available) refreshDangerous();
|
||||
}
|
||||
|
||||
function renderModelsForProvider(providerName) {
|
||||
const grouped = selectorData.models_by_provider || {};
|
||||
const names = providerName && grouped[providerName] ? grouped[providerName] : selectorData.models || [];
|
||||
model.replaceChildren(el("option", { value: "" }, "Model"));
|
||||
for (const name of names) model.append(el("option", { value: name }, name));
|
||||
model.value = selectorData.active_model || "";
|
||||
}
|
||||
|
||||
function renderCommands(data) {
|
||||
const commands = data.commands || [];
|
||||
commandSpecs = commands.map((item) => typeof item === "string" ? { command: item, usage: item, description: "" } : item);
|
||||
const list = el("div.chat-command-list");
|
||||
if (!commands.length) list.append(el("span", "Send a message to begin."));
|
||||
for (const item of commands) {
|
||||
const spec = typeof item === "string" ? { command: item, usage: item, description: "" } : item;
|
||||
list.append(el("div.chat-command-item", el("code", spec.usage || spec.command), el("span", spec.description || "")));
|
||||
}
|
||||
commandHelp.replaceChildren(el("summary", `Available commands (${commands.length})`), list);
|
||||
}
|
||||
|
||||
const updatePanel = el("div.chat-update-panel");
|
||||
const dangerousPanel = el("div.chat-dangerous-panel", { hidden: true });
|
||||
const commandMenu = el("div.chat-command-menu", { hidden: true, role: "listbox", "aria-label": "Commands" });
|
||||
const sessionTools = el("details.chat-session-tools", { hidden: true });
|
||||
|
||||
function commandQuery() {
|
||||
const before = composer.value.slice(0, composer.selectionStart);
|
||||
const match = before.match(/(?:^|\s)\/([^\s]*)$/);
|
||||
@@ -320,79 +96,51 @@ export function chatPage() {
|
||||
composer.focus();
|
||||
}
|
||||
|
||||
function renderUpdate(data) {
|
||||
updatePanel.replaceChildren();
|
||||
updateSnapshot = data?.snapshot || null;
|
||||
const available = data?.available || [];
|
||||
if (!available.length) {
|
||||
updatePanel.append(el("span", data?.snapshot?.deferred ? "Update deferred." : "Archie is up to date."));
|
||||
return;
|
||||
}
|
||||
updatePanel.append(
|
||||
el("div", el("strong", "Update available"), el("span", available.map((component) => `${component.Label || component.label}: ${component.Available || component.available}`).join(" · "))),
|
||||
el("div.chat-update-actions",
|
||||
el("button.btn", { onclick: async () => { await api.chatUpdateDefer(updateSnapshot); renderUpdate({ snapshot: { deferred: true }, available: [] }); status.textContent = "Update deferred"; } }, "Defer"),
|
||||
data.can_install ? el("button.btn.btn-primary", { onclick: async () => { status.textContent = "Installing…"; await api.chatUpdateInstall(updateSnapshot); status.textContent = "Update started"; refreshUpdate(); } }, "Install update") : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function refreshUpdate() {
|
||||
try {
|
||||
renderUpdate(await api.chatUpdate());
|
||||
const data = await api.chatUpdate();
|
||||
updateSnapshot = data?.snapshot || null;
|
||||
renderUpdate(updatePanel, data, {
|
||||
onDefer: async () => {
|
||||
await api.chatUpdateDefer(updateSnapshot);
|
||||
renderUpdate(updatePanel, { snapshot: { deferred: true }, available: [] }, { onDefer: () => {}, onInstall: () => {} });
|
||||
status.textContent = "Update deferred";
|
||||
},
|
||||
onInstall: async () => {
|
||||
status.textContent = "Installing…";
|
||||
await api.chatUpdateInstall(updateSnapshot);
|
||||
status.textContent = "Update started";
|
||||
refreshUpdate();
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
updatePanel.replaceChildren(el("span", err.message || "Updates unavailable"));
|
||||
}
|
||||
}
|
||||
|
||||
function dangerousActionButton(id, decision, label) {
|
||||
return el("button.btn", { onclick: async () => {
|
||||
try {
|
||||
await api.chatDangerousDecision(id, decision);
|
||||
status.textContent = decision === "deny" ? "Action denied" : "Action approved";
|
||||
await refreshDangerous();
|
||||
} catch (err) {
|
||||
status.textContent = err.message || "Approval failed";
|
||||
}
|
||||
} }, label);
|
||||
}
|
||||
|
||||
function renderDangerous(data) {
|
||||
dangerousPanel.replaceChildren();
|
||||
const checkpoints = data?.checkpoints || [];
|
||||
const pending = data?.pending || [];
|
||||
const checkpoint = el("select.chat-select", { "aria-label": "Checkpoint" },
|
||||
el("option", { value: "" }, "Select checkpoint"),
|
||||
...checkpoints.map((item) => el("option", { value: item.Number ?? item.number }, `${item.Number ?? item.number} — ${item.Label ?? item.label ?? "checkpoint"}`)),
|
||||
);
|
||||
const stopSpec = el("input.chat-dangerous-input", { placeholder: "Process name or id", "aria-label": "Process name or id" });
|
||||
const request = (kind, spec) => async () => {
|
||||
if (!String(spec.value || spec).trim()) return;
|
||||
try {
|
||||
await api.chatDangerousRequest(kind, String(spec.value || spec).trim());
|
||||
status.textContent = "Approval requested";
|
||||
await refreshDangerous();
|
||||
} catch (err) {
|
||||
status.textContent = err.message || "Could not request action";
|
||||
}
|
||||
};
|
||||
const pendingRows = pending.length ? pending.map((action) => el("div.chat-dangerous-pending",
|
||||
el("span", action.description),
|
||||
el("div.chat-update-actions", dangerousActionButton(action.id, "approve", "Approve"), dangerousActionButton(action.id, "permanent", "Approve for 24h"), dangerousActionButton(action.id, "deny", "Deny")),
|
||||
)) : [el("span.chat-hint", "No pending dangerous actions.")];
|
||||
dangerousPanel.append(
|
||||
el("div.chat-dangerous-head", el("strong", "Dangerous actions"), el("span.chat-hint", "Every action requires approval.")),
|
||||
el("div.chat-dangerous-controls",
|
||||
el("div", checkpoint, el("button.btn", { onclick: request("rollback", checkpoint) }, "Request rollback")),
|
||||
el("div", stopSpec, el("button.btn", { onclick: request("stop", stopSpec) }, "Request stop")),
|
||||
),
|
||||
el("div.chat-dangerous-pending-list", ...pendingRows),
|
||||
);
|
||||
}
|
||||
|
||||
async function refreshDangerous() {
|
||||
try {
|
||||
renderDangerous(await api.chatDangerous());
|
||||
renderDangerous(dangerousPanel, await api.chatDangerous(), {
|
||||
onRequest: async (kind, spec) => {
|
||||
if (!spec) return;
|
||||
try {
|
||||
await api.chatDangerousRequest(kind, spec);
|
||||
status.textContent = "Approval requested";
|
||||
await refreshDangerous();
|
||||
} catch (err) {
|
||||
status.textContent = err.message || "Could not request action";
|
||||
}
|
||||
},
|
||||
onDecision: async (id, decision) => {
|
||||
try {
|
||||
await api.chatDangerousDecision(id, decision);
|
||||
status.textContent = decision === "deny" ? "Action denied" : "Action approved";
|
||||
await refreshDangerous();
|
||||
} catch (err) {
|
||||
status.textContent = err.message || "Approval failed";
|
||||
}
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
dangerousPanel.replaceChildren(el("span.chat-hint", err.message || "Dangerous actions unavailable"));
|
||||
}
|
||||
@@ -401,9 +149,10 @@ export function chatPage() {
|
||||
async function refreshSessions() {
|
||||
const data = await api.chatSessions();
|
||||
sessions = data.sessions || [];
|
||||
renderSelectors(data);
|
||||
renderCommands(data);
|
||||
renderSessions();
|
||||
selectorData = data;
|
||||
renderSelectors({ persona, provider, model, restart, dangerousPanel }, data, refreshDangerous);
|
||||
commandSpecs = renderCommands(commandHelp, data.commands);
|
||||
renderSessions({ sessionList, sessionTools, sessions, currentSession, onSelect: selectSession });
|
||||
if (!currentSession && sessions[0]) await selectSession(sessions[0].session_id);
|
||||
}
|
||||
|
||||
@@ -429,7 +178,7 @@ export function chatPage() {
|
||||
|
||||
async function selectSession(id) {
|
||||
currentSession = id;
|
||||
renderSessions();
|
||||
renderSessions({ sessionList, sessionTools, sessions, currentSession, onSelect: selectSession });
|
||||
transcript.replaceChildren();
|
||||
await api.chatMessage(channelID(), `/resume ${id}`);
|
||||
persona.value = selectorData.active_personas?.[id] || selectorData.active_persona || "";
|
||||
@@ -451,7 +200,8 @@ export function chatPage() {
|
||||
composer.value = "";
|
||||
const replyBubble = el("div.chat-bubble-row.assistant", el("div.chat-bubble", el("div.chat-bubble-meta", "Archie"), el("div.chat-bubble-text")));
|
||||
transcript.append(replyBubble);
|
||||
const replyText = replyBubble.querySelector(".chat-bubble-text");
|
||||
let replyText = replyBubble.querySelector(".chat-bubble-text");
|
||||
let streamedText = "";
|
||||
let timeout;
|
||||
try {
|
||||
activeController = new AbortController();
|
||||
@@ -476,22 +226,28 @@ export function chatPage() {
|
||||
if (!line) continue;
|
||||
const event = JSON.parse(line.slice(6));
|
||||
if (event.session_id) currentSession = event.session_id;
|
||||
if (event.type === "delta") replyText.textContent += event.text;
|
||||
if (event.type === "done" && !replyText.textContent) replyText.textContent = event.text;
|
||||
if (event.type === "delta") {
|
||||
streamedText += event.text;
|
||||
replyText = updateStreamingReply(replyText, streamedText);
|
||||
}
|
||||
if (event.type === "done" && !streamedText) {
|
||||
streamedText = event.text;
|
||||
replyText = updateStreamingReply(replyText, streamedText);
|
||||
}
|
||||
if (event.type === "error") throw new Error(event.text);
|
||||
}
|
||||
if (done) break;
|
||||
}
|
||||
if (replyText.isConnected) replyText.replaceWith(renderMarkdown(replyText.textContent));
|
||||
if (replyText.isConnected) replyText = updateStreamingReply(replyText, streamedText);
|
||||
status.textContent = "Ready";
|
||||
await refreshSessions();
|
||||
if (currentSession) await selectSession(currentSession);
|
||||
} catch (err) {
|
||||
if (err.name === "AbortError") {
|
||||
replyText.textContent = "Turn stopped.";
|
||||
replyText = updateStreamingReply(replyText, "Turn stopped.");
|
||||
status.textContent = "Stopped";
|
||||
} else {
|
||||
replyText.textContent = `Unable to complete that turn: ${err.message || err}`;
|
||||
replyText = updateStreamingReply(replyText, `Unable to complete that turn: ${err.message || err}`);
|
||||
status.textContent = "Error";
|
||||
}
|
||||
} finally {
|
||||
@@ -550,7 +306,7 @@ export function chatPage() {
|
||||
status.textContent = `Personality: ${persona.value}`;
|
||||
};
|
||||
provider.onchange = async () => {
|
||||
renderModelsForProvider(provider.value);
|
||||
renderModels({ model }, selectorData, provider.value);
|
||||
if (!provider.value) return;
|
||||
await applyModelCommand(`/model --provider ${provider.value}`);
|
||||
};
|
||||
@@ -567,41 +323,17 @@ export function chatPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const commandHelp = el("details.chat-command-help");
|
||||
const checkUpdates = el("button.btn", { onclick: refreshUpdate }, "Check updates");
|
||||
const sessionActions = el(
|
||||
"div.chat-session-tool-list",
|
||||
el("button.btn", { type: "button", onclick: () => runSessionCommand("/retry") }, "Retry"),
|
||||
el("button.btn", { type: "button", onclick: () => runSessionCommand("/undo") }, "Undo"),
|
||||
el("button.btn", { type: "button", onclick: () => promptSessionCommand("/title", "Session title") }, "Rename"),
|
||||
el("button.btn", { type: "button", onclick: () => promptSessionCommand("/branch", "Branch name (optional)") }, "Branch"),
|
||||
el("button.btn", { type: "button", onclick: () => runSessionCommand("/compress --preview") }, "Preview compression"),
|
||||
);
|
||||
sessionTools.append(el("summary", "Session actions"), sessionActions);
|
||||
const chatTopbar = el(
|
||||
"div.chat-topbar",
|
||||
el("div", el("span.chat-kicker", "ARCHIE WORKSPACE"), el("h1.page-title", "Chat")),
|
||||
el("div.chat-topbar-actions", el("span.chat-status", status), restart, checkUpdates, persona, provider, model),
|
||||
);
|
||||
const chatLayout = el(
|
||||
"div.chat-layout",
|
||||
el("aside.chat-sidebar", el("div.chat-sidebar-head", el("strong", "Conversations"), el("button.btn.btn-primary", { onclick: () => { composer.value = "/new"; sendMessage(); } }, "+ New chat")), sessionList),
|
||||
el(
|
||||
"section.chat-workspace",
|
||||
el("div.chat-workspace-head", el("span.chat-workspace-label", "PERSONAL ASSISTANT"), commandHelp, sessionTools),
|
||||
transcript,
|
||||
el("div.chat-compose", el("div.chat-composer-shell", composer, commandMenu, el("div.chat-compose-actions", el("span.chat-hint", "⌘/Ctrl + Enter to send"), stop, send))),
|
||||
),
|
||||
);
|
||||
mount(root, el(
|
||||
"div.chat-page-content",
|
||||
chatTopbar,
|
||||
updatePanel,
|
||||
dangerousPanel,
|
||||
chatLayout,
|
||||
));
|
||||
|
||||
transcript.append(emptyState);
|
||||
checkUpdates.onclick = refreshUpdate;
|
||||
const actionHandlers = {
|
||||
retry: () => runSessionCommand("/retry"),
|
||||
undo: () => runSessionCommand("/undo"),
|
||||
title: () => promptSessionCommand("/title", "Session title"),
|
||||
branch: () => promptSessionCommand("/branch", "Branch name (optional)"),
|
||||
compress: () => runSessionCommand("/compress --preview"),
|
||||
};
|
||||
for (const button of root.querySelectorAll("[data-chat-action]")) {
|
||||
button.onclick = actionHandlers[button.dataset.chatAction];
|
||||
}
|
||||
|
||||
refreshSessions().catch((err) => { status.textContent = err.message || "Chat unavailable"; });
|
||||
refreshUpdate();
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { el } from "../base/dom.js";
|
||||
|
||||
function inlineMarkdown(text) {
|
||||
const fragment = document.createDocumentFragment();
|
||||
const pattern = /(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g;
|
||||
let cursor = 0;
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
if (match.index > cursor) fragment.append(document.createTextNode(text.slice(cursor, match.index)));
|
||||
const value = match[0];
|
||||
if (value.startsWith("~~")) fragment.append(el("del", value.slice(2, -2)));
|
||||
else if (value.startsWith("**") || value.startsWith("__")) fragment.append(el("strong", value.slice(2, -2)));
|
||||
else if (value.startsWith("`")) fragment.append(el("code", value.slice(1, -1)));
|
||||
else if (value.startsWith("[")) {
|
||||
const link = value.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);
|
||||
fragment.append(el("a", { href: link[2], target: "_blank", rel: "noreferrer" }, link[1]));
|
||||
} else fragment.append(el("em", value.slice(1, -1)));
|
||||
cursor = match.index + value.length;
|
||||
}
|
||||
if (cursor < text.length) fragment.append(document.createTextNode(text.slice(cursor)));
|
||||
return fragment;
|
||||
}
|
||||
|
||||
export function renderMarkdown(text) {
|
||||
const root = el("div.chat-bubble-text");
|
||||
const lines = String(text || "").split("\n");
|
||||
let paragraph = [];
|
||||
let list = null;
|
||||
let code = null;
|
||||
const flushParagraph = () => {
|
||||
if (paragraph.length) {
|
||||
root.append(el("p", inlineMarkdown(paragraph.join(" "))));
|
||||
paragraph = [];
|
||||
}
|
||||
};
|
||||
const flushList = () => {
|
||||
if (list) root.append(list);
|
||||
list = null;
|
||||
};
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
const line = lines[index];
|
||||
if (line.startsWith("```")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) {
|
||||
root.append(el("pre", el("code", code.join("\n"))));
|
||||
code = null;
|
||||
} else code = [];
|
||||
continue;
|
||||
}
|
||||
if (code) {
|
||||
code.push(line);
|
||||
continue;
|
||||
}
|
||||
const headerCells = tableCells(line);
|
||||
const separatorCells = index + 1 < lines.length ? tableCells(lines[index + 1]) : null;
|
||||
if (headerCells && separatorCells && isTableSeparator(separatorCells) && headerCells.length === separatorCells.length) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
const rows = [];
|
||||
for (index += 2; index < lines.length; index++) {
|
||||
const cells = tableCells(lines[index]);
|
||||
if (!cells || cells.length !== headerCells.length) {
|
||||
index--;
|
||||
break;
|
||||
}
|
||||
rows.push(cells);
|
||||
}
|
||||
const body = el("tbody");
|
||||
for (const row of rows) body.append(el("tr", ...row.map((cell) => el("td", inlineMarkdown(cell)))));
|
||||
root.append(el("table", el("thead", el("tr", ...headerCells.map((cell) => el("th", inlineMarkdown(cell))))), body));
|
||||
continue;
|
||||
}
|
||||
if (!line.trim()) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
continue;
|
||||
}
|
||||
const heading = line.match(/^(#{1,3})\s+(.+)$/);
|
||||
if (heading) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
root.append(el(`h${heading[1].length}`, inlineMarkdown(heading[2])));
|
||||
continue;
|
||||
}
|
||||
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
|
||||
const ordered = line.match(/^\s*\d+[.)]\s+(.+)$/);
|
||||
if (bullet || ordered) {
|
||||
flushParagraph();
|
||||
const tag = ordered ? "ol" : "ul";
|
||||
if (!list || list.tagName.toLowerCase() !== tag) {
|
||||
flushList();
|
||||
list = el(tag);
|
||||
}
|
||||
list.append(el("li", inlineMarkdown((bullet || ordered)[1])));
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith(">")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
root.append(el("blockquote", inlineMarkdown(line.replace(/^>\s?/, ""))));
|
||||
continue;
|
||||
}
|
||||
paragraph.push(line);
|
||||
}
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) root.append(el("pre", el("code", code.join("\n"))));
|
||||
return root;
|
||||
}
|
||||
|
||||
function tableCells(line) {
|
||||
const value = String(line || "").trim();
|
||||
if (!value.includes("|")) return null;
|
||||
const unwrapped = value.replace(/^\|/, "").replace(/\|$/, "");
|
||||
const cells = unwrapped.split("|").map((cell) => cell.trim());
|
||||
return cells.length > 1 && cells.every((cell) => cell !== "") ? cells : null;
|
||||
}
|
||||
|
||||
function isTableSeparator(cells) {
|
||||
return cells.every((cell) => /^:?-{3,}:?$/.test(cell));
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export function taskRowA11y(task, expanded) {
|
||||
const title = task.title || "untitled task";
|
||||
return {
|
||||
"aria-expanded": String(expanded),
|
||||
"aria-controls": `task-timeline-${task.id}`,
|
||||
"aria-label": `${expanded ? "Collapse" : "Expand"} timeline for ${title}`,
|
||||
};
|
||||
}
|
||||
@@ -36,6 +36,26 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.task-expand {
|
||||
width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
margin-right: var(--sp-2);
|
||||
padding: 0;
|
||||
color: var(--fg-muted);
|
||||
background: transparent;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 50%;
|
||||
font: inherit;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.task-expand:hover,
|
||||
.task-expand:focus-visible {
|
||||
color: var(--fg);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.activity-row {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
+28
-5
@@ -2,6 +2,7 @@ import "./tasks.css";
|
||||
import { api } from "../base/api.js";
|
||||
import { ago, el, empty, mount, pill, statusKind } from "../base/dom.js";
|
||||
import { statTile } from "../base/statTile.js";
|
||||
import { taskRowA11y } from "./task-row.js";
|
||||
|
||||
/**
|
||||
* Plain-language status labels. One place, so "waiting_human" only ever
|
||||
@@ -199,16 +200,37 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
}
|
||||
|
||||
function taskRow(t) {
|
||||
const expanded = expandedId === t.id;
|
||||
const timelineID = `task-timeline-${t.id}`;
|
||||
const toggle = (event) => {
|
||||
event?.stopPropagation();
|
||||
expandedId = expandedId === t.id ? null : t.id;
|
||||
renderRows();
|
||||
if (expandedId === t.id) loadTimeline(t.id);
|
||||
};
|
||||
return el(
|
||||
"tr.task-row",
|
||||
{
|
||||
onclick: () => {
|
||||
expandedId = expandedId === t.id ? null : t.id;
|
||||
renderRows();
|
||||
if (expandedId === t.id) loadTimeline(t.id);
|
||||
...taskRowA11y(t, expanded),
|
||||
tabindex: "0",
|
||||
onkeydown: (event) => {
|
||||
if (event.key !== "Enter" && event.key !== " ") return;
|
||||
event.preventDefault();
|
||||
toggle(event);
|
||||
},
|
||||
onclick: toggle,
|
||||
},
|
||||
el("td.mono", repoLink(t) ?? `${t.owner}/${t.repo}`),
|
||||
el(
|
||||
"td.mono",
|
||||
el("button.task-expand", {
|
||||
type: "button",
|
||||
"aria-expanded": String(expanded),
|
||||
"aria-controls": timelineID,
|
||||
"aria-label": `${expanded ? "Collapse" : "Expand"} timeline for ${t.title || "untitled task"}`,
|
||||
onclick: toggle,
|
||||
}, expanded ? "−" : "+"),
|
||||
repoLink(t) ?? `${t.owner}/${t.repo}`,
|
||||
),
|
||||
el("td.mono", issueLink(t) ?? `#${t.issue_number}`),
|
||||
el("td.strong", t.title || "(untitled)"),
|
||||
el("td", pill(statusLabel(t.status), statusKind(t.status))),
|
||||
@@ -322,6 +344,7 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
const cached = eventCache.get(t.id);
|
||||
return el(
|
||||
"tr.task-timeline-row",
|
||||
{ id: `task-timeline-${t.id}` },
|
||||
el(
|
||||
"td",
|
||||
{ colspan: 8 },
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import "./shim.js";
|
||||
import { renderMarkdown } from "../src/chat/markdown.js";
|
||||
import { updateStreamingReply } from "../src/chat/chat-stream.js";
|
||||
|
||||
test("chat Markdown renders Telegram-style rich blocks as semantic HTML", () => {
|
||||
const rendered = renderMarkdown(
|
||||
"# Summary\n\n**bold**, *italic*, ~~removed~~, and [docs](https://example.com)\n\n- first\n- second\n\n> quoted\n\n```go\nfmt.Println(\"hi\")\n```\n\n| Name | State |\n| --- | --- |\n| Archie | **live** |",
|
||||
);
|
||||
|
||||
assert.equal(rendered.querySelector("h1").textContent, "Summary");
|
||||
assert.equal(rendered.querySelector("strong").textContent, "bold");
|
||||
assert.equal(rendered.querySelector("em").textContent, "italic");
|
||||
assert.equal(rendered.querySelector("del").textContent, "removed");
|
||||
assert.equal(rendered.querySelector("a").getAttribute("href"), "https://example.com");
|
||||
assert.equal(rendered.querySelector("ul").children.length, 2);
|
||||
assert.equal(rendered.querySelector("blockquote").textContent, "quoted");
|
||||
assert.match(rendered.querySelector("pre").textContent, /fmt\.Println/);
|
||||
assert.equal(rendered.querySelector("table").querySelector("th").textContent, "Name");
|
||||
assert.equal(rendered.querySelector("table").querySelector("td").textContent, "Archie");
|
||||
});
|
||||
|
||||
test("streaming assistant replies keep rich Markdown in the live bubble", () => {
|
||||
const bubble = renderMarkdown("draft");
|
||||
const updated = updateStreamingReply(bubble, "# Live\n\n**bold**");
|
||||
|
||||
assert.equal(updated.querySelector("h1").textContent, "Live");
|
||||
assert.equal(updated.querySelector("strong").textContent, "bold");
|
||||
assert.equal(updated.className, "chat-bubble-text");
|
||||
});
|
||||
@@ -16,6 +16,10 @@ class Node {
|
||||
append(...cs) {
|
||||
for (const c of cs.flat(Infinity)) {
|
||||
if (c == null || c === false) continue;
|
||||
if (c instanceof DocumentFragment) {
|
||||
this.append(...c.childNodes);
|
||||
continue;
|
||||
}
|
||||
this.childNodes.push(c instanceof Node ? c : new TextNode(String(c)));
|
||||
}
|
||||
}
|
||||
@@ -87,6 +91,8 @@ class TextNode extends Node {
|
||||
}
|
||||
}
|
||||
|
||||
class DocumentFragment extends Node {}
|
||||
|
||||
class Element extends Node {
|
||||
constructor(tag) {
|
||||
super();
|
||||
@@ -97,8 +103,10 @@ class Element extends Node {
|
||||
globalThis.Node = Node;
|
||||
globalThis.Element = Element;
|
||||
globalThis.TextNode = TextNode;
|
||||
globalThis.DocumentFragment = DocumentFragment;
|
||||
globalThis.document = {
|
||||
createElement: (tag) => new Element(tag),
|
||||
createElementNS: () => new Element("svg"),
|
||||
createDocumentFragment: () => new DocumentFragment(),
|
||||
createTextNode: (text) => new TextNode(String(text)),
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import "./shim.js";
|
||||
import { taskRowA11y } from "../src/tasks/task-row.js";
|
||||
|
||||
test("task rows expose an explicit keyboard-accessible timeline control", () => {
|
||||
assert.deepEqual(taskRowA11y({ id: 42, title: "Keyboard task" }, false), {
|
||||
"aria-expanded": "false",
|
||||
"aria-controls": "task-timeline-42",
|
||||
"aria-label": "Expand timeline for Keyboard task",
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user