Commit Graph
24 Commits
Author SHA1 Message Date
sam e93ddf3128 chore(deps): bump ai-sdk to v0.1.21
ai-sdk v0.1.21 wraps the cancellation cause in aborted-stream errors
("%w: %w") instead of formatting it, so errors.Is(err, context.Canceled)
is reliable again. The Telegram channel was compensating with a comment
explaining why errors.Is could not be trusted.

The code was already correct; only the comment was obsolete. It now
states the real reason for context.WithoutCancel(turnCtx): turnCtx is
dead on both stop and fault paths, so the cursor-drop edit needs a live
context. The runtime effect of the bump is that a /stop landing inside
the step loop is now logged as "chat turn stopped" rather than
"route failed".

Refs ai-sdk-0pn
2026-08-15 00:24:33 +10:00
sam 61b4b7b0cf refactor(store): replace legacy persistence with SQLite
Task and event persistence now uses a dedicated SQLite sidecar derived from the configured state prefix, matching the independently persisted conversation store. The configured path now means a state-path prefix rather than a database file so fresh SQLite state never attempts to interpret the previous storage format.

Remove the retired implementation and dependency completely, strengthen SQLite migrations and concurrency behavior, restore backend-neutral coverage, and align configuration, operational guidance, UI labels, and deployment documentation with the new storage and host-daemon topology.
2026-08-09 22:27:25 +10:00
sam 4131f05036 feat(webui,gateway): wire config, channel, log-feed, and work-intake seams
Composition root work tying the config resolver, channel manager, log
feed, and executable workflow registry into the running daemon and
dashboard server: web.Channels/LogFeed/Workflows/ConfigProvenance,
channel-reload wiring, TaskStopper for the Stop action, and
SpawnRequest.Body/WorkRequests threading dashboard "Start work" requests
through the same admission path chat uses. Touches all three features at
once because this is where they're composed, not owned by any single one.

Refs #53, #54, #55
2026-08-09 01:26:58 +10:00
sam e10cbbc92c refactor: pre-cleanup. 2026-08-06 01:40:15 +10:00
sam 6ee86f2593 feat(setup): Prompter interface and a TTY-gated terminal implementation
archie-core-via. internal/infrastructure/configuration/setup defines
Prompter -- Select, ReadLine, ReadSecret, Confirm, all context-aware --
which is all the setup step logic (to follow) needs from a prompt
surface. No terminal dependency, so steps are testable without a TTY.

internal/infrastructure/terminalprompt.Terminal is the real
implementation, using golang.org/x/term. New refuses construction when
its input isn't a real terminal, with a message naming the problem --
enforcing "a non-TTY invocation fails with a clear message rather than
writing a partial config" at the earliest possible point, rather than
falling back to a plain read that would silently accept piped/scripted
input (ssh, `archied setup < answers.txt`, CI). Terminal satisfies
Prompter structurally; this package does not import that one, so
there's no infrastructure -> infrastructure edge for what Go's type
system already gives for free.

Each blocking read runs in a goroutine raced against ctx.Done(), so
Ctrl+C returns promptly instead of leaving the operator stuck; the
losing goroutine is abandoned on cancellation; term.ReadPassword's own
raw-mode restoration is not interruptible, so an abandoned secret read
can leave the terminal in raw mode until it unblocks on its own --
documented on Terminal.readSecret rather than worked around, since a
cancelled setup command is expected to exit shortly after via its own
signal handling anyway.

Tested by constructing a Terminal directly (bypassing New, same
package) over a plain pipe with an injected readSecret seam -- New's
TTY gate itself is exercised separately against a real os.Pipe(). No
weakening of the production constructor for testability.

Refs archie-core-via
2026-08-05 12:47:20 +10:00
sam cfec693716 chore: update NellDB to v0.3.0
- Add .pi-subagents/ to gitignore
2026-08-03 19:08:10 +10:00
sam 2307c8c81a feat: unify provider and model selection 2026-07-31 03:40:03 +10:00
sam 65aa5b462d chore: cleanup 2026-07-28 18:46:50 +10:00
sam f800e1de36 refactor(worktree): replace git shell-out with go-git v6
internal/worktree no longer executes the git binary. Clone, fetch,
checkout, commit, push and diff all run in-process through go-git v6,
which also removes the package's 9 noctx findings since the Context
variants are first-class.

