Commit Graph

53 Commits

Author SHA1 Message Date
alan cedfc22e45 Pipeline runs use the workspace's directory environment
Resolve the run workspace's environment with workenv (direnv, parent
.envrc, mise; same account rule as Claude chats) at run start and resume,
and apply it to Pi stage processes, a per-environment Pipelines-owned
OpenCode stage service (keyed by a hash of the change, reused across runs,
idle ones stopped after PIPELINES_OPENCODE_STAGE_IDLE_TIMEOUT, revived per
registration), delivery-gate checks and merges, plain-stage opencode CLI
calls and file-change capture git reads. Record the directory, .envrc
files, sources and variable names (never values) on the run detail; a
blocked .envrc becomes a run warning.
2026-11-04 18:08:42 +00:00
alan a627b38ef3 Merge main; use the shared chatShutdownDetacher for OpenCode and Codex
OpenCode and Codex chats implement Detach (called by chatManager.Close)
instead of a parallel DetachSessions interface. Docs follow the Claude Code
host and the systemd KillMode=process unit. The opt-in live restart check
copies only the stage provider's login row into its scratch OpenCode
database, builds the CLI for skill install and removes its scratch tree.
2026-11-04 16:24:17 +00:00
alan aa8eddd686 Keep OpenCode/Codex chat and stage sessions running across server restarts
A stopping server no longer interrupts harness sessions. Runs are canceled
with a shutdown cause, so stage clients leave admitted sessions running and
owned; start-up recovery re-adopts live OpenCode V2 stage sessions (wait,
read back the result, continue the graph), restarts unadmitted visits,
continues runs between stages, and falls back to interrupted with a reason
when the harness is gone. Chats with live work are recorded on shutdown and
reattached on start; turns that ended during the downtime are folded in
from history. The server-spawned V2 chat serve is now a detached owned
service. PIPELINES_SHUTDOWN_SESSIONS=stop restores the old behaviour.
2026-11-04 16:17:08 +00:00
alan b655278674 Run OpenCode stages on a Pipelines-owned stage service with their own limits
Stages now run on a detached Pipelines-owned opencode serve started with
OPENCODE_CONFIG_CONTENT carrying stage tool_output (16384 bytes / 400 lines)
and compaction.auto defaults, configurable through PIPELINES_OPENCODE_STAGE_*.
Chats keep their existing service and configuration; a server-spawned chat
serve can take PIPELINES_OPENCODE_CHAT_CONFIG. The service shares the user's
OpenCode config, credentials and session database, keeps a stable private
registration so retained references (recovery, interrupt, export) stay valid,
revives on the same port after a crash, replaces itself when idle after a
settings change, and is stopped on shutdown only when idle.
PIPELINES_OPENCODE_STAGE_SERVICE=shared restores the previous behaviour.
2026-11-04 14:04:35 +00:00
alan 10049b8062 Chat info: account quota per harness (Claude rate_limit_event, Codex account/rateLimits, OpenCode unsupported)
Usage frames carry optional usage.account {harness, source, plan, as_of,
windows[{id,label,used_percent,resets_at}], unsupported}. Claude Code quota
comes from its rate_limit_event stream lines and the initialize account
(plan), shared across chats on the same account. Codex reads
account/rateLimits/read once per connection (re-read when a chat opens after
5 min) and merges account/rateLimits/updated. OpenCode exposes no quota API
and says so. The app's chat info sheet shows an Account usage section with a
progress bar and reset countdown per window, Material and Cupertino.
2026-11-02 18:57:13 +00:00
alan 80022ea41a Keep observing chats with an in-flight turn after the last client leaves
Chat attention notifications (questions, approvals, finished replies) come
from a session's event stream, which the hub only read while a room existed;
detach destroyed the room when the last client left, so a turn that finished
or asked with the app closed notified nobody.

A room whose last client leaves now stays observing, unattended, while its
turn is in flight or it holds an unanswered question/approval, and is torn
down when the turn ends (or after 6h for a stuck turn); at most 16 such rooms.
At server start, recently used open sessions whose harness reports a running
turn (OpenCode /api/session/active, Codex thread/turns/list) are observed
again so their reply still notifies. Settings, dedupe and app_notifications
recording are unchanged.
2026-11-02 16:07:42 +00:00
alan 6d430948a6 feat(chat): per-chat permission modes for Claude, Codex and OpenCode 2026-10-24 18:16:10 +01:00
alan 910028a75c Keep last reported OpenCode metrics while the newest assistant is in flight
Read a bounded newest-first page of eight assistants (4 MiB, no cursor traversal), selecting context and completed generation rate independently from the latest valid measurement matching Session.Info.model provider/id. Require assistant model identity; never pair an old model's measurements with the selected model's window. Context remains unknown across a newer compaction until a subsequent prompt reports usage; the last completed matching rate may survive compaction.

