Commit graph

561 commits

Author SHA1 Message Date
Snider
35b327d47e fix(agent/agentic): nil-guard PrepSubsystem.Core() in handleComplete
Defensive nil check returns a typed error result when the subsystem
is constructed without a runtime, matching the pattern in adjacent
handlers. Adds Bad case test.

Co-authored-by: Cerberus <noreply@anthropic.com>
2026-04-25 20:49:57 +01:00
Snider
9628e5d088 feat(agent/brain): non-Laravel callers route through shared OpenBrain client (#121)
Audit + remediation pass on non-Laravel Brain callers per #121.

docs/brain-callers-audit.md (NEW): audit baseline. Lists every PHP +
Go + script call site, current protections (org auth, retry, circuit
breaker), and gaps. Cross-references recent fixes (#312, #998, #1052,
#1055, #1006, #985).

New pkg/agentic/brain_client.go helper: routes Go callers through
the shared OpenBrain client path with org injection (CORE_BRAIN_ORG
fallback) and a shared circuit breaker.

Patched call sites:
- pkg/agentic/prep.go (line ~1200)
- pkg/agentic/session.go (line ~826)
- pkg/agentic/brain_seed_memory.go (line ~153)
- pkg/brain/direct.go (line ~106)

These previously made raw Brain HTTP posts. Now they go through the
hardened client path inheriting #998 (key-perm), #1052 (bearer SSRF
guard), #1055 (jitter), and the circuit breaker.

Remaining non-Laravel gaps (documented in audit doc, not patched here
because they're outside this lane's path-allowlist):
- core/mcp/pkg/mcp/agentic/prep.go
- Hermes Python plugins
- Claude shell hooks
- plugins/core-go api-endpoints SKILL example

Follow-up tickets needed for those (file separately).

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=121
2026-04-25 20:33:33 +01:00
Snider
40728e68d1 feat(agent/agentic): Poindexter KD-tree clustering replaces exact-key bucketing in runQAWithReport
qa_cluster.go wires QA finding clustering through Poindexter instead
of the old exact (tool, severity, category, rule) bucketing. Hashed
feature vectors built from finding metadata + message text are
indexed in Poindexter KD-trees with cosine + Euclidean distance,
near-neighbours unioned, then emitted as the existing DispatchCluster
shape (so consumers don't break).

Old exact-key grouping kept as fallback if Poindexter tree
construction ever fails.

qa.go updated to describe new similarity-based contract;
runQAWithReport already consumes clusterFindings, picks up the new
grouping automatically.

Tests cover: 3 similar findings + 2 distinct → grouped correctly;
5 distinct findings → 5 clusters; 0 findings → empty/nil no panic;
sample-cap regression preserved.

Note: github.com/Snider/Poindexter added as a direct dep. Per the
non-negotiable migration policy on Snider personal-namespace deps
(see #219), file follow-up to migrate Poindexter to its canonical
core/* home if/when that lands.

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=164
2026-04-25 20:25:05 +01:00
Snider
b42cf5a18c feat(agent/agentic): 5-min background git fetch loop for registered repos
fetch_loop.go starts at PrepSubsystem.OnStartup, ticks on configurable
interval (default 5min), respects ctx.Done() for clean shutdown.
Each tick runs `git fetch origin <DefaultBranch>` via s.Core().Process()
— no worktree mutation.

Repo discovery sources (priority):
1. agents.fetch_repos in runtime config
2. repos / agents.*.repos in agents.yaml
3. Fallback scan of WorkspaceRoot() per RFC §7

Interval config: agents.fetch_interval, dispatch.fetch_interval, or
top-level fetch_interval in agents.yaml.

Loop survives individual repo failures (logs + continues — one bad
repo can't kill the loop).

Tests cover tick timing, failure isolation, ctx cancellation.

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=165
2026-04-25 20:24:21 +01:00
Snider
820d33ebec feat(agent/agentic): scaffold core pipeline command tree per RFC-AGENT-PIPELINE.md
Codex preflight found docs/RFC-AGENT-PIPELINE.md (not the speculative
RFC.pipeline.md the ticket title referenced). Implementation matches
the actual RFC tree:

- core (top-level)
- core pipeline (router)
- core pipeline epic / fix / budget / training (grouped routers)
- All RFC leaf commands under each grouped router

Routers print scoped help. Each leaf currently returns "not yet
implemented" with a concrete next doc/flow reference (e.g. docs/flow/
RFC.flow-audit-issues.md). Future tickets wire the leaves to real
handlers.

Tests cover registration, descriptions, --help routing through
core pipeline audit.

Note: docs/RFC.pipeline.md alias still missing — TODO note in
commands_core.go for that follow-up.

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=228
2026-04-25 20:24:21 +01:00
Snider
8858545f63 feat(agent/lib/flow): YAML flow library — Parse + ParseFile + LoadEmbedded
New pkg/lib/flow package per RFC §Flow System:

types.Flow{Name, Description, Steps}, types.Step{Name, Cmd, Args,
ContinueOnError}.

Parse(reader io.Reader) (Flow, error): YAML decoder
ParseFile(path string) (Flow, error): reads via core.Fs, then Parse
LoadEmbedded(name string) (Flow, error): bundled flow templates;
.md files only treated as flows when they contain YAML frontmatter

Validation: steps may be absent (empty Steps slice OK); any declared
step must define cmd.

Pairs with #160 (run/flow command at pkg/agentic/flow.go) — that
consumes types from this library for sequential step execution.

Tests cover: valid YAML, continueOnError, empty input, malformed
YAML, missing cmd, temp-file ParseFile, missing embedded files,
markdown-template failure (current state — embedded markdown is
content not YAML).

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=229
2026-04-25 20:21:33 +01:00
Snider
eed51d72b8 feat(agent/agentic): run/flow now executes sequential YAML steps
run/flow command now runs flow steps via the existing command tree:
- Each step's cmd is dispatched through s.Command(...)
- stdout/stderr captured per step
- Stops on first untolerated failure
- continueOnError: true allows step to fail without aborting flow
- Parse-time validation rejects unknown/non-executable commands
  BEFORE any step runs

flow/preview keeps the old inspection-only behaviour. Empty flows
succeed as no-ops.

Returns FlowRunOutput with summary: OK boolean, Executed/Passed/
Failed counts, per-step results.

Pest-equivalent Go tests cover: 3-step happy path, non-existent
cmd parse-time error, mid-flow failure (with + without
continueOnError), empty flow.

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=160
2026-04-25 20:09:52 +01:00
Snider
99b0865303 fix(agent/agentic): annotate net/http as AX-6 structural exception
pkg/agentic/transport.go is the low-level HTTP boundary behind
core.Drive / core.API — there is no exported core/api generic
request/response wrapper that covers protocol-level MCP POST/SSE
exchange. Codex preflight confirmed: http.Client state, request
construction, response handling, and header mutation are all
present and intrinsic.

Resolution: annotation rather than purge. Per AX-6 doctrine, when
a core wrapper genuinely doesn't exist, explicit annotation is the
correct outcome (vs forcing through a wrapper that doesn't fit).

Doc comment now explains: "structural HTTP transport boundary for
core.API protocol streams and raw MCP POST/SSE exchange; no
exported core/api generic request wrapper covers this file."

Future PR: when core/api exposes a generic request wrapper
(potentially via #197 TransformerIn/Out gateway), revisit this
file and replace where feasible.

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=222
2026-04-25 19:52:38 +01:00
Snider
f2b6ff29bd fix(agent): tighten directory perms in .core/reference/ siblings (Athena #988)
Mantis #324 narrowly tightened fs.go from 0644/0755→0600/0700. Athena audit
during task #20 closure-verification (2026-04-25) found sibling files in the
same directory still using 0755 for MkdirAll, leaving parent dirs world-listable
even when file content is 0600.

This commit applies the same hardening to:
- .core/reference/error.go:393 — crash-report parent dir 0755→0700
- .core/reference/embed.go:514/567/656 — workspace template extract dirs 0755→0700
- .core/reference/embed.go:595/660 — os.Create→os.OpenFile(...0600) for
  template renders + standard-file copies (default umask 0644 was leaking
  workspace-template content to other users on shared hosts)
- pkg/lib/workspace/default/.core/reference/error.go:414 — same crash-report fix
- pkg/lib/workspace/default/.core/reference/embed.go:518/571/660 — same template fixes

Workspace-template duplicates are kept in sync so newly-scaffolded workspaces
inherit the hardened perms instead of regressing to 0755/0644.

Closes Mantis #988.

Co-authored-by: Codex <noreply@openai.com>
2026-04-25 16:29:28 +01:00
Snider
6be6cb095c feat(agent/brain): adopt shared T1 client + propagate org through actions (#177)
#177 (T3/5 — direct subsystem adopts shared client):
- pkg/brain/direct.go: HTTP transport now delegates to shared T1 client
  in core/mcp's pkg/mcp/brain/client (retry, circuit breaker, org propagation)
- pkg/brain/actions.go: org now survives from action options through
  remember/recall/list calls
- pkg/brain/direct_test.go + actions_test.go: tests updated for org propagation

Tickets deferred:
- #179 (T5/5 — cross-runtime contract test + BRAIN-CALLERS.md): needs
  cross-repo edits to mcp + external runtime consumers
- #180 (lift RFC-OPENBRAIN features into vendored BrainService):
  base schema lacks memory_scope; no agentBoot, brain:consolidate,
  agent-context endpoint, or lifecycle events present

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=177
2026-04-25 16:22:38 +01:00
Snider
bf10d16f49 feat(agent): batch — sprint MCP tools + cmd cleanup (#142 #225 #226 #227)
Codex 5.5 batch lane processed 26 open Mantis tickets. 13 stale-fixed,
4 implemented, 9 deferred.

Tickets implemented:
- #142 — agentic_sprint_start + agentic_sprint_complete MCP tools wired to /v1/sprints/{id}/{start,complete} platform endpoints with tests
- #225 — cmd/core-agent/commands.go: removed raw flag parsing; startupArgs() uses Core arg filtering + local log-level strip
- #226 — cmd/core-agent/main.go: syscall.Exit(1) → core.Exit(1)
- #227 — pkg/agentic/dispatch.go: runtime.GOOS → Core environment-backed OS detection

Tickets stale-fixed: #161, #162, #163, #166, #167, #168, #171, #172, #223, #224, #230, #231, #232, #233
Tickets deferred: #160, #164, #165, #173, #222, #228, #229, #234

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=142
Closes tasks.lthn.sh/view.php?id=225
Closes tasks.lthn.sh/view.php?id=226
Closes tasks.lthn.sh/view.php?id=227
2026-04-25 14:55:23 +01:00
Snider
56a97e9178 fix(agent/brain): AX-6 sweep on direct.go — net/url → core.URLEncode + core.Join
url.Values manipulation replaced with []string builder + core.URLEncode
+ core.Join("&", params...). net/url import removed.

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=966
2026-04-25 13:34:18 +01:00
Snider
a0ba74d220 fix(agent/monitor): AX-6 sweep on sync.go — net/url → core.URLEncode
url.QueryEscape → core.URLEncode for checkin URL agent param.
net/url import removed.

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=965
2026-04-25 13:32:52 +01:00
Snider
14b0ef529c fix(agent/agentic): AX-6 sweep on scan.go — net/url → core.URLEncode
url.QueryEscape → core.URLEncode in listRepoIssues label encoding.
net/url import removed.

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=963
2026-04-25 13:30:27 +01:00
Snider
fedb1f3b00 fix(agent/monitor): AX-6 sweep on monitor.go — net/url → core.URLEncode
url.QueryEscape → core.URLEncode for inbox URL agent param encoding.
net/url import removed.

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=962
2026-04-25 13:30:27 +01:00
Snider
9ed15cbb42 fix(agent): replace sync/atomic plan ID generator with core.ID() (#863)
Removed local sync/atomic + crypto/rand + encoding/hex based plan ID
generator from pkg/agentic/plan.go. Switched planID() to core.ID()
primitive. Preserves id-{counter}-{suffix} shape via Core's primitive.

prep.go, sync.go, pkg/brain/*.go scanned — no sync imports remained
in non-test files.

Closes tasks.lthn.sh/view.php?id=863

Co-authored-by: Codex <noreply@openai.com>
2026-04-25 09:53:09 +01:00
Snider
e04f018b4c test(agent): add AX-10 unit tests for dispatch/session/sync/tools/content (#169)
Append-only — no existing tests modified.

- dispatch_test.go: TestDispatch_agentCommand_{Good,Bad,Ugly}
- session_test.go: TestSession_normaliseSessionAgentType_{Good,Bad,Ugly}
- sync_test.go: TestSync_syncBackoffSchedule_{Good,Bad,Ugly}
- tools_test.go: TestTools_RememberInput_{Bad,Ugly} (Good was pre-existing)
- content_test.go: TestContent_contentSchemaType_{Good,Bad,Ugly}

gofmt clean. Test verification deferred (private dappco.re/go/* deps
missing go.sum entries with GOWORK=off — would resolve under workspace).

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=169
2026-04-25 07:57:30 +01:00
Snider
f293d48006 fix(agent): tighten workspace file perms 0644→0600 to protect extracted secrets (Cerberus #324)
.core/reference/fs.go (canonical) + pkg/lib/workspace/default/.core/reference/fs.go (embedded copy):
- Write/WriteAtomic/Create/Append default to 0600
- Parent directories use 0700 (was 0755)
- WriteMode reapplies the requested mode after writes so overwriting an
  existing file also tightens permissions

Test (pkg/lib/lib_test.go) keeps embedded fs.go synced with canonical +
asserts extracted workspaces carry the secure permission defaults.

tests/cli/extract copy not hand-edited — that flows from regeneration.

Co-authored-by: Codex <noreply@openai.com>
Closes tasks.lthn.sh/view.php?id=324
2026-04-25 04:19:30 +01:00
Snider
ba8de0c0bb fix(agent): purge sync.Once from pkg/agentic via core.Once (§14A)
Closes Mantis #863 ([agent] Phase 2: purge sync stdlib).

Per RFC plans/code/core/go/RFC.primitives-lifecycle.md §14A (landed core/go
dev 8995a80), swaps the four sync.Once usages to core.Once and the two
sync.Once{} reset-pattern callsites to core.Once.Reset():

pkg/agentic/statestore.go:
- Drop `import "sync"`.
- stateStoreRef.once: sync.Once → core.Once
- closeStateStore reset: `s.stateOnce = sync.Once{}` → `s.stateOnce.Reset()`

pkg/agentic/workspace_stats.go:
- Drop `import "sync"`.
- workspaceStatsRef.once: sync.Once → core.Once
- closeWorkspaceStatsStore reset: `s.workspaceStatsOnce = sync.Once{}` →
  `s.workspaceStatsOnce.Reset()`

pkg/agentic/prep.go:
- Drop `import "sync"`.
- PrepSubsystem.stateOnce + .workspaceStatsOnce: sync.Once → core.Once

The Reset() pattern matches stdlib semantics (see RFC §14A "Tradeoff: Once.
Reset semantics") — caller serialises via the existing closeStateStore /
closeWorkspaceStatsStore structure that nests Reset inside the lifecycle
inverse, so no concurrent Do races are introduced.

Net: 3 files, +7/-11. Mechanical line-edit per RFC §16 migration plan.

Audit re-check post-commit:
  grep -n '"sync"\|sync\.Once\|sync\.Mutex' pkg/agentic/{statestore,workspace_stats,prep}.go
  → empty (lib local variable named `sync` in mirror.go is unrelated; not
    in scope of this ticket).

Pre-flight verification: core.Once + Reset symbols verified present on
core/go dev 8995a80. Local AX-10 build blocked by the same pre-existing
workspace forge dep break that affects all consumers (root cause: fake
v0.8.0-alpha.1 pins per task #28); CI in healthy env will validate.

Co-Authored-By: Athena <athena@lthn.ai>
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-25 00:58:49 +01:00
Snider
34010f6d35 feat(ax-10): bring agent to v0.8.0-alpha.1 + CLI test scaffold
- Bump dappco.re/go/* deps to v0.8.0-alpha.1 in go.mod (any forge.lthn.ai/core/* paths migrated to canonical dappco.re/go/* form)
- Update Go source imports across 29 .go files
- Add tests/cli/agent/Taskfile.yaml AX-10 scaffold (build/vet/test under default deps), per RFC-CORE-008-AGENT-EXPERIENCE.md §10

Co-Authored-By: Athena <athena@lthn.ai>
2026-04-24 23:48:34 +01:00
Snider
a50e3d8291 test(agentic): add HTTPS cert regression tests + fleet sync audit
Fleet registration in pkg/agentic already goes through the shared
&http.Client{Timeout: 30s} at transport.go:13 — no InsecureSkipVerify,
no custom TLS transport. This audit documents that finding and adds
regression coverage so future refactors can't silently strip TLS
validation from the /v1/fleet/register path.

Verdict: OK. No production bug. Tests pass trusted TLS server case
and reject untrusted cert with a wrapped error that surfaces the
certificate / x509 / tls signal in the message.

Closes tasks.lthn.sh/view.php?id=29

Co-authored-by: Codex <noreply@openai.com>
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-23 18:40:02 +01:00
e58986a3b4 revert fcb9c189e5
revert fix(agentic): harden TODO workspace write

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-23 12:32:57 +01:00
Codex
cbc262add4 fix(agentic): harden TODO workspace write
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-23 12:32:57 +01:00
Snider
401487301a feat(agent): gpt-5.4-mini/mature pass 5
- `go test ./... -count=1 -timeout 60s`

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-18 08:55:41 +01:00
Snider
b6d67ae634 feat(agent): gpt-5.4-mini/mature pass 4
Commit landed on `dev` at `a7c16de9715a653bc335d076982eaf9ce04b54bc`.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-18 08:48:06 +01:00
Snider
beff657e57 feat(agent): gpt-5.4-mini/mature pass 3
- `go test ./pkg/agentic -count=1 -timeout 60s`

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-18 08:42:14 +01:00
Snider
60f4cb6fdb feat(agent): gpt-5.4-mini/mature pass 2
- `git add` / `git commit` fail with `Operation not permitted` on `.git/index.lock`
  - even a plain `touch .git/...` is blocked

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-18 08:34:52 +01:00
Snider
651783e1f5 feat(agent): gpt-5.4-mini/mature pass 1
Commit:

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-18 08:32:10 +01:00
Snider
43568cae01 test(agentic): cover message and dispatch sync contracts
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-17 21:01:10 +01:00
Snider
2daabf27f7 fix(agentic): check append write failures
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-17 20:52:37 +01:00
Snider
4cea9555d4 fix(agentic): reject empty MCP session ids
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-17 20:50:17 +01:00
Snider
2eda43d5ad hardening(prep): fail closed on specs copy
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-17 20:38:42 +01:00
Snider
7bb5c31746 fix(agentic): surface persistence failures
Add warnings for silent filesystem write/delete failures in agentic persistence helpers and record two adjacent hardening gaps for follow-up.\n\nCo-Authored-By: Virgil <virgil@lethean.io>
2026-04-17 20:36:14 +01:00
Snider
db3ddc133e test(monitor): force binary fixtures into harvest tests
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-17 20:32:32 +01:00
Snider
b54daae418 fix(reference): harden core reference edge cases
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-17 20:31:06 +01:00
Snider
e837a284af feat(agent): RFC §9 agentic_auth_login MCP tool + dedupe tool registrations
Three load-bearing gaps between the agent RFC and the MCP surface:

- RFC §9 Fleet Mode describes the 6-digit pairing-code bootstrap as the
  primary way an unauthenticated node provisions its first AgentApiKey.
  `handleAuthLogin` existed as an Action but never surfaced as an MCP
  tool, so IDE/CLI callers had to shell out. Adds `agentic_auth_login`
  under `registerPlatformTools` with a thin wrapper over the existing
  handler so the platform contract stays single-sourced.
- `RegisterTools` was double-registering `agentic_scan` (bare
  `mcp.AddTool` before the CORE_MCP_FULL gate, then again via
  `AddToolRecorded` inside the gate). The second call silently replaced
  the first and bypassed tool-registry accounting, so REST bridging and
  metrics saw a zero for scan. Collapses both into a single recorded
  registration before the gate.
- `registerPlanTools` and `registerWatchTool` were also fired twice in
  the CORE_MCP_FULL branch. Removes the duplicates so the extended
  registration list mirrors the always-on list exactly once.
- Switches `agentic_prep_workspace` from bare `mcp.AddTool` to
  `AddToolRecorded` so prep-workspace participates in the same
  accounting as every other RFC §6 tool.

TestPrep_RegisterTools_Good_RegistersCompletionTool now asserts all
three `agentic_auth_*` tools surface, covering the new login registration
alongside provision/revoke.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 20:27:44 +01:00
Snider
b338e12fbf fix(agent): process action overrides survive ServiceStartup
go-process's OnStartup re-registers process.start/run/kill with
string-ID variants, clobbering the agent's custom handlers that return
*process.Process. This broke pid/queue helpers and 7 tests that need
the rich handle (TestPid_ProcessAlive_Good, TestQueue_CanDispatchAgent_Bad_AgentAtLimit,
etc). Register a Startable override service that reapplies the agent
handlers after every service finishes OnStartup — since services run in
registration order, "agentic.process-overrides" always runs last and
wins.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 18:24:47 +01:00
Snider
30cc4239d8 refactor(agent): runtimeAvailable uses core/process primitive
Replace os/exec.LookPath with process.Program.Find() — keeps dispatch
runtime detection in line with the repo's process-execution convention
and removes the os/exec import from pkg/agentic/dispatch.go.

Convergence-pass from spark-medium — no new features found on this
sample, confirms core/agent and go-store RFC parity is complete.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 14:21:09 +01:00
Snider
5ef2aba27b fix(agent): workspace prep falls back to GOWORK search
runWorkspaceLanguagePrep now appends `GOWORK=` (empty) to the env passed
to `go work sync` so inherited `GOWORK=off` from a test runner or CI
environment doesn't short-circuit the workspace lookup. The extracted
workspace template includes a go.work referencing ./repo; without this
override the sync fails even though the file is right there.

Converged pass — no new features found this sample.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 14:13:02 +01:00
Snider
2fc0de321d feat(agent): RFC §15.5 orphan QA buffer recovery on startup
Adds `recoverStateOrphans` per RFC §15.5 — startup scans `.core/state/`
for leftover QA workspace buffers from dispatches that crashed before
commit, and discards them so partial cycles do not poison the diff
history described in RFC §7.

- `statestore.go` — new `recoverStateOrphans` wrapper around go-store's
  `RecoverOrphans("")` so the agent inherits the store's configured
  state directory
- `prep.go` — wires the recovery into OnStartup immediately after
  `hydrateWorkspaces` so the registry, queue, and buffers all come back
  into a consistent state on restart
- `statestore_test.go` — Good/Bad/Ugly coverage, includes the cwd
  redirect guard so the go-store default relative path cannot leak test
  artefacts into the package working tree

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 13:51:54 +01:00
Snider
03e5934607 feat(agent): RFC §15.5 parent workspace stats store
Adds `.core/workspace/db.duckdb` — the permanent record of dispatch
cycles described in RFC §15.5. Stats rows persist BEFORE workspace
directories are deleted so "what happened in the last 50 dispatches"
queries survive cleanup and sync drain.

- `workspace_stats.go` — lazy go-store handle for the parent stats DB,
  build/record/filter/list helpers, report payload projection
- `commit.go` — writes a stats row as part of the completion pipeline so
  every committed dispatch carries forward into the permanent record
- `commands_workspace.go` — `workspace/clean` captures stats before
  deleting, new `workspace/stats` command + `agentic.workspace.stats`
  action answer the spec's "query on the parent" use case

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 13:41:07 +01:00
Snider
364655662a feat(agent): RFC §7 Post-Run Analysis — diff + cluster dispatch findings
Extends DispatchReport with the three RFC §7 diff lists (New, Resolved,
Persistent) and a Clusters list that groups findings by tool/severity/
category/rule_id. runQAWithReport now queries the SQLite journal for up
to persistentThreshold previous cycles of the same workspace, computes
the diff against the current cycle, and populates .meta/report.json
before ws.Commit(). The full findings payload is also pushed to the
journal via CommitToJournal so later cycles have findings-level data
to compare against (workspace.Commit only stores aggregated counts).

Matches RFC §7 Post-Run Analysis without pulling in Poindexter as a
direct dependency — uses straightforward deterministic clustering so
agent stays inside the core/go-* dependency tier.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 13:19:34 +01:00
Snider
eaf17823d9 feat(agent): RFC §7 QA capture pipeline
The runQA handler now captures every lint finding, tool run, build, vet
and test result into a go-store workspace buffer and commits the cycle
to the journal. Intelligence survives in the report and the journal per
RFC §7 Completion Pipeline.

- qa.go: QAFinding / QAToolRun / QASummary / QAReport DTOs mirroring
  lint.Report shape; DispatchReport struct written to .meta/report.json;
  runQAWithReport opens NewWorkspace("qa-<workspace>"), invokes
  core-lint run --output json via c.Process().RunIn(), records every
  finding + tool + stage result, then commits
- runQALegacy preserved for graceful degradation when go-store is
  unavailable (RFC §15.6)
- dispatch.go: runQA now delegates to runQAWithReport, bool contract
  unchanged for existing call sites
- qa_test.go: Good/Bad/Ugly triads per repo convention

Poindexter clustering from RFC §7 Post-Run Analysis remains open —
needs its own RFC pass for the package boundary.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 13:02:14 +01:00
Snider
eed2274746 feat(agent): pairing-code login per RFC §9 Fleet Mode
Implements `core login CODE` — exchanges a 6-digit pairing code generated
at app.lthn.ai/device for an AgentApiKey, persisted to ~/.claude/brain.key.
Pairing code is the proof, so the POST is unauthenticated.

- auth.go: AuthLoginInput/Output DTOs + handleAuthLogin handler
- commands_platform.go: login / auth/login / agentic:login CLI commands
  with cmdAuthLogin persisting the returned key
- prep.go: registered agentic.auth.login / agent.auth.login actions
- auth_test.go / commands_platform_test.go / prep_test.go: Good/Bad/Ugly
  triads per repo convention, including key persistence verification

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 12:51:17 +01:00
Snider
716546d0d5 feat(agent): workspace state mirror + ghost reap + sync queue via go-store
- prep.go TrackWorkspace mirrors into queue + concurrency store groups
  (previously only registry); hydrateWorkspaces reaps filesystem ghosts
  (dead PID → failed, persisted back to status.json) so cmdStatus and
  out-of-process consumers see coherent state (RFC §15.3)
- sync.go queue read/write goes through go-store first per RFC §16.5
  ("Queue persists across restarts in db.duckdb"), file remains fallback
  for graceful degradation
- statestore.go stateStoreGet helper for go-store-first reads
- tests/cli/restart — new CLI test for RFC §15.7 "dispatch → kill →
  restart → no ghost agents" dead-PID reap flow
- 4 new statestore tests: queue group mirror, concurrency refresh,
  sync queue persistence, fs ghost reap with disk write-back

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 12:36:44 +01:00
Snider
4684ae725a feat(agent): go-store backing for dispatch state per RFC §15
Introduce an optional go-store persistence layer for the three state
groups described in RFC §15.3 — queue, concurrency, registry — plus
runtime_state and dispatch_history used by the sync pipeline.

- statestore.go lazily opens `.core/db.duckdb` via go-store when
  available; nil-safe helpers return cleanly so in-memory/file-based
  fallbacks survive when the store cannot open (graceful degradation,
  RFC §15.6)
- prep.go tracks the store reference on the subsystem and closes it on
  shutdown; hydrateWorkspaces now consults the registry group before
  the filesystem scan so ghost agents are marked failed across
  restarts, and TrackWorkspace mirrors updates back into the cache
- runtime_state.go persists backoff + fail-count snapshots into the
  go-store runtime group so dispatch backoff survives restarts even
  when the JSON file rotates
- commit.go writes the completed dispatch record into dispatch_history
  for RFC §16.3 sync push to drain without rescanning workspaces
- statestore_test.go covers lazy-once init, restore/delete round trip,
  ghost-agent failure marking, and runtime-state replay across
  subsystem instances

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 12:17:08 +01:00
Snider
83364a6080 feat(agent): sync backoff + ledger + auto-flush loop
- sync.go: syncBackoffSchedule (1s/5s/15s/60s/5min) with per-push Attempts
  and NextAttempt honoured on retry (RFC §16.5)
- runSyncFlushLoop: ticks every minute from OnStartup when API key present,
  drains the queue without re-scanning workspaces
- SyncPushInput.QueueOnly: lets flush loop drain without triggering a full
  workspace scan (prevents duplicate pushes)
- Sync ledger at .core/sync/ledger.json: fingerprints keyed by workspace
  name + (updated_at, runs); skips already-synced workspaces until fresh
  activity
- docs/RFC-AGENT.md: synced from plans/code/core/agent/RFC.md with latest
  AgentPlan status enum, complete capability, pr.close/branch.delete,
  indexed_at/org brain fields

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 12:06:04 +01:00
Snider
edfcb1bdfe feat(agent): unblock factory dispatch, runtime-aware containers, RFC gaps
- paths.go: resolve relative workspace_root against $HOME/Code so workspaces
  land in the conventional location regardless of launch cwd (MCP stdio vs CLI)
- dispatch.go: container mounts use /home/agent (matches DEV_USER), plus
  runtime-aware dispatch (apple/docker/podman) with GPU toggle per RFC §15.5
- queue.go / runner/queue.go: DispatchConfig adds Runtime/Image/GPU fields;
  AgentIdentity parsing for the agents: block (RFC §10/§11)
- pr.go / commands_forge.go / actions.go: agentic_delete_branch tool +
  branch/delete CLI (RFC §7)
- brain/tools.go / provider.go: Org + IndexedAt fields on Memory (RFC §4)
- config/agents.yaml: document new dispatch fields, fix identity table
- tests: dispatch_runtime_test.go (21), expanded pr_test.go + queue_test.go,
  new CLI fixtures for branch/delete and pr/list

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-14 11:45:09 +01:00
Snider
db6d06ae2b merge: integrate forge dispatch + mcp changes with AX compliance sweep
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-13 09:39:41 +01:00
Snider
39914fbf14 refactor: AX compliance sweep — replace banned stdlib imports with core primitives
Replaced fmt, strings, sort, os, io, sync, encoding/json, path/filepath,
errors, log, reflect with core.Sprintf, core.E, core.Contains, core.Trim,
core.Split, core.Join, core.JoinPath, slices.Sort, c.Fs(), c.Lock(),
core.JSONMarshal, core.ReadAll and other CoreGO v0.8.0 primitives.

Framework boundary exceptions preserved where stdlib types are required
by external interfaces (Gin, net/http, CGo, Wails, bubbletea).

Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-13 09:32:00 +01:00