Security: the forge token no longer leaves the process. The old
implementation wrote a GIT_ASKPASS shell script to disk and exported the
token into the environment of every git child process. Authentication is
now an in-process credential passed via client.WithHTTPAuth. cloneURL
also stops embedding the bot user in the GitHub URL.

Dropped the per-repo object cache (PreparePersistent, prepareCache,
CleanupExpiredCaches). go-git can clone with shared alternates but has no
equivalent of --dissociate, so a cached bare repo would remain a live
dependency of every worktree built from it, and expiring one would
corrupt running tasks rather than fail cleanly. Every task now gets an
independent full clone. repo.PersistentStorage still governs the
container volume; only the git object cache is gone.

Two real defects surfaced while porting, both caught by the new tests:

  - go-git honours the host's global git config and cannot sign commits
    (no gpg fallback, only an ObjectSigner plugin). On any machine with
    commit.gpgSign=true set globally, every bot commit would have failed
    with "cannot auto-sign commit". setIdentity now pins gpgsign=false in
    the clone's own config so daemon behaviour does not depend on the
    ambient config of whatever host it runs on.
  - go-git's Add(All) does NOT honour .git/info/exclude, which is how the
    .archie-prepared sentinel was kept untracked. It was being committed
    and would have been pushed onto every task branch. The sentinel now
    lives at .git/archie-prepared, where nothing can ever track it, and a
    regression test asserts it never appears in a commit.

Diff is now merge-base relative via Commit.MergeBase, matching the three
dot semantics of `git diff origin/base...HEAD`; diffing against the remote
tip would attribute commits landed on base since the branch started to
this task and could trip the diff-size cap. Base resolution tries the
remote-tracking ref first and falls back to the short "origin/<base>"
revision, keeping git's more permissive lookup.

The test suite was rebuilt on go-git fixtures and no longer needs a git
binary installed to run.
2026-07-28 01:56:59 +10:00
sam 15d746c2f6 style: phase 1 of lint remediation — autofix pass (qa4)
golangci-lint run --fix plus the formatters: errorlint, gocritic,
sloglint, usestdlibvars, usetesting, gci, gofumpt, goimports.
160 issues -> 130.

One autofix was wrong and had to be reverted by hand. gocritic rewrote

    ctx, cancel = context.WithTimeout(ctx, m.prefetchTimeout)

to `:=` inside an if-block in internal/memory/manager.go. That does not
compile, which is the good outcome — had it compiled, the shadowed ctx
would have scoped the timeout to the if-block and the prefetch deadline
would silently never have applied. Restored the assignment and commented
why it must not be a declaration.

Worth recording: --fix is not a safe no-op. It broke the build on a
24-file change, and the failure mode it was one compiler error away from
was a silent behaviour change.
2026-07-28 01:37:20 +10:00
sam 446dc6b3de feat(indexing): port tau's codesearch workspace index (4we)
First slice of the tau cherry-pick strategy: copy-and-mutate rather than
extracting tau to pkg/. Exporting would force designing metrics, session
and logger seams upfront, before archie-core knows which of them it wants
differently — a cost paid for reuse not yet proven. ai-sdk earned library
status by stabilising across two consumers; nothing in tau/internal has.

indexing is the cheapest high-value lift: 512 LoC, one file, and its only
coupling to tau was three calls to process-global config path helpers.
Nothing else in tau imports it.

Mutations from upstream:
  - path helpers become an explicit indexing.Config. Two archied instances
    share a host (archie and winter), so they must not share one index.
  - the child-process helper is archied's own workspace-codesearch
    subcommand, dispatched before flag parsing so it touches no config,
    store or NATS.
  - deferred db.Close calls explicitly discarded; archie-core runs errcheck.