Unknown model metadata is cached for 15 seconds instead of five minutes, while known capacities retain their five-minute cache. Provenance remains canonical V2 Model.Ref, TokenUsage and request-created/streamed/completed fields cited in chat_usage.go. No live endpoint access, inference or service changes.

Isolated HTTP regressions cover in-flight/null/empty newest tokens with prior known metrics, post-compaction boundaries, independent prompt/rate selection, switched/missing model identity, duplicate known-zero measurements, over-limit page rejection and metadata recovery. Checked full internal/opencode suite, focused usage race suite, go vet ./internal/opencode and git diff --check.
2026-10-21 00:26:48 +01:00
alan ce3482b057 Expose native OpenCode chat usage snapshots and replay session metrics
Read V2 session accounting, latest assistant prompt/cache components and native request-to-stream boundary. Resolve capacity by location/provider/catalog id with bounded metadata caching. Coalesce active/final readbacks; retain message-less session snapshots without changing admission or compaction state.

Provenance: https://opencode.ai/v2/openapi.json and anomalyco/opencode V2 4617210822bdbb31e5749751afbfb4584ccedac8: packages/schema/src/token-usage.ts, session-event.ts; packages/core/src/session/usage.ts, projector.ts, message-updater.ts, runner/step.ts. Native output is visible output, reasoning separate. Session totals include all five non-overlapping components. Generation rate uses created-to-streamed, not tool-inclusive completion.

Limitations: metrics remain unknown for missing components, absent timing/model metadata, reads beyond bounded latest-message/catalog budgets, or context preceding compaction. No local pricing, token estimation or default capacity. V1 gets no invented cumulative metrics; older V2 events remain available when readback is unavailable. No deployment or protocol/web/docs changes.

Checks: go test ./...; focused usage/stream race tests; go vet ./internal/opencode ./internal/server; go build ./...; git diff --check.
2026-10-21 00:13:51 +01:00
alan 4969d667b3 Expose native chat compaction activity and retained replay 2026-10-20 22:17:41 +01:00
alan d3c7e6e784 fix: allow cold managed service discovery only at stage admission 2026-10-20 21:53:52 +01:00
alan bb98bde4fc fix: pin native exports to stage execution service 2026-10-20 21:47:04 +01:00
alan 1b8d0f2a75 fix(opencode): read V2 session exports directly from authenticated API 2026-10-20 20:43:42 +01:00
alan 68761652cf fix(codex): accept prepared chat attachments with model overrides 2026-10-20 18:07:00 +01:00
alan 35329e4022 feat(chat): broker Codex approvals and complete typed tool interactions 2026-10-20 17:41:35 +01:00
alan c78def70dd fix(chat): recover web approvals and questions across clients and reconnects 2026-10-20 17:23:07 +01:00
alan fdf0369ede Enforce runtime report contracts and recoverable session exports 2026-10-20 16:05:33 +01:00
alan e504780976 fix(chat): settle authoritative turns and make capabilities explicit 2026-10-20 15:45:44 +01:00
alan db88cebd0b opencode: retry one settling session export
A stage's final session write can land just after the step settles. Retry the
read-only native export once after 200 ms when its envelope is invalid or names
another session, so the stage records session.html instead of dropping evidence.
2026-10-20 15:16:19 +01:00
alan eafe6f1702 opencode: find the CLI without trusting service PATH
Fall back to Homebrew and local install locations when opencode is not on the
service's minimal PATH, so a launchd/systemd restart cannot fail a run with
exec: opencode not found.
2026-10-20 15:10:54 +01:00
alan 6bfe4c8921 chat: add model switching and preloaded instructions
Expose the OpenCode model list and session model switch over the chat protocol,
carry a per-session model provider on chat rows, and apply a preloaded behavior
brief as a durable session instruction entry when a chat is created.
2026-10-20 14:58:20 +01:00
alan f5ccec8e1f chat: deliver attachments and cancel runs immediately
Carry browser files as base64 prompt attachments, write them to private
temporary files and pass file:// references to OpenCode, and map the user
turn's top-level files back into history. Replay a running step on subscribe,
forward only a caller-supplied msg_ id, and persist cancel on the run and live
step before interrupting the runner.
2026-10-20 14:30:53 +01:00
alan 526c19fc21 web: shared chat stars, pipeline mini graphs and agent questions
- Persist chat stars in the operator-session registry (chat_star) so every
  browser/device shows the same Starred group; migrate old local stars once.
- Add a compact pipeline graph shape to list responses and draw a lightweight
  list miniature; replace the cryptic id/version line with the stage count.
