Commit Graph

1594 Commits

Author SHA1 Message Date
Harshit Singh Bhandari c343c55c14
fix: 7 bugs from discussion #149 smoke walk (envelope, spawn, CDC, observer) (#153)
* fix(cdc): emit pr_review_thread_resolved on replace polls (#152 bug 5)

writePRRows was DELETE-then-UPSERT on the Replace path, so every poll's
upserts hit the INSERT branch and the AFTER UPDATE trigger that emits
pr_review_thread_resolved never fired in production. Replaces the
blanket delete with a set-diff: upsert observed threads first (so
unchanged thread_ids go through ON CONFLICT DO UPDATE and fire the
UPDATE trigger when resolved flips), then delete orphans whose
thread_id is not in the observed set, all inside the existing tx.

Adds DeletePRReviewThread query (sqlc-generated form hand-edited; no
sqlc binary available locally — sqlc generate from backend/ produces an
identical file).

Tests: TestPRReviewThreadsCDC_EmitsResolvedOnReplacePoll (regression —
fails without fix) and TestPRReviewThreadsReplace_PrunesOrphansWithoutReinserting.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(observe): emit scm-disabled log on startup with no subjects (#152 bug 7)

checkCredentials lived only inside Poll, which short-circuits when
discoverSubjects is empty. On a fresh daemon with no tracked PRs the
documented "scm observer disabled: provider credentials unavailable"
warn was unreachable, leaving users with no signal that the SCM
observer was a no-op.

Calls checkCredentials once in Observer.loop before the first Poll.
The existing credentialsChecked guard preserves once-per-process
semantics; provider construction still uses SkipTokenPreflight so
daemon readiness doesn't block on gh.

Test: TestStart_LogsDisabledWarningWhenNoTokenAndNoSubjects with a
race-safe syncBuffer for capturing slog from the observer goroutine.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(api,spawn): typed errors + project/branch/binary preflight (#152 bugs 1-4,6)

Closes the long tail of opaque-500-and-orphan-row failures that
discussion #149's smoke walk surfaced. The common shape: spawn created
the session row before validating preconditions, and the underlying
errors weren't typed, so toAPIError defaulted to INTERNAL_ERROR.

Bug 1 (orphan row + opaque 500 on unknown projectId):
Service.Spawn / SpawnOrchestrator now call store.GetProject first and
return apierr.NotFound("PROJECT_NOT_FOUND", ...) before manager.Spawn,
eliminating the create-row-then-fail-workspace ordering.

Bug 2 (Restore opaque 500 on half-spawned/terminated session):
Manager.Restore gained the ErrIncompleteHandle guard that Kill has at
manager.go:189-193. toAPIError now maps both restore and kill to the
same SESSION_INCOMPLETE_HANDLE 409 envelope.

Bug 3 (--branch unfetched / checked-out-elsewhere → opaque 500):
gitworktree pre-checks listRecords for branch-in-other-worktree, falls
back to refs/tags on missing local/remote head, and emits two new port
sentinels (ErrWorkspaceBranchCheckedOutElsewhere,
ErrWorkspaceBranchNotFetched) mapped to BRANCH_CHECKED_OUT_ELSEWHERE
(409) and BRANCH_NOT_FETCHED (400).

Bug 4 (orphan terminated row on claim-pr rollback):
Adds Store.DeleteSession gated to seed-state rows only (preserves the
no-resurrection guarantee for live sessions), transactional change_log
cleanup, Manager.RollbackSpawn (delete-then-fallback-to-kill), a new
POST /sessions/{id}/rollback endpoint, and rewires
cli/spawn.rollbackSpawnedSession to use it. The exit-0 sub-symptom was
unreproducible from current source and is left unaddressed.

Bug 6 (agent binary not on PATH → silent idle session):
Drops the "return name, nil" anti-pattern from all 21 agent adapters
and returns the new ports.ErrAgentBinaryNotFound on exec.LookPath miss.
Manager.Spawn gained a validateAgentBinary pre-flight (with injectable
LookPath so tests don't need real binaries on PATH) that aborts before
runtime.Create. Mapped to AGENT_BINARY_NOT_FOUND (400). Integration
tests in internal/integration/ stub LookPath to /usr/bin/true.

Tests cover each bug end-to-end. OpenAPI regenerated for /rollback.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* chore: gofmt + regen frontend schema.ts for /rollback

CI fixes for #153:
- gofmt/goimports on kilocode and kiro adapters that the bug 6 audit
  left mis-grouped.
- openapi-typescript regen against the new /rollback endpoint added in
  the Lane A commit.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(store): guard change_log delete behind seed probe + regen sqlc (#152, PR #153 review)

Addresses @greptile-apps P1 and P2 review feedback on PR #153.

P1 (CDC events deleted for live sessions in rollback fallback):
DeleteChangeLogForSession ran unconditionally inside the transaction
before DeleteSeedSession's seed-state predicates filtered the session
delete to a no-op. For a live session reaching DeleteSession (the
delete-then-kill fallback path inside RollbackSpawn), the seed delete
returned 0 rows but the session_created/session_updated CDC events
had already been purged. Now probes via a new SessionIsSeed query
first and short-circuits the whole tx — including the change_log
cleanup — when the row is not in seed state.

P2 (regen sqlc): installed sqlc 1.31.1 and ran `sqlc generate` from
backend/, replacing the hand-edited pr_review_threads.sql.go (and
producing minor format-only churn in models.go, pr.sql.go,
sessions.sql.go, changelog.sql.go).

The regen surfaced two issues:

1. GetPR / ListPRsBySession had their return types hand-changed to
   gen.PR by the previous PR; sqlc actually emits GetPRRow /
   ListPRsBySessionRow when queries enumerate columns. Fixed by
   collapsing those two queries to `SELECT * FROM pr` so sqlc returns
   gen.PR (which is what the store's prRowFromGen converter expects),
   and pr.last_nudge_signature now lands in the result alongside the
   existing 37 columns.

2. sqlc 1.31.1's SQLite parser silently strips trailing `?`
   placeholders and string literals from DELETE statements (reproduced
   with sqlc.arg, IFNULL, rowid subquery, and second-predicate
   workarounds — all eaten). DeleteSeedSession and
   DeleteChangeLogForSession both tripped it. They are now run as
   plain tx.ExecContext calls inside Store.DeleteSession, inside the
   same write transaction as SessionIsSeed; both queries are removed
   from the queries/ directory and the workaround context is
   documented inline in queries/sessions.sql and queries/changelog.sql
   to keep future contributors from re-adding them.

Verified: go build ./... clean, go test -race ./... 1097/1097 pass.
2026-06-07 07:35:46 +05:30
Harshit Singh Bhandari c7e3a0336e
ci(frontend): add react-doctor check for landing site (#151)
* ci(frontend): add react-doctor check for landing site

Adds a CI job that runs react-doctor (https://github.com/millionco/react-doctor)
against the Next.js 15 + React 19 landing site at frontend/src/landing/.
The landing has 29 .tsx components and no existing lint coverage; the only
prior frontend CI was a schema.ts drift check in go.yml.

- New workflow .github/workflows/react-doctor.yml, path-filtered to
  frontend/src/landing/** so backend-only PRs don't pay for it.
- doctor script + react-doctor devDep added to the landing package.
- Default --blocking=error: surfaces security, bugs, perf, a11y, and
  maintainability findings without failing CI on existing warnings
  (current baseline: 0 errors, 58 warnings, ~5s locally).
- Runs with --no-telemetry so CI runners don't ping react.doctor.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* ci(frontend): also scope react-doctor push trigger to landing paths

Mirrors the PR path filter on push to main so backend-only merges don't
re-run the landing check. Unlike go.yml/cli-e2e.yml (which trigger on
broad path sets), this workflow only cares about frontend/src/landing/.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* ci(frontend): use react-doctor GitHub Action, drop devDep + lockfile churn

Replaces the npm install + npm run doctor approach with the official
millionco/react-doctor@v2 composite action. The action manages its own
Node setup and react-doctor install on the runner, so the landing
package.json and lockfile stay untouched (no transitive-dep bloat from
react-doctor's 479-package tree).

The action also wires up sticky PR summary comments, inline review
comments, and commit statuses out of the box — requires pull-requests
and statuses write perms.
2026-06-07 07:11:35 +05:30
Harshit Singh Bhandari 9dedae905f
feat(agents): add remaining 15 adapters (droid, amp, agy, crush, aider, goose, auggie, continue, devin, cline, kiro, kilocode, vibe, pi, autohand) (#150)
* feat(agents): add droid adapter

Registers the droid harness, stacked on the agent platform. Includes its own activity deriver.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(agents): add amp adapter

Registers the amp harness, stacked on the agent platform.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(agents): add agy adapter

Registers the agy harness, stacked on the agent platform. Includes its own activity deriver.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(agents): add crush, aider, goose, auggie, continue, devin, cline, kiro, kilocode, vibe, pi, autohand adapters

Cherry-pick batch landing the remaining 12 yyovil adapter directories per
Discussion #148 recipe, on top of #145 (grok/cursor/qwen/copilot/kimi) and
the droid/amp/agy commits earlier on this branch. Each adapter is a
self-contained package under backend/internal/adapters/agent/<name>/;
registry.Constructors(), activitydispatch.Derivers (for adapters with
activity.go), and wiring_test.go are unified to register all 23 shipped
adapters in one place. No new migration: 0007_allow_implemented_harnesses
already widens the sessions.harness CHECK to cover every adapter.

* fix(agents/kilocode): return error from json.Marshal of permission config

Previously the marshal error was discarded and the function returned a
prefix carrying an empty KILO_CONFIG_CONTENT. An unrecoverable marshal
failure for the typed map should never happen in practice, but if it ever
did, Kilo would silently launch with default permissions regardless of
the requested mode. Surface it as "no prefix" so the caller's mode choice
can't be misrepresented.

---------

Co-authored-by: yyovil <itsyyovil@gmail.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 03:46:52 +05:30
Harshit Singh Bhandari 95f8b421ff
docs: refresh README to reflect current main (#147) 2026-06-07 01:42:58 +05:30
Harshit Singh Bhandari b13f413515
feat(agents): add grok, cursor, qwen, copilot, kimi adapters (#145)
* feat(agents): add grok adapter

Registers the grok harness (xAI Grok CLI). grok installs Claude Code-compatible
hooks, so it reuses the claude-code activity deriver already in the platform.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(agents): add cursor adapter

Registers the cursor harness, stacked on the agent platform. Includes its own activity deriver.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(agents): add qwen adapter

Registers the qwen harness, stacked on the agent platform. Includes its own activity deriver.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(agents): add copilot adapter (#128)

* feat(agents): add copilot adapter

Registers the copilot harness, stacked on the agent platform. Includes its own activity deriver.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Update backend/internal/adapters/agent/copilot/hooks.go

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix(copilot): map permission-request to documented preToolUse event

Copilot CLI does not document a "permissionRequest" hook event. Per
https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/use-hooks
the documented camelCase events are sessionStart, sessionEnd,
userPromptSubmitted, preToolUse, postToolUse, errorOccurred, agentStop.
Writing "permissionRequest" into .github/hooks/ao.json silently disables
that hook because Copilot does not recognize the key.

Remap AO's permission-request sub-command onto preToolUse (the closest
documented signal — fires before any tool invocation, including ones
that would prompt for approval) and add a tripwire test asserting the
JSON keys AO writes match the documented camelCase names.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* chore(copilot): gofmt the new tripwire test

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Harshit Singh Bhandari <dev@theharshitsingh.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Co-authored-by: harshitsinghbhandari <24b4506@iitb.ac.in>

* feat(agents): add kimi adapter

Registers the kimi harness, stacked on the agent platform.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(agents/kimi): drop approval flags on -p and --session paths

Kimi rejects `--prompt` combined with `--yolo`/`--auto`/`--plan`, and
rejects `--yolo`/`--auto` combined with `--session`/`--continue`
(non-interactive and resumed sessions inherit the auto permission
policy). The previous mapping appended one of those flags before `-p`
on every launch and before `--session` on every restore, so every
non-interactive launch would fail at startup. The local binary
(v1.37.0) additionally has no `--auto` option at all, which would
fail even on otherwise-permissible paths.

- GetLaunchCommand: emit approval flags only on the interactive path
  (no prompt). The `-p <prompt>` path is now bare.
- GetRestoreCommand: never emit approval flags; resumed sessions
  inherit the original session's approval settings.
- Tests assert no approval/plan flag leaks onto either path for any
  PermissionMode, and keep the interactive mapping unchanged.

Refs: https://moonshotai.github.io/kimi-code/en/reference/kimi-command.html

* fix(agents/qwen): sync hook settings temp file

* fix(agents/grok): delegate hook cleanup lifecycle

---------

Co-authored-by: yyovil <itsyyovil@gmail.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-06-07 01:17:53 +05:30
yyovil 3152cdc948
feat(agents): agent platform — registry, activity hooks, harness allowlist (#119)
Introduces the shared platform that per-agent adapters plug into, wired for the
three shipped harnesses (claude-code, codex, opencode):

- adapters/agent/registry: single source of truth for shipped adapters
  (Constructors), consumed by the daemon to resolve a session's harness.
- adapters/agent/activitydispatch + 'ao hooks' command: maps an agent's native
  hook callbacks onto AO activity states (active/idle/waiting/...).
- claudecode/codex/opencode: emit SessionStart/UserPromptSubmit/Stop activity.
- HTTP + OpenAPI: report session activity state.
- db: single migration widening sessions.harness to all shipped harnesses, so
  adding an adapter needs no further migration.
- domain: harness constants + --agent alias for 'ao spawn'.

Adding a new agent is now one adapter package plus a line in Constructors().

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Harshit Singh Bhandari <claudeagain@pkarnal.com>
2026-06-07 00:52:40 +05:30
yyovil 3c7344b233
[codex] add ao hooks activity command (#113)
* feat: add ao hooks activity command

* fix(activity): address review nits

- lcm: sameActivity ignores LastActivityAt so same-state repeats no-op
  and don't churn UpdatedAt / CDC events.
- cli/hooks: surface stdin read errors to stderr for parity with the
  daemon-error path; still exit 0 so a failed hook can't break the agent.
- claudecode: GetAgentHooks docstring covers Notification + SessionEnd
  (the slice already included them; only the comment was stale).

---------

Co-authored-by: harshitsinghbhandari <dev@theharshitsingh.com>
2026-06-06 20:29:00 +05:30
Vaibhaav Tiwari a9b08cd368
feat(cdc): add SSE event stream replay (#106)
* feat(cdc): add SSE event stream replay

* fix(cdc): document SSE route registration

* test(httpd): cover SSE dedupe and Last-Event-ID cursor paths

Two gaps in events_test.go coverage:

- TestEventsStreamDeduplicatesLiveEventOverlappingReplay: a live event whose
  seq falls within the already-replayed range must be silently dropped by
  writeSSEEvent so the client sees each seq exactly once. Publishes seq=5
  (duplicate of replay) and seq=6 (new) into the live buffer before replay
  returns; asserts the client receives [5,6], not [5,5,6].

- TestEventsStreamParsesLastEventIDHeader: Last-Event-ID header must be used
  as the replay cursor when the after query param is absent. Source returns
  after+1, so receiving seq=8 proves the header was parsed as 7.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: regenerate schema.ts for GET /api/v1/events

Regenerated with npm run api after merging the OpenAPI spec generation
tooling from main. Adds the streamEvents operation and its after cursor
parameter to the TypeScript API types.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: harden SSE event stream headers

---------

Co-authored-by: Vaibhaav <user@example.com>
Co-authored-by: Pritom14 <pritommazumdar1995@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-06 19:32:21 +05:30
Harshit Singh Bhandari 3413acca33
feat: ao session claim-pr + spawn --claim-pr wiring (#101)
* feat: add session PR claiming CLI and API

* fix: tighten PR claim rollback and CDC facts

* fix: align PR claim branch with latest main
2026-06-06 00:01:03 +05:30
Harshit Singh Bhandari 378addf4a0
test(scm): end-to-end integration coverage for SCM observer (#109) (#115)
* test(scm): end-to-end integration coverage for SCM observer (#109)

Adds backend/internal/integration/scm_observer_test.go, the regression
guard for the SCM observer wiring landed in PR #114. Drives
scmobserve.Observer.Poll against a real sqlite.Store, a real
lifecycle.Manager with a recording messenger spy, and a canned
observe/scm.Provider, asserting the full observation -> reducer ->
store -> messenger pipeline.

Three table-driven subtests, each on its own tmpdir fixture:

- A CI-failing observation persists the pr row (provider-neutral
  columns + semantic hashes), persists pr_checks mirroring the
  observation, delivers exactly one nudge with the failed-log tail,
  persists last_nudge_signature, and produces no additional nudge on
  an identical re-poll.
- A Merged: true observation MarkTerminated's the session and sends
  no nudge.
- A branch with no open PR writes nothing and sends no nudge.

Closes #109

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(scm): address review — drop string key indirection, document idempotency path

- Key cannedSCMProvider.observations/reviews by PR number directly so
  the fake no longer carries a string key that resembled (but did not
  actually need to mirror) the observer's internal prKey. Every case
  in this test uses scmTestRepo, so number alone is unambiguous.
- Add an explicit pointer in the CI-failing subtest noting it
  exercises the hash-match short-circuit in prepareForPersistence;
  the ETag-driven 304 short-circuit on the same SHA is covered by
  observe/scm/observer_test.go (Poll_RepoETag304SkipsDetectPR,
  Poll_CIETagChangeRefreshesWhenRepoUnchanged).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-05 23:46:38 +05:30
Harshit Singh Bhandari bfb6e9860b
feat(scm): wire observer messenger + RepoOriginURL + persist dedup (#108) (#114)
* feat(daemon): thread runtime messenger into Lifecycle Manager (#108)

The daemon used to construct the LCM with a nil messenger, so every
SCM-driven nudge dropped silently inside sendOnce. Move newSessionMessenger
above startLifecycle and pass the real messenger through, so CI-failure,
review-feedback, and merge-conflict nudges actually reach the agent.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(project): populate RepoOriginURL at add + lazy observer backfill (#108)

project.Add now shells out to `git -C path remote get-url origin` and
captures the result on the new project row, so the SCM observer can parse
it on the first poll. A missing remote falls back to "" rather than failing
project add — non-git roots and remoteless repos stay registerable.

To cover projects added before this change, the observer's discoverSubjects
lazily backfills RepoOriginURL via the same shell-out and persists it
through UpsertProject, so subsequent polls skip the fork-exec.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(lifecycle): persist reaction-dedup signatures across restart (#108)

Add migration 0005 with `pr.last_nudge_signature TEXT NOT NULL DEFAULT ''`
and two scoped sqlc queries (Get/UpdatePRLastNudgeSignature). Lifecycle
serialises the per-PR slice of its seen/attempts maps to that column as a
small JSON document; sendOnce loads it lazily on first touch of each PR
and persists after every successful send.

This closes the post-restart re-nudge gap: the daemon used to lose the
seen map on bounce, so a still-failing CI re-prompted the agent on the
first post-restart observer poll even when it had already been told.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(lifecycle): silence nilerr on intentional corrupt-payload swallow

golangci-lint's nilerr flagged the `if err := json.Unmarshal(...); err != nil { return nil }`
path in loadPRSignaturesLocked. The swallow is deliberate (a corrupt persisted
payload should not crash the lifecycle write path), so compare against nil
directly so no `err` is bound and the lint goes quiet.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: silence nilerr, address reviewer notes, drop task-tagged comments

- reactions.go: discard the json.Unmarshal error explicitly via `_ =` so
  golangci-lint's nilerr stops flagging the intentional corrupt-payload
  swallow; behavior unchanged.
- reactions.go: document the Send → memory → persist order in sendOnce so
  the "one extra nudge on restart after a transient persist failure"
  trade-off is explicit (vs. the inverse risk of losing a real nudge).
- service.go: stop reaching for slog.Default() in resolveGitOriginURL;
  align with the observer's identical helper that just returns "" on git
  failure rather than logging through the global logger.
- tests: drop "issue #108" / "guards the regression from #X" framing in
  test docstrings — explain WHAT the test asserts, not the PR context.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-05 23:20:02 +05:30
neversettle 6da5d93241
feat: automate OpenAPI spec + frontend TS type generation (issue #102) (#103)
* feat: add npm run api scripts and document API contract change flow

Adds three root package.json scripts mirroring the sqlc convention:
- api:spec — runs go generate to regenerate openapi.yaml
- api:ts   — runs openapi-typescript@7.4.4 to generate frontend/src/api/schema.ts
- api      — runs both in sequence (the single contributor command)

Documents the full flow in a new AGENTS.md "API contract changes" section
so contributors know which files to edit, how to regenerate, and what to
verify. Implements slice 1 of issue #102.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: correct paths in AGENTS.md API contract changes section

- api:ts equivalent command: use full relative path
  backend/internal/httpd/apispec/openapi.yaml, not bare openapi.yaml
- verify command: prefix with `cd backend &&` so it works from repo root

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: add CI drift guard for OpenAPI spec and frontend TS types

- Adds api-drift job to go.yml: regenerates openapi.yaml + schema.ts
  via `npm run api`, then fails if git diff detects any change
- Expands go.yml path filter to trigger on package.json and schema.ts
- Commits initial schema.ts generated from the current spec
- Notes the CI guard in AGENTS.md API contract changes section

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address review feedback on api-drift CI job

- Scope git diff to schema.ts only; openapi.yaml drift is already
  caught by TestBuild_MatchesEmbedded in the build-test Go job
- Add npm ci step so openapi-typescript is installed from the lockfile
  rather than re-fetched by npx on every run
- Move openapi-typescript from npx -y to a pinned devDependency
  (exact 7.4.4, no caret) with a committed package-lock.json
- Note in AGENTS.md Verify block that go test does not cover schema.ts drift

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 14:45:10 +05:30
Adil Shaikh 19b6ca5093
feat: add provider-neutral SCM observer (#76)
* feat: add provider-neutral scm observer

* fix: satisfy scm batch query lint

* fix: avoid scm token preflight on startup

* fix: bound github scm review refresh

* docs: clarify scm observer fields

* fix: gate scm observer credentials lazily

* fix: preserve scm review threads in legacy pr writes

* fix: harden scm observer state refresh

* fix: retry scm lifecycle after persistence

* fix: persist scm lifecycle acknowledgement cursor

* fix: tune scm graphql pagination

* chore: remove scm observer no-op code

* fix: tighten scm bot and log-tail handling

* fix(scm): emit CDC events for pr_review_threads

* fix(db): renumber scm observer migration

* fix: preserve cdc triggers during scm migration

* fix: preserve scm comments across legacy writes

* fix: retry transient scm credential checks

* fix: preserve review rows during lifecycle ack

* fix: harden scm observer review follow-ups

---------

Co-authored-by: harshitsinghbhandari <24b4506@iitb.ac.in>
2026-06-04 22:26:07 +05:30
Dhruv Sharma d623ab28b7
docs: document backend code structure (#41) 2026-06-04 02:32:18 +05:30
Dhruv Sharma 86f3f0880c
docs: document AO technical stack (#25)
* docs: document AO technical stack

* docs: update stack decisions from review
2026-06-04 02:24:19 +05:30
codebanditssss b40d7bcf04 fix: suppress hydration warning on html for theme class 2026-06-03 22:15:52 +05:30
codebanditssss a8b5b6cf02 feat: add docs routes and layout 2026-06-03 22:12:25 +05:30
codebanditssss b3ed10a5ae feat: add docs source loader and mdx components 2026-06-03 22:12:25 +05:30
codebanditssss 9242868b5a docs: add documentation content pages 2026-06-03 22:12:25 +05:30
codebanditssss 66a3490aa6 chore: add remaining docs logo assets 2026-06-03 22:12:25 +05:30
codebanditssss e10e9f17e7 chore: add fumadocs setup and config for docs 2026-06-03 22:12:25 +05:30
codebanditssss 93f904e429 feat: wire up landing page routes and layout 2026-06-03 21:57:38 +05:30
codebanditssss d0c053e99e feat: add landing page section components 2026-06-03 21:57:38 +05:30
codebanditssss fbaa6d17a5 feat: add github repo stats helper 2026-06-03 21:57:38 +05:30
codebanditssss c74fefbaf5 chore: add landing page images and agent logos 2026-06-03 21:57:38 +05:30
codebanditssss e1d7ce6b0f style: add landing design tokens and global styles 2026-06-03 21:57:38 +05:30
codebanditssss 71e05dce4a chore: scaffold next.js and tailwind for landing page 2026-06-03 21:57:38 +05:30
codebanditssss 0ffe7145f5 chore: add gitignore for landing build artifacts 2026-06-03 21:57:38 +05:30
neversettle 7880f59cf5
refactor(backend): LLD maintainability fixes in controllers/service layers (#95) (#96)
* refactor(backend): LLD maintainability fixes in controllers/service layers

Addresses the high + medium severity findings from the LLD review of
backend/internal/httpd and backend/internal/service (#95):

1. Controllers no longer import internal/session_manager. Session sentinel
   errors are now *domain.ServiceError values carrying their own HTTP mapping,
   so the controller translates them with one generic errors.As — no
   cross-package sentinel imports.
2. One error pattern across services: project.Error is now an alias of the
   shared domain.ServiceError, and session_manager sentinels use it too. A
   single writeServiceError replaces the per-resource error switches.
3. Clean-orchestrator business logic moved out of the controller into
   session.Service.SpawnOrchestrator(ctx, projectID, clean).
4. isGitRepo no longer treats case-different paths as equal on case-sensitive
   filesystems; case-insensitive compare is gated to darwin/windows via samePath.
5. Project repo check sits behind an injectable GitChecker, so the service is
   testable without a real git binary.
6. httpd exports only the production constructors (NewWithDeps,
   NewRouterWithControl); the 3 test-only wrappers are removed and the
   "router with empty deps" convenience moved to an unexported test helper.

Closes #95

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor(backend): standardize service errors on internal/httpd/errors

Replace the domain.ServiceError approach with a REST-API-scoped error package
and a single envelope renderer, per review feedback:

- Add internal/httpd/errors (package errors, aliased apierr): one structured
  Error type with semantic Kinds (Internal/Invalid/NotFound/Conflict) and
  constructors. Imports nothing, so any layer can depend on it.
- envelope.WriteError is now the single path from a service error to the wire
  APIError, and the only place a Kind becomes an HTTP status/word. The
  per-resource writeProjectError/writeSessionError translators are gone.
- Delete domain/errors.go (keeps domain pure of HTTP-flavored kinds) and
  service/project/errors.go (no per-service error files); services build
  errors inline via apierr constructors.
- session_manager sentinels are apierr.Error values (pointer identity still
  works with errors.Is).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* revert(backend): drop GitChecker seam and isGitRepo case-sensitivity change

Defer findings #4 (isGitRepo case-sensitivity) and #5 (GitChecker seam) out
of this PR. Restores the original exec-based isGitRepo and the New(store)
constructor; removes git.go, git_test.go, and the test-only export shims. The
error-standardization and other findings are unaffected.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor(session): translate engine errors to API errors at the facade

The session_manager is the internal command engine and must not depend on the
REST API error vocabulary. Revert its sentinels to plain errors.New values and
move the engine→API translation into the service/session facade (toAPIError),
which is the correct boundary. Controllers still see apierr.Error and never
import the engine; the engine no longer imports internal/httpd/errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* docs(session): tighten error comments to state what the code does

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* style(envelope): make KindInternal an explicit case in httpStatus

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor(apierr): rename package, test SpawnOrchestrator, parity fixes

Address review feedback on PR #96:
- Rename internal/httpd/errors → internal/httpd/apierr (package apierr) so
  importers no longer alias around the stdlib errors package.
- Add a commander seam to session.Service and unit-test the relocated
  clean-orchestrator rule: clean=true kills all active orchestrators before
  spawning; clean=false spawns without kills.
- project.Add: wrap the UpsertProject store error in apierr.Internal for parity
  with its sibling paths (was a raw 500).
- Document that KindInternal is iota's zero value, so a zero-value Error
  defaults to 500.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 18:09:02 +05:30
yyovil e25b2ad4de
feat(agent): opencode adapter + activity plugin hooks (#80)
* feat(agent): add opencode adapter + activity plugin hooks

Add an opencode (sst/opencode) agent adapter implementing the 6-method
ports.Agent interface and register it in the daemon's agent resolver, so a
session with harness "opencode" spawns and restores a real opencode worker.

opencode diverges from the claude-code/codex adapters in two ways the adapter
bridges:

- No native command-hook config. Unlike Claude Code (.claude/settings.local.json)
  and Codex (.codex/hooks.json), opencode has no "run this command on event"
  config (see sst/opencode#5409). Its only lifecycle surface is a JS/TS plugin
  loaded from .opencode/plugins/. GetAgentHooks therefore //go:embeds an
  AO-owned plugin (assets/ao-activity.ts) and writes it atomically; install is an
  idempotent overwrite and uninstall is a sentinel-guarded delete, so
  user-authored plugins are never touched. The plugin maps opencode events onto
  AO's three normalized activity events: session.created -> session-start,
  message.updated/message.part.updated -> user-prompt-submit, and
  session.status(idle) -> stop (NOT the deprecated session.idle, which is
  unreliable under `opencode run`). It shells `ao hooks opencode <event>` via a
  guarded sh -c so a missing `ao` binary is a silent no-op.

- A single approval flag. opencode exposes only --dangerously-skip-permissions
  (no graduated accept-edits/auto) and no system-prompt flag, so those map to a
  bypass-only permission flag and a documented no-op for the system prompt
  (deferred to opencode's own config).

Launch uses the interactive TUI (`opencode --prompt <p>`); restore continues a
captured native session via `opencode --session <id>`.

opencode_test.go mirrors codex_test.go (12 tests) and the daemon wiring test now
asserts the opencode harness resolves.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(agent): address Greptile review on opencode adapter (#80)

- Dispatch all opencode plugin hooks synchronously (Bun.spawnSync). The
  session.created handler previously fired session-start via an async
  Bun.spawn; if opencode does not await the event handler, a following
  message.updated -> user-prompt-submit (sync) could complete before the
  in-flight async session-start, so AO would see the prompt before the session
  was registered. A sync spawn blocks opencode's single-threaded event loop, so
  events are now reported strictly in dispatch order. Removes the now-unused
  async callHook helper.
- Fix package/doc comments that said .opencode/plugin/ (singular) to match the
  plural .opencode/plugins/ the adapter actually writes to.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(agent): surface opencode hook failures instead of swallowing them

The activity plugin previously discarded every failure: callHookSync ignored
the subprocess exit code/stderr and both catch blocks were empty, so a failing
`ao hooks` invocation or a malformed event payload was completely invisible.

Now failures are reported through opencode's structured logger (client.app.log)
while still never crashing opencode:
- callHookSync pipes stderr and checks result.success; a non-zero exit (a real
  `ao hooks` failure — the `command -v ao` guard makes a missing binary exit 0)
  is logged with its exit code and stderr.
- spawn exceptions (e.g. no `sh`) are caught and logged.
- the event-handler catch logs the offending event type instead of swallowing.
- logHookFailure is itself best-effort (optional-chained, rejection swallowed),
  so logging can never throw back into opencode.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(agent): address opencode adapter review — install guard, prompt dedup, hook timeout

Maintainer review on #80 surfaced three pre-merge issues:

- GetAgentHooks could clobber a user file: install overwrote
  .opencode/plugins/ao-activity.ts unconditionally while uninstall was
  sentinel-guarded. Install now refuses (loud error) to overwrite a file that
  isn't AO-managed; absent/AO-managed targets still write idempotently.

- Empty-prompt report poisoned the dedup: message.updated fired
  user-prompt-submit with an empty prompt AND marked the message seen, so the
  text from the following message.part.updated was deduped away and never
  reached AO — breaking title-from-prompt. reportUserPrompt now reports at most
  twice: an optional early empty report (keeps run-mode flows active) that does
  NOT block a later text report, and a text report that is terminal.

- Bun.spawnSync had no timeout, so a hung `ao hooks` could block opencode
  indefinitely. Each spawn is now time-boxed at 30s, matching the claude-code
  and codex hook timeouts.

Adds TestGetAgentHooksRefusesToClobberForeignFile and a spawn-timeout assertion.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: harden opencode activity hooks

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: harshitsinghbhandari <24b4506@iitb.ac.in>
2026-06-03 17:06:32 +05:30
Harshit Singh Bhandari 210c9df758
feat(cli): enrich ao doctor (#90) (#99)
* feat(cli): enrich ao doctor

* fix(cli): address doctor review feedback
2026-06-03 16:50:54 +05:30
Harshit Singh Bhandari bab0d2d167
feat: add light backend CLI commands (#98) 2026-06-03 16:18:00 +05:30
Harshit Singh Bhandari 010b422bb5
feat(cli): add ao session ls/get/kill/restore (#90) (#92)
* feat(cli): add session commands

* test(cli): cover session json output

* chore(cli): trim unused session response fields
2026-06-03 04:50:45 +05:30
Harshit Singh Bhandari ae9fa0e341
feat(cli): add ao project ls/get/rm (#90) (#91)
* feat(cli): add project ls get rm

* fix(cli): satisfy project confirmation lint

* chore(ci): remove agent-ci dockerfile

* test(cli): cover project json output

* fix(cli): label project agent as default harness
2026-06-03 04:46:55 +05:30
neversettle fab5451a9f
feat(api): PR action routes — merge + resolve-comments (#88)
* feat(api): register PR action route shells (merge + resolve-comments)

Adds two 501 Not Implemented route shells for the SCM/PR action lane
as specified in issue #21. No business logic — the routes are stubs
that return a structured planned body with the embedded OpenAPI spec
slice, consistent with the existing route-shell pattern.

Routes registered:
  POST /api/v1/prs/{id}/merge
  POST /api/v1/prs/{id}/resolve-comments

Closes part of #18.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(api): PR action routes — full impl (merge + resolve-comments)

Builds the two SCM/PR action routes end-to-end per issue #21:

  POST /api/v1/prs/{id}/merge
  POST /api/v1/prs/{id}/resolve-comments

**ports/scm.go** — new PRService interface, MergeResult, ResolveResult.

**adapters/scm/github** — adds ErrNotMergeable/ErrUnprocessable sentinels
to the client (405/409/422 classification) and MergePR / ListUnresolvedThreadIDs /
ResolveThread methods to the Provider.

**internal/scm/pr_service.go** — concrete PRService over PRProvider. Parses
the path ID as a PR number, calls the provider, maps github sentinel errors to
domain errors (ErrPRNotFound / ErrPRNotMergeable / ErrPRPreconditions /
ErrNothingToResolve). Nil PRService keeps routes registered but returns
OpenAPI-backed 501s.

**httpd/controllers/prs.go** — real handlers; writePRError maps the four domain
errors to 404 / 409 / 422 / 500.

**prs_test.go** — httptest coverage: 501 (nil service), 200/404/409/422 for
both routes, spec-slice present in 501 body.

**scm/pr_service_test.go** — table-driven unit tests with a fake PRProvider.

Closes part of #18. Closes #21.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(api): PR action routes — merge + resolve-comments (#21)

Implements POST /api/v1/prs/{id}/merge and POST /api/v1/prs/{id}/resolve-comments.

Service logic lives in internal/service/pr (ActionManager interface + ActionService
struct). Controllers use the projects pattern — import the service package directly
rather than going through a ports interface. Drops the internal/scm intermediary
package and the ports/scm.go file added in earlier iterations.

Also fixes the ContentLength-based body-decode guard in resolveComments, which
silently dropped JSON bodies sent with chunked transfer encoding; now decodes
unconditionally and treats io.EOF as an absent body.

Closes #21.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(specgen): remove dead path-param entries from schemaNames

ControllersProjectIDParam, ControllersSessionIDParam, and ControllersPRIDParam
are never matched by the schemaName interceptor — swaggest reflects path-param
structs inline rather than as $ref component schemas, so the hook is never
called for these types.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(pr): anchor resolve-comments to stated PR when explicit IDs supplied

When commentIDs were provided, the parsed PR number was never used — any
thread ID could be resolved regardless of which PR was in the URL path.
Add a ListUnresolvedThreadIDs existence probe in the else branch so the PR
must be reachable before iterating the caller-supplied IDs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(controllers): exclude io.ErrUnexpectedEOF from isEmptyBody

A truncated body (e.g. {"commentIds":["T_1") returns io.ErrUnexpectedEOF,
not io.EOF. Treating it as an absent body caused the handler to fall through
to "resolve all unresolved threads" instead of returning 400. Only io.EOF
(reader returned no bytes) is a genuine empty-body signal.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(api): revert to route shell — stubs, no adapter changes

- Remove adapter changes (ErrNotMergeable/ErrUnprocessable from client.go,
  MergePR/ListUnresolvedThreadIDs/ResolveThread from provider.go)
- ActionService returns dummy values with TODO; no business logic
- Errors (ErrPRNotFound etc.) moved to controllers/errors.go
- PR DTOs moved to controllers/dto.go
- Remove 501 guards — stub service always wired via NewAPI default

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: restore client.go, move PR errors to service/pr, fix lint

- Restore original client.go alignment (no functional change)
- Move PR sentinel errors to service/pr/errors.go
- controllers/errors.go now only contains writePRError, referencing prsvc sentinels
- Fix schemaNames alignment in specgen/build.go (goimports lint)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(api): replace fake-success stub with 503 when SCM not configured

The nil-service fallback was silently injecting a stub that returned
fake merge/resolve success, misleading callers when no SCM is wired.
Remove the injection; nil Svc now returns 503 SCM_NOT_CONFIGURED.
Also inline writePRError into prs.go and delete controllers/errors.go.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(specgen): mark resolve-comments request body as optional

reqBody: nil removes the requestBody.required: true annotation so
generated SDK clients can omit the body (which resolves all threads).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(prs): align nil-service guard with spec (501) and echo prID in stub

Use apispec.NotImplemented (501) instead of 503 so nil-service responses
match the OpenAPI spec and generated clients hit the documented 501 branch.

Echo prID as PRNumber in the stub Merge to avoid claiming the wrong PR
was merged if NewActionService is wired by accident before real impl lands.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-03 04:43:50 +05:30
Harshit Singh Bhandari 718a1b135c
docs: add AGENTS.md (#93)
* docs: add AGENTS.md

* docs: address AGENTS review
2026-06-03 04:24:04 +05:30
Harshit Singh Bhandari 9058017439
fix: prefix ao send messages with sender session (#85)
* fix: prefix ao send messages with sender session

* feat: add orchestrator-aware spawn prompts

* fix(session): return first active orchestrator
2026-06-02 21:39:21 +05:30
Harshit Singh Bhandari 5435246c9a
feat(cli): add minimal ao send (#83)
* feat(messenger): ao send + live zellij pane ping (live agent nudges)

Replace the daemon's noopMessenger stub with a composite AgentMessenger
that writes a durable inbox file (primary) and types a live pointer into
the running zellij pane (best-effort secondary), plus the `ao send` CLI
that drives the existing POST /api/v1/sessions/{id}/send route.

- composite: fans Send to inbox then panep, pinning one timestamp so both
  derive the same filename; a secondary failure is logged at WARN and
  swallowed (the file is on disk), a primary failure aborts the call.
- inbox: writes <workspace>/.ao/inbox/<rfc3339nano>_<hash>.md.
- panep: types "new message at .ao/inbox/<file>" + Enter via a new narrow
  zellij WriteChars seam (RuntimePaneWriter), kept off ports.Runtime.
- wiring: newSessionMessenger composes inbox+panep over the shared store;
  startSession takes the messenger instead of the noop stub.

Carries across @aa-43's work from PR #74 (staging), adapted to main's
post-#65/#77 daemon wiring shape.

Closes #79

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(inbox): use O_EXCL so a filename collision errors instead of clobbering

os.WriteFile opens with O_CREATE|O_WRONLY|O_TRUNC, which silently overwrites
an existing file. The doc comment already stated the intent ("we do not retry
on EEXIST"), but O_TRUNC never yields EEXIST — two identical messages sent on
the same composite-pinned nanosecond would produce the same filename and the
second Send would silently lose the first message. Switch to
O_CREATE|O_EXCL|O_WRONLY so a collision surfaces as an error; O_EXCL also
refuses to follow a symlink at the final path component. Add a regression test.

Addresses greptile review on PR #83.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(inbox): remove the freshly-created file when write or close fails

The O_EXCL switch creates the inbox file before writing its body; if
WriteString or Close then fails, the empty/partial .md was left on disk and
the agent's next inbox scan would pick up a truncated ghost message. Remove
the file on those error paths. O_EXCL guarantees the file did not exist before
this call, so the cleanup can only delete our own partial write, never a
legitimate earlier message.

Addresses greptile review on PR #83.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(messenger): reduce ao send to live pane delivery

* fix(send): preserve messages and map lookup errors

* fix(send): reject terminated sessions
2026-06-02 20:02:47 +05:30
yyovil 57bb63701d
Add `ao spawn` + `ao project add` (spawn a real worker end-to-end) (#77)
* Add `ao spawn` and `ao project add`; resolve project repos for worktrees

Make a registered project spawnable end-to-end from the CLI:

- DB-backed RepoResolver: the daemon resolves a project's on-disk repo
  path from the projects table (replacing the empty StaticRepoResolver
  that failed every lookup), so a session's worktree is cut from the
  right repo.
- session_manager defaults an empty spawn branch to ao/<session-id> — a
  fresh, unique branch per session, since gitworktree can't reuse a
  branch already checked out elsewhere (e.g. main).
- `ao project add --path <repo>`: register a local git repo (POST /api/v1/projects).
- `ao spawn --project <id> [--harness] [--branch] [--prompt] [--issue]`:
  spawn a worker session (POST /api/v1/sessions); harness defaults to the
  daemon's AO_AGENT.
- Shared postJSON daemon client (reads the run-file for the port, surfaces
  the API error envelope).

Stacked on #65, which lands the agent-adapter + session-manager wiring
this depends on.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Address Copilot review on #77

- `ao spawn` no longer prints a branch the sessions API doesn't return
  (session metadata is json:"-"), so the output is no longer misleading.
- Unregistered/archived/no-path projects now surface a 400
  PROJECT_NOT_RESOLVABLE with an actionable message instead of a generic
  500: a new sessionmanager.ErrProjectNotResolvable sentinel the resolver
  wraps and writeSessionError maps.
- postJSON reuses the injected Deps.HTTPClient (cloned, with a longer
  timeout) instead of a fresh client, keeping HTTP behaviour stubbable.
- postJSON treats a stale run-file (dead PID) as "not running" via
  ProcessAlive, matching its docstring.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Assert the project-not-resolvable sentinel in the resolver test

Greptile review: harden TestProjectRepoResolver to verify the unregistered
-project error wraps ErrProjectNotResolvable, so a future regression in the
sentinel wrapping (which the HTTP 400 mapping relies on) is caught.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Fix ao spawn 500 on long session ids (zellij socket-path overflow)

Root cause: the daemon built the zellij runtime with an empty SocketDir,
so zellij fell back to its $TMPDIR-based default (long on macOS). That
left almost none of the ~103-byte unix-socket-path budget for the session
name, so a long session id (e.g. "aoagents-agent-orchestrator-1", derived
from a long project id) was rejected by zellij with "session name must be
less than 0 characters". runtime.Create failed, the spawn 500'd, and the
worktree was rolled back (leaving an orphan ao/ branch).

- New zellij.DefaultSocketDir(): a short, stable per-user socket dir
  (/tmp/ao-zellij-<uid>); the daemon uses it (and MkdirAll's it).
- ao spawn's attach hint now prefixes ZELLIJ_SOCKET_DIR so it stays
  copy-pasteable against the daemon's socket dir.
- Regression test guards that the socket dir leaves >= 48 bytes for the
  session name within the 103-byte limit.

Verified: ao spawn against a long-id project now succeeds (session live,
worktree created) where it previously 500'd.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(cli): guard CLI/daemon DTO drift with an e2e round-trip

The CLI keeps its own request structs (spawnRequest, addProjectRequest)
separate from the daemon's canonical DTOs (controllers.SpawnSessionRequest,
project.AddInput). Nothing verified the JSON field names agreed, so a renamed
tag on either side would compile but break at runtime.

Drive `ao spawn` and `ao project add` through the real httpd router and
controllers (fakes only at the service layer) over a real loopback round trip
via postJSON, asserting each field decodes into the right SpawnConfig/AddInput
field. Runs in the normal test lane (no extra ports/processes).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(cli,daemon): address review findings on ao spawn

- spawn: print the sanitised zellij session name (zellij.SessionName) in the
  attach hint; a long/non-conforming session id is registered under a different
  name, so the raw id sent users to a missing session.
- client: surface the daemon error envelope's requestId so a failed command can
  be correlated with daemon logs.
- daemon: don't swallow the zellij socket-dir MkdirAll error — log it, since a
  failure otherwise surfaces later as an opaque socket-bind error on every spawn.
- project: reject an embedded ".." in a project id up front; it passed the id
  pattern but yielded an invalid branch (ao/a..b-1) and an opaque 500 at spawn.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: harshitsinghbhandari <24b4506@iitb.ac.in>
2026-06-02 18:39:13 +05:30
yyovil 3346c6cb6c
Add agent adapters and wire per-session agents into the session manager (#65)
* feat(plugin): add agents plugin (first iteration)

Faithful copy of the agents plugin implementation from yyovil/better-ao
(internal/plugin/ -> backend/internal/plugin/) plus its PRD
(prds/plugins/agents/PRD.md), as a first-iteration proposal for review.

Imports are left at their original github.com/yyovil/better-ao/... paths and
are NOT yet reconciled to this repo's module; see PR description for the
integration deltas (module path, missing internal/utils dependency).

Co-authored-by: Claude <noreply@anthropic.com>

* Move agent adapters under backend adapters

* Keep daemon ports and session out of adapter move

* Remove Better-AO naming from flake

* Keep flake as dev shell only

* Use goimports for local formatting

* Wire session manager to per-session agent adapters

Move the Agent port into internal/ports and have the claude-code and
codex adapters implement it directly, alongside their workspace-local
activity hooks and a manifest-keyed adapter registry. Rename
RuntimeConfig.LaunchCommand to Argv and update the tmux and zellij
runtimes to match.

The session Manager now resolves a real agent adapter per session via a
new ports.AgentResolver: from cfg.Harness on Spawn and the stored harness
on Restore, so one daemon runs claude-code and codex sessions side by
side. The daemon backs the resolver with the registry; AO_AGENT selects
the default harness (default claude-code), validated at startup. Removes
the temporary noopAgent stub.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(agent): point the agent contract at internal/ports/agent.go

The Agent interface moved from internal/adapters/agent to internal/ports;
update the PRD's Goal and Agent Contract sections (and the SessionInfo
references) to match the code.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Wire the session service into the daemon

daemon.Run now builds the controller-facing session service — a session
manager over the zellij runtime, a gitworktree workspace, the shared
store + LCM, and the per-session agent resolver (AO_AGENT default,
validated at startup) — and mounts it at httpd APIDeps.Sessions, so the
session REST routes are backed by a real service. startLifecycle moves
ahead of the HTTP server so both share one LCM.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Address Greptile review: complete the live spawn path

- Spawn and Restore now install workspace-local activity hooks
  (GetAgentHooks) and run the adapter's optional PreLaunch step before
  launch, via a shared prepareWorkspace helper. PreLaunch is how Claude
  Code records workspace trust, so its interactive "trust this folder?"
  dialog can't hang the headless pane; the spawned env now also carries
  AO_DATA_DIR so the installed hook commands find the store.
- claudecode and codex hook/config writes are now atomic (temp + rename)
  instead of os.WriteFile, so a crash mid-write can't leave a partial
  file the agent fails to parse.
- ensureWorkspaceTrusted serializes its read-modify-write under a package
  mutex, so concurrent spawns to different workspaces don't drop each
  other's ~/.claude.json trust entries.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(ports): pin MetadataKeyAgentSessionID to domain.SessionMetadata json tag

The equality between ports.MetadataKeyAgentSessionID and the json tag on
domain.SessionMetadata.AgentSessionID is a hand-maintained invariant; this
test fails loudly if either side drifts.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(adapters): use ports.MetadataKeyAgentSessionID in claudecode + codex

The native session id metadata key is defined in ports for cross-package
consumption; drop the duplicated literals in each adapter so the constant
has one home.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(codex): cover ensureCodexHooksFeatureEnabled TOML edge cases

The helper is a string editor over config.toml; pin its content
transformation for missing/empty files, existing [features] blocks,
the no-op case, and the legacy codex_hooks=true migration paths.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs(adapters): document Registry concurrency contract

Registry registration runs at daemon boot before any goroutine calls Get,
so the underlying map needs no lock; pin that contract in the doc comment
so a future change doesn't quietly introduce a race.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* style(codex): gofmt codex_test.go after constant rename

The previous commit (7c5b2a9) replaced codexAgentSessionIDMetadataKey with
ports.MetadataKeyAgentSessionID inside a map literal; the longer key threw
off gofmt's column alignment on the adjacent codexTitleMetadataKey /
codexSummaryMetadataKey lines. Caught by agent-ci's Check formatting step.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

Co-authored-by: harshitsinghbhandari <dev@theharshitsingh.com>
2026-06-02 16:51:32 +05:30
prateek c3eeecb686
merge fork, 25 May - 2 June (#2086)
* feat(core): add prs[] array to Session for multi-PR support — Phase 1 metadata layer

* feat(core): update lifecycle-manager for multi-PR per session — Phase 2

* feat(web): add prs[] to DashboardSession and wire up multi-PR display — Phase 3

* feat(plugins): append to prs metadata field on gh pr create — Phase 4

* fix: address all code review issues — PR number, enrichment pipeline, claimPR append, stale PRs, V1 compat, SCM calls, dead code, isDraft, session validation

* fix: address Greptile review — state machine aggregation, URL dedup, React keys, review comments, typecheck

* fix: remove useless assignment in lifecycle-manager — lint error

* fix: add missing prs field to Session objects in cli and plugin test files

* fix: add prs field to integration-tests helpers and fix V1 flat-file fallback in agent-claude-code

* fix: use stack approach for claimPR prs field — claimed PR becomes primary

* feat(core,web): multi-PR per session — enrichment, status dots, bug fixes (#1821)

- Session metadata now stores a comma-separated prs list; all PR URLs
  parsed into session.prs[] on load, backwards-compatible with single-PR
- Enrichment loop hydrates every PR in the list each poll cycle via the
  existing batch GraphQL call
- Fixed closed-PR filter reading from session lifecycle state instead of
  per-PR enrichment cache, which misclassified secondary PRs
- Fixed isDraft never propagating from enrichment cache to dashboard.pr
  and dashboard.prs[i]
- Fixed prs[0] and dashboard.pr being separate objects — enrichment on
  one now syncs to the other
- SessionCard PR badges now show a colored status dot per PR: green (CI
  passing/merged), yellow (CI pending), red (CI failing/changes
  requested), grey (unenriched/draft/closed)
- Corrected color token mapping: passing uses --color-status-merge
  (green), pending uses --color-status-pending (yellow)

* fix(core): add missing prs field to code-review-manager test fixture

* feat(web): per-PR rows with colored chips, titles, and click-to-switch on session card

- Replace single-PR badges with one row per PR when session has multiple PRs
- Each row shows: status-colored chip, PR title (truncated), diff size
- Chip colors: green (CI passing/merged), yellow (CI pending), red (CI
  failing/changes requested), grey (closed/draft/unenriched)
- Repo initials badge (e.g. AO, CM) shown per row when PRs span multiple repos
- Clicking a row selects it — description, alerts, and action buttons in the
  card body all switch to that PR's context
- Clicking the chip opens GitHub; clicking title/diff area selects without
  navigating away
- Single-PR sessions are completely unchanged

* fix(web): address multi-PR card review — effectivePR for merge button, color-mix chips, left-border selection

* fix(web): derive prs from pr in makeSession test helper

* fix(core): fall back to raw[pr] when prs absent in claimPR

* feat(web): PR switcher in session detail header for multi-PR sessions

* fix(core): treat ciStatus/reviewDecision 'none' as passing in multi-PR aggregation

* fix(core): stale-session cleanup checks all prs before killing multi-PR session

* fix(core): all-none reviewDecision aggregates to none, not approved

* fix(core): prs accumulation in Node hook, bump WRAPPER_VERSION, clear stale enrichment on claimPR

* fix(core,web): webhook matching for secondary PRs, restore lifecycle PR number fallback

* fix(web): merge endpoint resolves target PR from session.prs for secondary PRs

* fix(core,web): clamp selectedPRIndex, guard multi-PR partial cache miss, clear prs on takeover

* fix(core,web): scope webhook secondary PR match by owner/repo, handle JSON metadata in Node hook

* fix(web): guard merge route PR lookup by owner/repo to prevent number collision

* fix(web): forward owner/repo from merge button to activate PR disambiguation guard

* fix(web): propagate owner/repo through BottomSheet and AttentionZone merge triggers

* test(web): update onMerge assertion to expect owner/repo arguments

* fix(core,web): resolve 5 multi-PR logical gaps — conflict detection, partial cache miss, isDraft aggregation, event context prs, AttentionZone labels

* fix(core,cli,plugins): add prs field to NotificationEventContext fixtures across all packages

* fix(web): add owner/repo guard to primary PR branch in webhook session match

* fix: handle unknown update versions and flat interactive config

* ci: pin GitHub Actions to SHAs

* fix: support new orchestrator from flat config

* ci: skip dependency review on unsupported forks

* revert: run dependency review on all PRs

* docs(design): add dashboard design-language exploration + mockups

Capture the design-language direction explored for the AO dashboard as
live HTML mockups plus rationale, under docs/design/.

- dashboard-language.md: the language — blue=orchestrator / orange=agents
  identity, rationed semantic color, Schibsted Grotesk + JetBrains Mono,
  unified status system, layout patterns, and how it diverges from DESIGN.md.
- mockups/kanban.html: canonical fleet board (frameless lifecycle columns).
- mockups/session.html: canonical session detail (framed xterm + pluggable
  inspector rail: Summary / Changes / Browser; review-comment "Address").
- mockups/{concepts,refined,*-icons}.html: exploration / icon comparisons.
- mockups/mascot.png: the blue conductor mascot.

Reference mockups only (CDN fonts + inline styles); production must use the
Tailwind tokens in globals.css per C-02/C-07.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(web): migrate dashboard to mission-control design language (supersedes DESIGN.md)

Replace the "Warm Terminal" system with the "Mission Control" language from
the merged design exploration (docs/design/dashboard-language.md + the kanban
& session mockups). One coherent system, dark control-room aesthetic, rationed
color (blue = orchestrator/you, orange = working agent, amber = needs-input,
red = failing/stuck, green = mergeable, else grayscale).

Tokens & fonts
- globals.css @theme/.dark: add literal palette (--bg #0a0b0d, --bg-side,
  --card #15171b = only bordered surface, --term #0c0d10, --line/--line-2,
  text ramp --t1..--t4, --blue/--orange/--amber/--red/--green) and re-point the
  existing --color-* semantic tokens to it (no token renames — alias + migrate).
  Flat surfaces, no warm gradients/glows. Dark theme preserved.
- Self-host Schibsted Grotesk (UI) + JetBrains Mono (machine) via
  next/font/local — no external font CDN. Geist Sans removed.

Status system (one spectrum, used everywhere)
- lib/status-spec.ts (getStatusSpec) + <StatusBadge> render the kanban card
  badge, sidebar dot, and session topbar pill from a single source; working dot
  breathes (CSS-only @keyframes breathe).

Fleet board (kanban.html)
- Frameless tinted columns Working -> Needs you -> In review -> Ready to merge
  with per-column semantic top-glow; the card is the only bordered surface
  (hairline ring, no status left-rail). Sidebar-shows-all-projects + SSE 5s
  unchanged.

Session detail (session.html)
- Framed xterm terminal: theme object tied to tokens (orange cursor, blue
  selection, token-mapped ANSI) — terminal content unstyled.
- New pluggable inspector rail <SessionInspector>: Summary (PR -> review
  comments -> Activity -> Overview) / Changes / Browser. Review comments keep
  the soft-blue Address action (askAgentToFix passing comment + file:line).
- Topbar: shared status pill, Kill, solid-blue Orchestrator primary; the PR
  popover is now mobile-only (desktop has the inspector). Blue mascot mark.

Tests: add status-spec / StatusBadge / SessionInspector / AppMark tests; update
column-label, theme, layout-metadata and PR-location assertions; mock
next/font/local in vitest. typecheck / test / lint / build all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* wip(web): compact card footer + cleanup before mockup-fidelity pass

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(web): mockup-faithful redesign pass — sidebar brand, resizable panels, cleaner chrome

Addresses review feedback to follow docs/design/mockups/{kanban,session}.html closely.

Sidebar (ProjectSidebar + mc-sidebar.css)
- Brand + blue mascot mark moved to the TOP of the sidebar (was in the topbar).
- Cool sidebar background (var(--color-bg-sidebar) #08090b) — removed the warm tint.
- Removed the yellow session-count chip (plain mono count) and the Review button.
- Per-project action icons now reveal on hover only.
- Consolidated the footer's four buttons into a single Settings gear + popover
  (show killed / show done / show session id / theme).
- Right edge is drag-resizable.

Board (Dashboard + AttentionZone + SessionCard + mc-board.css)
- Topbar brand removed; "Board" header + mockup subtitle; blue primary CTA.
- Frameless tinted columns with per-column glow; compact informational cards
  (status badge · id · hover terminal, 2-line title, branch w/ git icon, thin
  PR/CI footer). Removed inline quick-reply/alerts/CI-chips/merge+review buttons
  from cards (actions live on the session page); kept hover kill + terminal link.
- Split Done card into SessionCard.parts.tsx (≤400 lines).

Session detail (SessionDetail* + SessionInspector + TerminalControls + mc-session.css)
- Topbar: ‹ Kanban back button, title with branch to its RIGHT (git icon, no odd
  truncation), shared status pill, Kill, blue Orchestrator. Brand removed from the
  session shell header too.
- Terminal header: removed the "Connected" status text; matches the mockup
  (Terminal label · id · zoom · fullscreen). Terminal flush (no stray left margin).
- Terminal head and inspector tab bar are both 47px so their rules align.
- Inspector: PR → review comments → Activity timeline → Overview; left edge
  drag-resizable. Split header helpers into SessionDetailHeader.parts.tsx.

Shared infra
- useResizable hook (pointer drag → CSS var on :root, localStorage-persisted,
  no inline style); .resize-handle styles; per-screen mc-*.css loaded after
  globals.css in layout.tsx; sidebar/inspector widths read --ao-sidebar-w /
  --ao-inspector-w with sensible min/max + double-click reset.

typecheck / web tests (1005) / lint (0 errors) / build all green; resize verified.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(web): sidebar/topbar polish from review feedback

- Notification bell icon 13→17px (was tiny inside its 34px button).
- Sidebar project rows: count shows at rest in the right slot; per-project
  action icons are now an absolutely-positioned hover-reveal group (out of
  flow) so the project name keeps full width and the row stays single-height
  (fixes the inflated rows / vertically-stacked icons).
- Session status dot nudged 1px to vertically center against the mono label.
- Orchestrator session page no longer renders the inspector rail (full-width
  terminal — nothing to inspect).

typecheck / web tests (1005) / lint (0 errors) green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(web): notification icon size + sidebar/topbar review fixes

- Notification bell on the session topbar was squeezed to a 6px sliver: the
  text-button padding rule applied to the icon-only button inside its fixed
  34px width. Give the bell its own 34px square / zero-padding rule → 17px icon.
- Remove the redundant sidebar toggle from the session topbar on desktop
  (mobile keeps the drawer hamburger); the sidebar owns collapse/expand.
- Collapsed sidebar now shows an expand button so it can be reopened.
- Trim sidebar padding + session-list indent so project/agent rows get more
  width.

typecheck / web tests (1005) / lint (0 errors) green; collapse↔expand + icon
size verified.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(web): sidebar session names truncate with ellipsis; rename pencil no longer overlays

- The session label was an inline <span>, so text-overflow:ellipsis never
  applied — long names hard-clipped. Make it display:block so it ellipsizes.
- The rename pencil now absolutely positions at the row's right edge; at rest
  the label gets the full row width, and on hover the link gains right-padding
  so the text re-truncates and the pencil sits in the reserved space instead of
  covering the name.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(web): project name reserves space for hover action icons (no overlap)

On hover the per-project action icons reveal over the right slot; the toggle now
gains right-padding so the project name re-truncates with ellipsis instead of
running underneath the icons — same pattern as the session rows.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(web): remove kanban topbar toggle + redesign empty state to mission-control

- The board (kanban) topbar still rendered a desktop sidebar toggle; make it
  mobile-only (the sidebar owns collapse/expand), matching the session topbar.
- Empty state (Skeleton EmptyState): ghost columns now use the live board's
  labels (Working / Needs you / In review / Ready to merge), 4 columns, and the
  frameless tinted-trough look — removing the old dashed/warm-tinted columns and
  the stale 5-category set. Orchestrator glyph recolored to the blue accent via
  tokens (was hardcoded orange).

typecheck / web tests (1005) / lint (0 errors) green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(web): show project name in titlebar, not the raw project id hash

The board topbar special-cased projects named 'Agent Orchestrator' to display
the project id (e.g. agent-orchestrator_649ba24578) — unreadable gibberish.
Always show the human-readable project name instead.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(core,web): detectPR branch guard, multi-PR prLabel aggregation, reset selectedPRIndex on session change

* fix(web): render terminal with xterm WebGL renderer (fixes broken box-drawing)

The dashboard terminal used xterm's default DOM renderer, which draws each
row as a separate DOM line and cannot tile box-drawing / block glyphs across
cells. Agent TUIs (Claude Code's bordered panels, the "N shell command"
expansion) rendered with broken/gappy frames and a grey blob — independent of
font or lineHeight (verified: even a complete font at lineHeight 1.0 breaks in
the DOM renderer).

Load xterm's WebGL renderer (@xterm/addon-webgl), which GPU-draws box/block
glyphs into each cell so frames connect and shaded regions stay solid. Loaded
rAF-deferred after open() with a DOM fallback on context-loss / when WebGL is
unavailable (headless, blocklisted GPU). This matches how superset renders
the same agent TUIs.

The WebGL addon only ships for the xterm 6.1.0-beta train, so bump
@xterm/xterm 6.0.0 -> 6.1.0-beta.256 and the addons to the matched beta set
(the same pair superset runs in production).

Also drops the earlier no-op fontWeight/fontWeightBold/letterSpacing change —
those values equalled xterm's defaults and had no visible effect.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(web): enforce dark-mode contrast floor so agent blocks aren't grey blobs

Claude Code's expanded "Ran N shell command" block is painted on an ANSI
white background (ESC[47m). The terminal theme sets `white` ≈ `foreground`
(#c5ccd3), and dark mode used `minimumContrastRatio: 1` (no floor), so the
block's text was the same colour as its background — rendering as an
unreadable grey blob (only independently-coloured links/emoji showed through).

Raise the dark-mode floor to 4.5 (WCAG AA), matching the rationale already
used for light mode (7). xterm then auto-adjusts only the foregrounds that
fail the floor, leaving all other agent colours untouched. Verified in an
isolated harness with the real theme: white-on-white block goes from
invisible to legible.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(web): load Unicode 11 addon so emoji/wide-char widths match tmux

Agent TUIs and tmux lay out tables treating emoji like / as 2 cells
wide (modern Unicode). xterm defaults to Unicode 6 width tables, where
those are 1 cell — so the grid shifts a column after every emoji, breaking
table borders and leaving stray text fragments (visible only in the web
terminal; a direct tmux attach via a modern terminal renders it fine).

Load @xterm/addon-unicode11 and set unicode.activeVersion = "11" so xterm's
width tables agree with tmux/the agent. Same beta train as the other addons.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(web): rescale overlapping glyphs so out-of-font chars don't overlap text

JetBrains Mono is subset to Latin glyphs, so characters it lacks (arrows
→ ← ↔, CJK, emoji, powerline) are drawn from a fallback font whose advance
can exceed our monospace cell — the glyph then bleeds into the next cell and
overlaps the following character. Set rescaleOverlappingGlyphs so xterm shrinks
any glyph wider than its cell back to fit. Fixes the whole class of out-of-font
overflow, not just arrows.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(web): ship full-coverage JetBrains Mono (restore arrows/box/blocks)

The self-hosted JetBrains Mono was subset to ~229 Latin glyphs, dropping
arrows (→ ← ↔), box-drawing, block elements and other symbols agents emit.
Those fell back to a system font at the wrong cell width — overlapping
(pre-rescale) or shrunk/blurry (post-rescale). Replace it with the full
JetBrains Mono variable face (OFL-1.1, wght 100–800, ~111 KB woff2, same
metrics) so those glyphs render in-font, full-size and crisp at the correct
monospace width. rescaleOverlappingGlyphs stays as a safety net for the few
glyphs even the full face lacks (CJK, emoji, powerline PUA).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Laraib-1629 <laraibahmed73@gmail.com>
Co-authored-by: suraj-markup <sk9261712674@gmail.com>
Co-authored-by: itrytoohard <ayetrytoohard@gmail.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Priyanshu Choudhary <57816400+Priyanchew@users.noreply.github.com>
2026-06-02 05:10:55 +05:30
neversettle 3a93e33331
refactor: move project manager to service layer (#68)
* refactor(project): manager talks to the sqlite store; drop the in-memory store

The project Manager now runs only against the durable backend store: remove the
process-local MemoryStore (and NewMemoryManager), and require a real Store. The
daemon already wires the sqlite store; tests now build a real temp-dir sqlite
store instead of the mock.

- Move Row + the Store port to project/store.go. The Store interface stays
  because it is the dependency-inversion port that lets the manager reach the
  backend without an import cycle (storage imports project.Row), not an extra
  mock layer — there is no longer any in-memory implementation.
- NewManager requires a non-nil Store (no in-memory fallback).
- Add project/manager_test.go: List/Add/Get/Remove happy paths +
  PATH_REQUIRED/NOT_A_GIT_REPO/PATH_ALREADY_REGISTERED/ID_ALREADY_REGISTERED,
  PROJECT_NOT_FOUND/INVALID_PROJECT_ID, and UpdateConfig — all against a real
  sqlite store (the service-logic tests #47 lacked).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor(project): trim routes, consolidate package, add code-first OpenAPI

- Remove POST /reload, PATCH /{id}, POST /{id}/repair routes and their
  Manager methods (Reload, UpdateConfig, Repair) and DTOs (ReloadResult,
  UpdateConfigInput) — not needed at this stage
- Merge Manager interface into manager.go; delete project.go (single-impl
  split served no purpose)
- Remove dead notImplemented helper from errors.go
- Port PR #59 code-first OpenAPI generation: controllers/dto.go named
  response types, specgen/build.go (4 routes), parity + drift tests,
  cmd/genspec, go generate wiring; regenerate openapi.yaml
- Add swaggest deps; add YAML() method to apispec.Spec

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* fix(project): address PR review comments

- t.Skipf → t.Fatalf in gitRepo helper: git failures now hard-fail
  instead of silently skipping manager tests on a misconfigured runner
- FindProjectByPath: add AND archived_at IS NULL so archived paths don't
  permanently block re-registration (update queries/projects.sql and
  generated gen/projects.sql.go)
- Add TestManager_ReaddAfterRemove to lock the fix

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* fixed lint and fmt

* addressed greptile comments

* Apply suggestions from code review

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* project tests fix

* project_tests fix

* fix: Linting and formatting fix

* refactor: move project manager into service layer (#68)

* refactor: split service package by resource (#68)

* fix: ignore archived project id conflicts (#68)

* refactor: move pr manager into service layer (#68)

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Co-authored-by: itrytoohard <ayetrytoohard@gmail.com>
2026-06-02 01:26:48 +05:30
prateek 424e6e824b
refactor: move session status assembly to service (#62) (#67)
Co-authored-by: itrytoohard <ayetrytoohard@gmail.com>
2026-06-01 23:31:21 +05:30
Harshit Singh Bhandari f9b08aada4
feat(scm): GitHub provider adapter — Observe(prURL) → PRObservation (#69)
* feat(scm): GitHub provider adapter — Observe(prURL) → PRObservation

A fresh GitHub SCM provider adapter under
backend/internal/adapters/scm/github/ exposing one method:

  (*Provider).Observe(ctx, prURL) (ports.PRObservation, error)

It performs a REST GET on /repos/{o}/{r}/pulls/{n} for the authoritative
draft/merged/closed/head-SHA, one GraphQL query for the reviewDecision +
mergeStateStatus + statusCheckRollup + unresolved review threads, and
(only for failure-class CheckRuns) a REST GET on
/actions/jobs/{job_id}/logs to splice the last 20 lines of the failed
job into the observation.

The package is the observation primitive; the polling loop, cadence
selection, daemon wiring, persistence and webhook receiver are all
intentionally out of scope (separate PRs / lanes).

Closes #27 — this supersedes PR #28's attempt, which targeted types
(domain.SCMProvider / SCMSnapshot / ports.SCMObserveRequest) that the
PR #62 simplification refactor has since removed. The GraphQL queries
and mergeability composition logic are credited to @whoisasx from
PR #28's provider.go; the package was re-implemented against the
current ports.PRObservation seam (post-#62) rather than rebased.

Bot-author detection uses ONLY GitHub's typed signal (__typename
"Bot" / User.Type "Bot"). The strings.Contains(login, "bot") fallback
from PR #28 was intentionally dropped — aa-18's review flagged it as
a false-positive magnet for logins like "robothon" / "lambot123".

46 table-driven tests against httptest.NewServer cover happy path,
draft, merged, closed (not merged), CI passing/failing/pending,
StatusContext legacy, log-tail extraction (and the best-effort
log-fetch failure case), mergeability mergeable/conflicting/blocked
(including ci-failing → blocked even when GitHub still says CLEAN —
the load-bearing aa-18 contract)/unstable/unknown, review
approved/changes-requested/required/none, bot-author filtering
(including the robothon false-positive guard), unresolved-only
threads, all-bots → empty Comments, ETag-304 cache hit, primary +
secondary rate-limit (with errors.As → *RateLimitError), 401 →
ErrAuthFailed, malformed JSON → Fetched:false, network error →
Fetched:false, Authorization Bearer header injection,
StaticTokenSource blank/whitespace rejection, GHTokenSource memoize
+ invalidate.

Verification:
- go build ./...               clean
- go vet ./...                 clean
- gofmt -l backend/internal/adapters/scm/   clean
- golangci-lint run ./... (v2.12, repo .golangci.yml)   0 issues
- go test -race ./internal/adapters/scm/github/...      46/46 PASS

References:
- aa-18 review of PR #28: ~/.ao/agent-reports/aa-18.md
- aa-26 tracker adapter (sibling Go-adapter pattern): #36 / agent-reports/aa-26.md

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(scm): address greptile review on #69

Four fixes from the greptile review of PR #69:

1. CI rollup pagination (P1) — when GraphQL reports
   pageInfo.hasNextPage=true for the statusCheckRollup contexts, a
   visible "all passing" set could be hiding a failing context on the
   next page. ciSummaryFromGraphQL now degrades Passing / Pending /
   Unknown to CIUnknown in that case; a known CIFailing on the visible
   page is still safe and is NOT degraded. Also bumped the per-page
   limit from 50 to 100 (GraphQL's documented max for the contexts
   connection). Two new tests pin both branches.

2. Empty GraphQL inline fragment (P2) — dropped
   `... on User { }` from the reviewThreads author selection. The
   empty selection set was technically invalid GraphQL and a future
   API tightening could reject the query. __typename already tells us
   whether the actor is a Bot, so the fragment carried no information.

3. rest.MergeStateStatus dead-code (P2) — the field decoded from the
   non-existent REST `merge_state_status` was always empty, making the
   firstNonEmpty fallback dead code. Removed the field and switched
   the tiebreaker to rest.MergeableState (the actual REST field, upper-
   cased so the same switch covers both GraphQL and REST shapes).

4. Wrong Accept header on /actions/jobs/{id}/logs (P2) — GitHub's
   REST API validates the Accept header before issuing the 302 to the
   log blob; sending text/plain risks a 406. Switched to the canonical
   application/vnd.github+json; the redirected blob serves text/plain
   regardless.

Verification:
- go build ./...               clean
- go vet ./...                 clean
- golangci-lint run ./...      0 issues
- go test -race ./internal/adapters/scm/github/...   48 / 48 PASS

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-01 21:44:56 +05:30
prateek c8f6050539
refactor: remove activity source tracking (#62) (#66)
Co-authored-by: itrytoohard <ayetrytoohard@gmail.com>
2026-06-01 09:26:18 +05:30
prateek a34094e7d8
refactor: simplify session lifecycle and zellij runtime (#62)
* refactor: remove canonical lifecycle state

* refactor: move sqlite stores into subpackage (#62)

* refactor: strengthen sqlite generated model types (#62)

* refactor: remove lifecycle notifications (#62)

* docs: remove notification cleanup leftovers (#62)

* refactor: narrow lifecycle manager scope (#62)

* refactor: keep PR nudges in lifecycle (#62)

* refactor: trim unused storage and lifecycle contracts (#62)

* refactor: align storage and runtime observation surfaces (#62)

* refactor: remove stale daemon and adapter bloat (#62)

* test: fix terminal ring race assertion (#62)

* refactor: trim lifecycle and http boilerplate (#62)

* refactor: expose sqlite CDC source directly (#62)

* refactor: share process liveness checks (#62)

* test: trim lifecycle store fake surface (#62)

* refactor: separate PR observations from storage rows (#62)

* refactor: trim remaining cleanup surfaces (#62)

* refactor: narrow observation and PR display APIs (#62)

* refactor: move PR write DTOs out of domain (#62)

* refactor: normalize PR domain storage types (#62)

* refactor: remove unused session port interface (#62)

* fix: reject unexpected CLI arguments (#62)

* refactor: use session metadata for spawn completion (#62)

* refactor: narrow session runtime dependency (#62)

* fix: validate zellij version in doctor (#62)

* refactor: split observation port DTOs (#62)

* chore: add sqlc generation script (#62)

* refactor: clarify terminal mux naming (#62)

* fix: tolerate nil loggers (#62)

---------

Co-authored-by: itrytoohard <ayetrytoohard@gmail.com>
2026-06-01 08:42:49 +05:30
prateek 80f46719d9
Merge pull request #61 from aoagents/chore/golangci-lint
chore(ci): add golangci-lint with a strong ruleset + fix CI Go version
2026-06-01 05:02:02 +05:30
prateek 8df074b1c9 chore(backend): add golangci-lint with a strong ruleset and clear the tree
Introduces backend/.golangci.yml (27 linters across correctness, dead-code/
boilerplate, style, and security), wires it into CI as a blocking job, and
fixes every finding so the tree starts at zero.

Config:
- 27 linters: errcheck, govet, staticcheck, errorlint, bodyclose,
  sqlclosecheck, rowserrcheck, nilerr, makezero, unused, unparam, unconvert,
  wastedassign, copyloopvar, prealloc, dupl, revive (incl. exported-symbol doc
  comments), gocritic, misspell, usestdlibvars, predeclared, nakedret, gosec, …
- Tuned for signal over noise: govet/shadow and gocritic hugeParam/rangeValCopy/
  unnamedResult disabled (idiomatic-Go false positives); sqlc-generated code and
  tests get scoped exclusions; gosec G304 excluded (paths are config/run-file/
  worktree-derived, not user input); nilerr excluded in cli/status.go (probe
  failures are the reported status, not a command error).

CI:
- New blocking lint job (golangci-lint-action, latest binary for Go-version
  compatibility).
- go-version now read from go.mod (was pinned 1.22 while go.mod declares 1.25).

Cleanup to reach zero (no behavior change):
- errcheck: wrap deferred/inline Close()/Remove()/Rollback() with `_ =`.
- gosec: tighten dir/file perms (0755->0750, 0644->0600).
- unparam: drop always-nil error return from startLifecycle; drop unused
  shellPath param (zellij PowerShell) and always-500 fallbackStatus param
  (writeProjectError).
- gocritic: regexp \d, s != "", switch->if, combined appends.
- revive: doc comments on all exported symbols; rename project.ProjectRow ->
  project.Row (stutter); rename `max` locals shadowing the builtin.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-01 04:58:41 +05:30
prateek c4bbbf73c4
Merge pull request #63 from aoagents/revert-58-feat/55
Revert "feat: add notifier delivery runtime"
2026-06-01 04:48:25 +05:30
prateek cb2a00a0c2
Revert "feat: add notifier delivery runtime" 2026-06-01 04:46:38 +05:30