The child process is not incidental: google/codesearch calls fatal exits on
a corrupt index and leaks mmapped regions. Verified end to end against this
repo — 2.2MB indexed, correct hits for BuildSystemPrompt, [] for no match,
and a deliberately corrupted index returns "corrupt index" with exit 1
instead of taking the process down.

Every lifted file carries a provenance header naming its tau path and
commit (4893818d0c76), so refreshing from upstream is a diff rather than
archaeology.
2026-07-28 01:37:19 +10:00
sam 285c618f74 fix(chat): drain FullStream, not TextStream — streaming deadlocked every reply
Streamed chat replies hung on the first token: the draft rendered an
empty cursor, the typing indicator never cleared, and the turn never
completed.

RouteStream consumed stream.TextStream, but ai-sdk's channel contract
makes FullStream authoritative and requires draining it until close --
its writes are synchronous, so an unread FullStream applies backpressure
and stalls the producer. Once its buffer filled, the producer blocked,
TextStream stopped yielding, and the range loop blocked forever.

TextStream was the wrong source regardless: it is explicitly best-effort
and drops deltas when not drained, so a reply reconstructed from it can
silently lose text. Range over FullStream and collect StreamPartTextDelta
parts, exactly as the SDK documents.

Also bumps ai-sdk v0.1.17 -> v0.1.18 (build, full suite and lint clean).
2026-07-27 05:04:04 +10:00
sam 3e3911a423 feat(telegram): native rich messages + streamed replies (16.32)
Upgrades go-telegram/bot v1.18.0 -> v1.22.0 and uses the Bot API's rich
message support instead of hand-rolled formatting.

The previous commit converted LLM Markdown into Telegram's HTML subset,
on the premise that the API could not take Markdown directly and had no
table element. Both are true of v1.18.0 but not of v1.22.0, which adds
sendRichMessage/sendRichMessageDraft taking InputRichMessage{Markdown},
plus RichBlockTableCell for native tables. markdownToHTML and its tests
are deleted: LLM Markdown, tables included, now goes to Telegram as-is.

Replies also stream. runtime.ChatStream already returned a TextStream
and sendRichMessageDraft renders partial output, so the only missing
piece was a gateway seam: gateway.LLMStreamResponder plus Router.
RouteStream, which degrades to the blocking Route when unset so any
adapter can call it unconditionally. Local commands answer from local
state and are not streamed; an unrecognised /command is, since Route
hands it to the LLM. main.go derives both responders from one shared
turn implementation.

Draft updates are throttled to one per 700ms to respect per-chat rate
limits, and every streaming/rich path falls back rather than dropping a
reply: a rejected rich send retries unformatted, and a failed draft
update is skipped since the final message is authoritative.
2026-07-27 04:57:36 +10:00
sam 80cd473559 fix: remove local filesystem replace directive for NellDB
go.mod pointed NellDB at a local dev-machine path
(/work/apps/nell-engine) instead of the published v0.2.5 module,
which the Gitea CI runner can't resolve — every push since the
replace was added has failed the deploy workflow's docker build
(go mod download: no such file or directory), silently leaving
carina on a two-day-old image. Confirmed nell-engine's local HEAD
is functionally identical to the already-tagged-and-pushed v0.2.5
(only a trivial .gitignore commit ahead), so dropping the replace
and re-resolving from the registry is a no-op for behavior.
2026-07-27 04:00:51 +10:00
sam 4c1cc151a5 feat: NellDB storage backend replacing SQLite (archie-core-abg.30)
Extracted store.TaskStore interface (20 methods) covering task
lifecycle, queries, and observability. Separate WorkflowStore for
the agent RPC proxy.

New internal/nell/ package:
  - OpenStore(path, nodeID) — persistent logstore.LogStore backend
  - OpenMemory(nodeID) — in-memory store for tests
  - Full TaskStore implementation via sdk.DocDB with MVCC

All consumers updated to interface:
  - daemon.Daemon.Store, webui.Server.Store, storerpc.Server.Store
  - workflow.TaskContext.Store (WorkflowStore)
  - cmd/archied uses nell.OpenStore(cfg.DBPath, cfg.BotUser)