- Surface OpenCode form questions as a chat card (chat_answer), replay a
  pending form to late subscribers, and notify for background questions.
- Make the mobile dock's Search cell equal to every destination, keep the
  tab row visible with 100svh, and let Source use the full pane height.
- Let a fresh sign-in auto-connect to its own origin; use a Lax session cookie
  with Expires so Remember me survives app/link launches.
- Keep shipped starters and the skill agnostic: no repository paths, project
  areas or personal device commands; add Diagnose/Fix and Research starters.
- Refresh the installed skill and document the new browser conventions.
2026-10-20 03:11:37 +01:00
alan 7da3d54013 chat: reconcile history by canonical message identity 2026-10-19 00:08:30 +01:00
alan f5f682a990 test: strengthen background shell output verification 2026-10-18 20:23:43 +01:00
alan ded7927778 WIP: preserve remaining background task output work 2026-10-18 17:42:15 +01:00
alan fd4c329eaf WIP: preserve background task output API 2026-10-18 17:10:44 +01:00
alan 27108bcc0c Merge branch 'main' into manager-skill-bootstrap 2026-10-18 15:23:27 +01:00
alan 18e7d073a6 Harden paged chat history loading
Close the per-thread history loading gate before launching requests, make live/history part reconciliation linear, and reject duplicate history envelope fields.

Complete task-owned history paging work remains preserved in the preceding recovery commit. Checked packaged templates and packaged authoring skill references: neither needs an update; docs/notes/large-chat-history.md records the stale shared documentation.
2026-10-18 15:21:09 +01:00
alan 1c89414896 Merge commit '4b66e608' into manager-skill-bootstrap
# Conflicts:
#	internal/opencode/chat_v2_test.go
2026-10-18 15:03:46 +01:00
alan ff1775e11f Merge branch 'main' into large-chat-history 2026-10-18 15:03:22 +01:00
alan ab9181eee9 Preserve manager skill bootstrap work 2026-10-18 15:03:22 +01:00
alan 998da0e7af WIP preserve large chat history recovery 2026-10-18 15:03:18 +01:00
alan e9d902213e Preserve background shell visibility across readback races
Reconcile authoritative shell snapshots with bounded lifecycle journals so concurrent exits and creates cannot be overwritten, coalesce observation setup, and retain verified ownership across reconnects. Add deterministic reconciliation and cancellation regressions plus stable limited-visibility handling.\n\nChecked packaged templates and authoring skill references: none need updating. The task-owned docs note records the stale shared chat documentation for docs-fold; shared documentation was not edited.
2026-10-18 12:54:36 +01:00
alan 7d9490bba1 chat: name the in-flight state, and surface background processes
Two gaps in the chat's in-flight feedback.

The turn indicator no longer reads a bare `Working…` for every state. A new
pure derivation (TurnPhase/turnPhase/turnPhaseLabel in ui/chat/ChatFormat.kt)
labels the headline from evidence already on the wire: `Thinking…` while text
or reasoning deltas are still arriving (within TURN_THINKING_WINDOW_MILLIS),
`Running a tool…` while calls are in flight, `Waiting…` otherwise. No
percentage, ETA or invented progress.

The agent's shell commands are now surfaced end to end as their own frame kind,
so a background process (a dev server, a watching build) that outlives its tool
call is visible and clears when it exits.

Server:
- protocol/chat.go adds ChatEventShell, ChatShell (id, status, command, *int
  exit — a pointer so exit 0 is not "absent") and ChatEventFrame.shell.
- opencode/chat.go maps shell.created/shell.exited through a new exported
  ChatStreamState, attributing created via info.metadata.sessionID and exit via
  the ids the stream already surfaced; another session's or an unattributed
  shell is ignored, an id-less shell fails the stream. No cwd/file/credential is
  carried.
- server/chat_hub.go retains still-running shells (chatShellLimit plus the
  shared byte cap) and drops them on exit; chat_stream.go replays them on
  chat_subscribe, the shell half of the resume (a shell is not a turn, so the
  message snapshot cannot carry it).

App:
- data/protocol/Chat.kt adds ChatShell, ChatEventFrame.shell, EVENT_SHELL,
  SHELL_RUNNING/SHELL_EXITED.
- ui/chat/ChatStore.kt stamps ChatThread.lastDeltaAt on each delta (cleared when
  the turn settles) and keeps ChatThread.shells across a chat switch; a shell
  never marks the thread running. streamResumed drops shells so the subscribe
  replay re-syncs the still-running ones.
- ui/chat/ChatTranscript.kt: RunningIndicator prints the phase label; a new
  always-visible BackgroundProcessBar names each running shell.
- ui/chat/ChatConversationPane.kt shows the bar whenever a shell is running,
  whether or not a turn is.

Tests extend the server's event mapping (opencode/chat_v2_test.go,
server/chat_test.go) and the app's pure folds (new
ui/chat/ChatInFlightStateTest.kt, 15 tests), pinning the shell mapping, the
other-session rejection and the "background process outlives the turn" state.

Checked and intentionally unchanged:
- No packaged OpenCode skill reference documents either surface.
  internal/author/skill/references/operations.md describes the brokered chat_*
  protocol in prose without naming frame kinds or the app indicator, so it stays
  correct as-is; no reference was added, so install.go's managed inventory needs
  no change.
- This repository has no packaged templates directory.
- Shared docs are not edited here per the map: docs/notes/chat-shell-background
  -process.md records what is now stale in docs/cli.md and android/README.md for
  the docs-fold writer.

Verification (this session): gofmt -l clean, go build ./... and go vet ./... OK.
Android unit suite and the on-device capture were run in the preceding review
stage; see the note for the live-verification limitation.
2026-10-18 09:45:28 +01:00
alan 798e958cb7 chat: fold an agent turn into one reply, split reasoning from answer, keep tool name/input
The phone's chat transcript rendered one agent reply as ~36 bubbles, each with
its own thinking block, and a finished tool call lost its name and its input.

- Turn fold (android): ChatFormat.kt gains the pure ChatTurn / TranscriptRow /
  transcriptRows fold - each run of consecutive assistant messages between two of
  the operator's messages is one agent turn - and ChatTranscript renders one
  bubble per turn: the turn's single collapsible thinking block (all its
  reasoning, in order, growing live while it streams), then its tool-call chips,
  then one answer block of just the turn's text parts. AssistantParts/MessagePart
  are replaced by AgentTurnItem/UserMessageItem; ChatConversationPane counts the
  folded rows.
- Delta part ids (server + client): internal/protocol/chat.go adds
  ChatDeltaPartID(messageID, kind, ordinal), mirrored as ChatProtocol.deltaPartId
  in data/protocol/Chat.kt, and NormalizeChatEvent keys a text or reasoning delta
  on it. OpenCode numbers a message's text and reasoning parts independently from
  0, so the old "%s#%d" gave the first text delta and first reasoning part the
  same id: the answer was appended into the thinking block, and the server's
  retained state (chat_hub.go) re-collided on resume. ChatStore's upsert now
  routes a delta through the kind-aware deltaPartId fold, so it stays robust even
  against a peer that still shares one id.
- Tool fields (server + client): NormalizeChatEvent takes a call's arguments from
  session.tool.input.ended's text as well as session.tool.called's input object
  (toolInput), and chat_hub.go's new mergeChatToolPart folds each tool frame onto
  the retained part so the progress/success frames that omit name and input never
  blank them. ChatFormat.kt's mergeToolPart mirrors that on the client, so the
  chip and panel header keep the real tool name and the panel shows INPUT beside
  OUTPUT.

Tests: chat_v2_test.go and chat_test.go add the text/reasoning id-collision and
the tool name+input retention cases; ChatReasoningTurnTest, ChatTranscriptTest
and ChatRunningWorkTest cover the turn fold, the collision and the tool lifecycle.

Checks: Go build, vet, gofmt and the package tests pass (go build ./... &&
go vet ./...; gofmt -l . empty; go test ./internal/server ./internal/opencode
./internal/protocol ./internal/stage ./internal/pipeline; go test ./...).
Android passes offline with --no-daemon (assembleDebug and the full
testDebugUnitTest suite, 660 tests). The on-phone observation was not performed:
the device lock was held by another run and adb was not available here.

Documentation inventory checked: no packaged OpenCode skill reference in
internal/author/skill/references/ and no packaged template documents the app's
chat transcript, this delta part-id derivation or the tool-field retention, and
no internal/author/ managed file inventory entry names any touched file, so none
of them needs updating. The shared android/README.md behaviour statements are
made stale by this change and are recorded instead in
docs/notes/chat-transcript-turn-fold.md for the docs-fold writer, per the repo
rule that an item never edits a shared document itself.
2026-10-18 01:47:52 +01:00
alan 0ba1204895 chat: attach to the operator's own OpenCode by pairing, fall back honestly
Brokered chat accepted an operator-supplied endpoint (-opencode-endpoint /
PIPELINES_OPENCODE_ENDPOINT) but failed closed against the operator's running
V2 service: that API authenticates every request with HTTP Basic auth (fixed
user "opencode" plus a password), the broker had no credential, so the health
probe answered 401 and startup logged "OpenCode endpoint ... is unreachable or
is not an OpenCode service", disabling chat entirely.