7 integration tests. Build + 32 packages pass.

Closes: archie-core-abg.30
2026-07-26 01:06:05 +10:00
sam f36b6f2e41 feat: gateway architecture with Telegram channel
internal/gateway/ — Gateway interface, Router with gateway-local
command dispatch (commands handled directly, no LLM needed).
ModelManager interface for /model and /models support.

internal/channels/telegram/ — Telegram Gateway using go-telegram/bot
v1.18.0 (ported from GopherClaw). Webhook support, middleware,
allowed-chat filtering, long-message splitting.

internal/config/ — ChatConfig + TelegramConfig optional TOML block.

Cmd wiring in archied/main.go: starts Telegram gateway when
[chat.telegram] token_env is configured.

Gateway-local commands implemented: /status, /help, /model, /models.
Write actions (/spawn, /approve, /cancel) follow in abg.13.

Closes: archie-core-abg.5, archie-core-abg.14, archie-core-abg.15
2026-07-25 23:50:52 +10:00
sam edd05aea6b feat: add Gitea forge support alongside GitHub
Implements the Forge interface for Gitea instances (tested against
git.catlow.cloud, Gitea v1.26.4). The forge.New factory now dispatches
on forge type, and config validation accepts 'gitea'.

Changes:
- internal/forge/gitea.go — GiteaClient implementing all 11 Forge
  methods: issue polling (assigned + label), comments, PR creation,
  PR state reconciliation, issue closure, reactions, state labels,
  push verification. Handles edge cases: not-found PRs return
  'closed', GetUserByName errors from the Gitea SDK are mapped to
  user-friendly messages.
- internal/forge/forge.go — New() factory dispatching on forge type
  (github/gitea). GitHub constructor renamed to NewGitHub.
- internal/forge/github_test.go — updated to use New() signature
- internal/config/config.go — forge.type accepts 'gitea', BotEmail
  defaults change per forge type (gitea uses @gitea.local)
- cmd/archied/main.go — passes cfg.Forge.Type to forge.New()

Dependencies: added code.gitea.io/sdk/gitea v0.25.1

End-to-end verified against live Gitea instance: daemon starts clean,
registry built (5 workflows), web UI listening, no errors or warnings.
2026-07-22 05:15:09 +10:00
sam 2f4ca5be60 chore: switch ai-sdk from local path to published version 2026-07-22 05:05:06 +10:00
sam de57f72cce feat: add Docker container sandbox for archie-agent
Dockerfile: multi-stage fat image (golang:1.26 builder → ubuntu:24.04)
with Go 1.26, Python 3.12/3.13 via deadsnakes, UV, Node 22, pnpm,
TypeScript, esbuild, git, gh, golangci-lint, gofumpt.

Container pool (internal/container): manages Docker container lifecycle
via moby/moby client. Per-task containers with bind-mounted workspaces.

- Acquire: create, start, mount workspace, inject NATS + API key env
- Release: stop, remove (AutoRemove as safety net)
- Orphan recovery on daemon startup (label: archie-daemon=true)
- MaxConcurrency enforcement, MaxUptime config (unused in MVP)
- Image pull with "missing"/"always" policy

Config: [containers] block (enabled, image, max_concurrency, max_uptime,
pull_policy). Validation: requires agent.mode = "nats" and [nats] url.

Daemon: acquires container before workflow.Run, releases after.
Container environment auto-populated from provider API keys.
2026-07-22 02:39:17 +10:00
sam a9641276e1 feat: parse SKILL.md frontmatter, inject skill body into agent context
Adds internal/skill package with YAML frontmatter parsing and skill
discovery from .agents/skills/ (agentskills.io spec convention).