Established from the installed binary (opencode v2.0.20), not from docs:
`opencode --help` advertises `api`, `pair`, `serve`, `service` and `auth`;
`GET /api/info` is unauthenticated-401 with www-authenticate Basic realm
"Secure Area"; Basic auth user `opencode` with the password from
~/.local/state/opencode/service.json answers 200; `POST /api/pair` returns a
code and `GET /auth/connect/{code}` returns a token that is then accepted as
the Basic password.

- internal/opencode/pair.go (new): PairEndpoint does the pair exchange over the
  shared nativeRequest transport (same auth, bounds and JSON checks);
  ReadServiceCredential reads the operator's local service password under the
  private-file rule; OpenEndpointAttached resolves the credential in precedence
  order - explicit password file, a paired token stored by an earlier run, then
  a fresh pairing bootstrapped by the local service credential - stores the
  token owner-only and re-pairs once when a stored token is refused (401).
- internal/opencode/endpoint.go: OpenEndpoint wraps probeEndpoint, which returns
  the connection even on failure; Connection.unauthorized (set on HTTP 401 by
  the request paths, cleared per probe) distinguishes an authentication refusal
  from any other refusal.
- cmd/pipelines-server/main.go: the endpoint attach uses OpenEndpointAttached
  with the paired-credential file beside the pipeline database. An endpoint that
  cannot be attached logs a line naming it and falls back to the server's own
  OpenCode instance instead of leaving chat refused.
- internal/protocol/status.go, internal/server/websocket.go: get_status gains an
  opencode object (health = endpoint | fallback | spawned | unavailable, plus
  the endpoint url), the honest status evidence for the fallback. No credential
  is ever placed there.
- Tests: internal/opencode/pair_test.go, internal/protocol/status_test.go and a
  TestStatusReportsOpenCodeAttachment case in internal/server/status_test.go.

Repository checks: go build ./..., go vet ./... and gofmt -l . clean;
go test ./internal/... ./cmd/... green.

Packaged templates and skill references: the repository has no template tree
that mentions the OpenCode endpoint, and no packaged reference file is added, so
internal/author/install.go's managed inventory is unchanged. The packaged
authoring reference internal/author/skill/references/operations.md (the endpoint
paragraph around line 289, the "clear refusal and no fallback" wording and the
password-file/username-only credential story, and the missing opencode status
field) is now stale; per the maintenance convention the item does not edit the
shared document and instead records the stale points, with the exact wording
they should take, in docs/notes/chat-persistence.md for the docs-fold writer.
2026-10-18 00:55:26 +01:00
alan 1f75e4797e Broker chat from an operator's own OpenCode endpoint and adopt existing sessions
Add an opt-in way to broker chat from an operator-supplied OpenCode service
instead of the instance the server spawns for itself, and a way to adopt a
session that already exists on that endpoint so it appears in chat_sessions and
can be continued from the app.

- Endpoint selection: the `-opencode-endpoint` server flag (defaulting to
  `PIPELINES_OPENCODE_ENDPOINT`) opts in; precedence is explicit flag >
  explicit environment > the endpoint recorded on a previous run, with the
  spawned instance as the default. opencode.OpenEndpoint validates the
  reference once (http(s), host, no userinfo/query/fragment/path), detects the
  backend from its own /api/info (v2) or /global/health (v1) contract, and
  requires a streamable text/event-stream event path. It owns no process
  (Close is a no-op) and never calls startServe; every failure names the
  endpoint and disables chat rather than silently falling back. An
  authenticated endpoint takes an optional password only through the private
  file PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE, with
  PIPELINES_OPENCODE_ENDPOINT_USERNAME overriding the detected default.
- Persistence: the validated choice is recorded in an additive single-row
  server_settings table so a restart with no flag/environment reuses it; an
  unreachable recorded endpoint disables chat with a clear message and no
  fallback.
- chat_adopt: a new protocol request (ChatAdoptRequest) with handleChatAdopt in
  internal/server/chat.go. It refuses a nil broker/registry/payload and a
  blank or foreign-shaped id before any endpoint call, reads the endpoint via
  the shared Chat.Session (which reuses Sessions/decodeChatSessions), records
  through the existing RecordOperatorSession with the endpoint's directory and
  title verbatim, and echoes the adopted session plus its registry row like
  chat_create. A missing id is refused naming the id and records nothing; an
  endpoint record with an empty directory is refused rather than substituting
  the server's working directory or home.
- CLI: `pipelines chat-adopt <session-id> [--json]` (usage, notes, help
  inventory, dispatch) with docs/cli.md updated under Chat sessions.
- Autostart preserves the endpoint variables (and the password-file reference,
  never an inline secret) via serviceEnvironmentKeys.