- Frontmatter struct with name, description, version, metadata.archie
- Parse() extracts YAML frontmatter delimited by --- markers
- Discover() scans .agents/skills/*/SKILL.md (follows wfeval pattern)
- LoadBody() for single-skill lazy loading

Skills moved from .archie/skills/ to .agents/skills/ per the
agentskills.io specification.

Wiring: TaskContext.SkillBody field, lazy-loaded on first agent stage
from worktree. When non-empty, prepended to Mission as "Follow these
project-specific guidelines" context. Hardcoded Mission templates stay
(task-specific formatting). Backward compatible: empty when no skill
found.
2026-07-22 02:23:20 +10:00
sam bb2193e5e4 feat: add optional NATS JetStream task distribution
Adds optional NATS-based task distribution alongside the existing
SQLite flow. When [nats] is absent from config, zero behaviour change.

New internal/nats package:
- Subject constants matching PRD §2 (archie.task.{bug,feature,default,bootstrap})
- Client: Connect (stream + durable pull consumer), PublishTask
  (Nats-Msg-Id dedup), Fetch, DecodeTask
- Tests with embedded NATS server (connect/publish, dedup, subject routing)

Config: NATSConfig{URL, TokenEnv} on Config, commented-out [nats] block
in config.example.toml

Store: ClaimByIssue atomic claim by owner/repo/number for NATS consumer

Daemon: Nats client field, poll() branches to pollNATS/pollSQLite,
Cycle() branches to drainNATS/drainSQLite (NATS fetch then SQLite
ClaimNext fallback for requeued tasks), processNATSTask
(decode → EnqueueIssue → ClaimByIssue → process → Ack)

Scratch: explorer and plan agent outputs from parallel-explore phase
2026-07-22 02:02:09 +10:00
sam c0d108a5d0 feat: add Yaegi-based plugin system (gates, custom stages, skill scripts)
Implements the full PRD (docs/prds/yaegi-plugin-system.md): repos can
now define .archie/gate.go for diff-inspecting quality rules shell
commands can't express, .archie/stages/*.go for custom pipeline steps,
and skills can ship Go scripts run via a new run_go_script agent tool —
all interpreted in-process with Yaegi, with panics recovered so a bad
script can't take down the daemon. Hot reload (phase 4) needed no code:
every loader reads from disk per call and every task gets a fresh
clone, so nothing is ever cached to go stale.
2026-07-22 00:54:46 +10:00
sam 708e55a95b feat: implement workflow — planner/builder agent stages over agentloop
AgentStage is the reusable bridge from workflow stages to agentloop
runs: role->model selection from config, budgets, repo gate conversion,
task-row NotesStore (survives worktree cleanup, never pollutes the PR),
and park-on-anything-but-passed. Every future LLM stage (tdd,
feasibility) is an AgentStage with a different mission/gate/handler.

The implement workflow: prepare -> baseline gate (park on red base,
prevents park-storms) -> plan (read-only agentloop, plan posted to the
issue as a veto window) -> build (full toolset behind the repo's
configured gate) -> commit/push -> diff cap -> PR with the builder's
finish summary as the body.

Proven live on samcharles93/todo#3: planner 3 steps, builder 4 steps
(~31k tokens total), producing gate-verified table-driven TodoStore
tests as PR #4.
2026-07-21 04:03:06 +10:00
sam c2c8e92304 feat: archied walking skeleton — poll, store, worktree, workflow engine, bootstrap PR
Repurposes archie-core as the archie orchestrator daemon (the old
Pocketbase PM-backend plan is archived under .references/).

- cmd/archied: -config, -once (single cycle for timers/testing)
- internal/config: TOML; per-repo gate command lists; role->model refs
- internal/store: SQLite (modernc, WAL) task state machine with
  transitions audit, idempotent enqueue, crash recovery (running ->
  queued, attempt++)
- internal/forge: go-github v78 — labelled-issue polling, invitation
  auto-accept, push verification, PR create/state, comments, close
- internal/worktree: fresh clone per task, bot identity, askpass token
  handling, diff-size stats, cleanup on merge/reject
- internal/workflow: extensible engine (stages over TaskContext, shared
  step library, label routing bug->tdd feature->feasibility default->
  implement); parks always comment on the issue. Bootstrap workflow
  (deterministic marker-file PR) proves the plumbing without LLM spend.

Store and worktree round-trips covered by tests (local bare remote).
2026-07-21 03:46:06 +10:00