Checks before committing:
- Package location: the change is user-facing chat behaviour, so the packaged
  authoring skill reference internal/author/skill/references/operations.md is
  updated in the same change (Brokered OpenCode chat section) with a dated
  verification-evidence entry and the not-deployed state. No new reference file
  is added, so internal/author/install.go's managed inventory is unchanged.
- Packaged templates: this repository packages no template set for this
  behaviour and none references the chat endpoint, so no template needs
  updating.
- Verification: `go build ./...`, `go vet` on the touched packages, `gofmt -l`
  clean and `go test ./...` all pass. The unit tests cover the endpoint
  validation/precedence, the adopt happy path and refusals, the recorded
  endpoint round-trip, the protocol round-trip and the CLI dispatch. The live
  scratch-server check against the operator's real endpoint was not run in this
  change.

Nothing unrelated is staged; docs left stale (README and other shared documents)
are not edited here and are for a single folding writer.
2026-10-17 20:14:11 +01:00
alan 58c6b9b7c6 server: export a finished stage's real session as session.md and session.html
Every OpenCode-harness model stage now writes its real session into its own
step artifacts directory as session.md and session.html, so the existing
bounded artifact listing, the /artifacts/<run>/<step>/<name> serving path and
the artifact scan find and serve them with no special casing, while the stage
keeps its bounded preview in the run record unchanged.

- internal/opencode/export.go adds the one shared native export invocation and
  the exact session-ID/messages validation used by both Connection.Messages and
  the new ExportSession, so the readback path does not diverge. The backend's
  published subcommand is used (v1 `export <id>`, v2 `session export <id>`),
  the source read is capped at 8 MiB, and a larger session is read as a prefix
  and reported truncated instead of failing. boundedOutput.ReadFrom keeps the
  cap effective so overflow and the truncation path are real.
- internal/stage/session_export.go renders markdown and html with a metadata
  header, every role and every part (unknown part types as raw JSON, every
  session text escaped in html), atomic temp+rename writes that never overwrite
  an existing file, a visible truncation banner at both ends when the source or
  the 2 MiB rendered cap cuts it, and an honest 0-message header for an empty
  session rather than fabricated text.
- protocol.SessionExport and RunStep.SessionExport are stored in a new
  step_session_exports table (CREATE TABLE IF NOT EXISTS, so an old database
  gains an empty table with no migration) loaded through the existing main
  SELECT alongside the other per-step evidence and deleted by run retention.
- internal/server/runner.go exports after the post-stage filediff capture and
  before scanArtifacts, with context.WithTimeout(context.WithoutCancel(ctx),
  10s); it never waits for session idleness and a failure or a Pi stage (no
  native export path) records a sanitized diagnostic and continues, never
  changing the stage status, outcome, target, timing or result validation.

Reflected where it belongs: the packaged skill references
(internal/author/skill/references/operations.md and delivery.md) carry the new
Session export rules and the run-artifacts bullet, and docs/stage-artifacts.md
documents the names, the <run>/<step> paths, the served URL, the caps, the
truncation labels, failure isolation and the Pi limitation. The packaged
templates (examples/*.md) only tell a stage to save its own artifacts and say
nothing about the server-written session export, so none needed updating; no
new reference file was added, so install.go's managed inventory is unchanged.

Shared documentation: README.md's per-step artifacts sentence is now stale - it
should name the exported session alongside images, screenshots, reports and
logs. It is deliberately not committed here; the shared documents are folded by
the single documentation writer.

Checks: gofmt -l on the touched packages produced no output; go vet ./...
passed; go test -race -count=1 ./... passed.
2026-10-17 19:40:43 +01:00
alan 7b72b8f20f stage: retry pre-admission harness reach failures and widen repair deadline
Treat a failure to reach the harness before any prompt or tool call is
admitted (connecting or creating the session) as a distinct retryable
reach failure, so a transport blip at the first stage no longer ends a
mutating run; keep post-admission readback/poll/agent failures retried
only on an explicit read-only stage and never replay admitted tool work.
Preserve the true cause when the context is already done (join ctx.Err
with the typed transport error) and report a sanitized unknown provider
error name/status instead of a blanket summary.

Make the isolated format-repair deadline proportional to the stage
timeout (floored, capped and clamped to remaining minus a margin) so a
slow-but-repairable result is recovered without ever extending the stage
deadline; the bounded ladder, value guard, deny-all formatter session,
cumulative usage accounting and no-tool-replay rule are unchanged.

Update docs/model-results.md, docs/pipeline-performance-review.md and the
packaged skill references; add stage, opencode and server fixtures.
2026-10-17 14:51:09 +01:00
alan 18398dfa5b chat: give the operator their own sessions, separate from run sessions
chat_sessions used to list exactly the OpenCode sessions the pipelines own,
filtered through pipeline.SessionOwner (run_steps/run_session_owners), so an
operator-created chat was an accident of the run-ownership table and the
operator's working sessions were mixed with the internals of running pipelines.

Add a first-class operator session:

- internal/pipeline/operator_sessions.go: a dedicated operator_sessions table
  (session_id PK, directory, title, tag, created_at, last_used_at) with
  RecordOperatorSession (upsert preserving created_at), a one-statement
  TouchOperatorSession (no-op for a non-operator id), OperatorSessions bounded to
  128 rows most-recently-used first, and OperatorDirectories (bounded MRU,
  deduped). run_steps/run_session_owners and SessionOwner/OwnedSessions are
  untouched.
- internal/server/chat.go: chat_sessions returns operator sessions only - it
  reads the registry once, intersects it with one broker session-list call, fills
  directory/tag/created/updated from the registry, sets busy for a session held
  by another connection, keeps MRU order, and stays fail-closed (empty list, never
  the endpoint's whole list). A pipeline stage session and an untagged row can
  never be listed. chat_create resolves the directory (empty/'~'/'~/...' ->
  operator home; relative or missing rejected before any OpenCode call), calls
  broker.Create(title, resolved) and records the row with the operator tag.
  chat_directories returns home first then bounded (8) deduped recents. A
  successful prompt touches the operator session without affecting pipeline
  prompts.
- internal/opencode, internal/protocol, internal/server/websocket.go and
  message.go: unscoped session list, Create posts {"title":...,
  "location":{"directory":...}} to POST /api/session, additive protocol fields
  (omitempty) and the ChatDirectories request/response, plus the OperatorRegistry
  option defaulting to the first store. One OpenCode transport per server is
  unchanged.

Docs and references: docs/cli.md gains a "Chat sessions" section documenting the
operator-only fail-closed list, directory defaulting/rejection, chat_directories
(home first, deduped, bounded 8) and why a dedicated request was chosen.
internal/author/skill/references/operations.md's stale "Brokered OpenCode chat"
text (chat_create unbrokered, run_steps filtering, "listed the owned scratch
session" evidence) is rewritten to the operator-session registry, the fail-closed
filter, directory defaulting and the corrected live-test wording. No new
reference file, so internal/author/install.go's inventory is unchanged.

Checked for staleness elsewhere: README.md, the docs/ topic pages and the
packaged server/TUI templates carry no chat-session ownership claims, so none
needed updating.

Verified: gofmt -l clean; go vet and go build ./... clean; go test -count=1
./internal/pipeline/... ./internal/protocol/... ./internal/opencode/...
./internal/server/... and the full go test -count=1 ./... pass.
2026-10-17 11:14:25 +01:00
alan 30c1ed442e chat: broker OpenCode v2 chat over the owned serve SSE endpoint
The installed OpenCode 2.0.20 exposes the authenticated SSE event firehose at
/api/event and the /api HTTP surface, but Detect selects backend "v2" and Open
returned no owned process/URL, so chat stayed disabled and every chat_* request
was answered with "chat is not configured on this server".

Add opencode.OpenStream/OpenChat: for either backend they start the single owned
opencode serve process, discover the loopback URL and verify the backend health
contract (/api/info for v2, /global/health for v1). main and the live test share
OpenChat so the selection cannot drift. Chat now streams real incremental
session.text.delta/session.reasoning.delta frames via the existing
Connection.EventStream + NormalizeChatEvent, with no polling and no fake
streaming.

- Authenticate the owned endpoint with the per-backend user (opencode for v2,
  pipelines for v1); the v2 server ignores OPENCODE_SERVER_USERNAME.
- Send the V2 prompt shape {"text":...}, which the v1 translation also accepts.
- Skip firehose event types the adapter does not surface before decoding their
  data, so session.instructions.updated (delta is an object) no longer fails the
  stream.

Unit tests cover the per-backend user, the prompt shape/auth, the captured real
V2 event shapes and the selection guards. An opt-in live test drives
chat_sessions/chat_messages/a completed chat_prompt/an interrupted chat_prompt
against the installed OpenCode. Update the packaged operations reference with the
realized capability, dated evidence and deployment state.

Checks before commit: the packaged authoring reference
internal/author/skill/references/operations.md is updated in this change; no new
reference file was added, so internal/author/install.go's managed inventory is
unchanged and the internal/author tests pass. No packaged template describes the
brokered chat surface, and neither README.md nor the topic docs under docs/ (nor
web/) document it, so none of them needed updating.
2026-10-17 01:54:14 +01:00
alan 1818a06d2f Restrict chat_sessions to server-owned sessions
chat_sessions now brokers GET /api/session but filters the global list to
the sessions this server recorded in run_steps, deduped by session id, and
fails closed to an empty list when no ownership source is configured. A
session another client holds (in-server claim, released on stream end or
disconnect) or an active run is marked busy; a second client's chat_prompt
for a held session is rejected before any OpenCode call. chat_create stays
unbrokered.
2026-10-16 09:21:50 +01:00
alan 3ff5cd8838 Poll OpenCode permission requests and forward chat_reply 2026-10-16 08:06:39 +01:00
alan b28f88be66 Add tests proving chat_interrupt stops a running chat turn
The chat_interrupt path was already wired end to end (protocol type,
server dispatch through handleChatSimple to broker.Interrupt, and the
adapter POST /api/session/{id}/interrupt), but nothing exercised it
against a live stream. Add the missing coverage:

- internal/opencode/chat_test.go: pin the adapter's outbound call
  exactly (POST /api/session/ses_1/interrupt, empty JSON body, one
  request, nil on 200) plus a non-nil error on HTTP 500.
- internal/server/chat_test.go: drive the real opencode.Chat adapter
  over an httptest SSE fixture that holds the turn open until the
  interrupt arrives, then assert the run ends, the interrupt is
  acknowledged, no error frame is sent, and the prompt/interrupt posts
  and interrupt path match. Also cover invalid-session rejection,
  the unconfigured-broker error, and broker-failure reporting, adding a
  spare interruptErr hook to the scripted fakeChat.

Production code is unchanged: verification found no gap in the existing
interrupt transport. Tests use httptest loopback fixtures only and do
not touch the live OpenCode service.
2026-10-16 06:43:02 +01:00
alan 915016df0b Expose OpenCode conversation history in chat_messages
decodeChatMessages only understood the native-serve {info,parts} envelope,
so records from the V2 HTTP API (GET /api/session/{id}/message) decoded
with an empty role and were silently dropped, leaving chat_messages with
empty history. Teach nativeChatMessage to read the V2 top-level shape
(id/type/agent/model/time, parts under "content", user prompt as a bare
string) while keeping the native {info,parts} path via role/id/model/agent/
created accessors and a contentParts fallback.

Add seeded-session evidence: a decoder table test covering both envelopes
(user + assistant with text, reasoning and a completed tool part carrying
input, content and status) plus handler tests that drive chat_messages
through the broker fallthrough and through the real adapter.
2026-10-16 05:24:00 +01:00
alan b8b545accd Stream brokered OpenCode chat replies over /connect
Add the server-side half of the brokered chat path (route B): the
opencode.Chat adapter forwards chat_prompt to POST
/api/session/{id}/prompt through the owned Connection.Call translation
and derives chat_event frames from the authenticated /api/event SSE
firehose (text and reasoning deltas, tool parts with their status
transitions, step and usage). Every pushed frame carries a stable
session and message id, with a last-message-id fallback so step/tool
events that omit the assistant message id stay attributable.

The /connect handler keeps per-session retained state (chatHub) capped at
1 MiB with least-recently-updated eviction at 128 turns, so a
reconnecting client re-syncs through chat_messages instead of replaying
deltas the OpenCode per-session log never resends. Prompt dispatch
subscribes before posting and buffers pre-ack frames to preserve order,
and cancels the stream on disconnect so no goroutine leaks. chat_sessions
and chat_create are declared but not yet brokered: they answer with an
explicit protocol error rather than the generic Pong.

Reuse the existing transport, validation and normalization; no second
OpenCode transport or credential path is introduced.

Tests: protocol golden round-trip, adapter normalization + v1/v2 Call
translation, and handler ack/stream/validation/resume/disconnect, plus a
real-adapter no-tool evidence harness.
2026-10-16 04:09:14 +01:00
alan 05ae530442 Make Pipelines Docker-only with OpenCode and Pi
Install current verified harness releases inside Docker, preserve persistent accounts and settings, and provide separate interactive and pipeline model defaults with terminal onboarding and fuzzy pickers.

Add Docker-aware authoring transport, Pi stage execution, bounded workflow controls, reliable final-result readback and usage settlement, and finite short-lived CLI pipe draining. Keep dated installation evidence and packaged authoring guidance consistent.

Verified with a real Docker installation, both harness stages and interactive authors, the built-in plan/implement/review starter, independent host race/vet checks, installer tests, and packaged skill tests. Generated release receipts stay ignored in clean checkouts.
2026-10-11 23:00:25 +01:00
alan a66d540125 Add stage execution limits and result-first workflow views 2026-10-10 03:03:46 +01:00
alan a1c0eb4a72 Handle native structured-format incompatibility and preserve failure evidence 2026-10-10 00:01:02 +01:00