Commit Graph

52 Commits

Author SHA1 Message Date
alan ceffd5d0d1 fix(stage): retain inline audit payloads once without losing native evidence 2026-10-21 16:59:20 +01:00
alan 22801a9b06 fix(stage): align session export render cap with artifact bound
Six computed Flutter runs stopped at the export handoff gate because the
rendered session.html cap was 2 MiB while their complete sessions (well inside
the 8 MiB source read bound) rendered between 2.25 and 4.28 MiB once html
escaping and the readable projection duplicated native text.

Raise SessionExportFileLimit to 8 MiB, the server's existing per-artifact file
bound, so a complete export is still listed and served. Normal export
verification, versioned repair and the handoff gate keep using the single
shared constant. The source read bound is unchanged, and an over-cap render is
still visibly truncated and recorded partial.

Add focused regressions for a complete export above the old cap, an over-new-cap
file rejected as partial, repair above the old cap leaving original evidence
untouched, the gate accepting the larger repair, and the constant staying inside
the artifact file bound. Update the artifact, handoff-gate and operations docs
and record the diagnosis in docs/notes/session-export-render-cap.md.
2026-10-21 15:26:29 +01:00
alan 724de27561 feat(stage): honor per-stage reasoning effort across native harnesses 2026-10-20 23:51:14 +01:00
alan 9ce2c5d143 feat(stage): apply and verify Pi reasoning effort before prompting 2026-10-20 23:45:17 +01:00
alan 2aaf7fe2cc feat(pipeline): parse optional reasoning effort for model stages 2026-10-20 23:40:14 +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 f87e1ed488 runner: gate stage handoff on settled verified session export 2026-10-20 20:55:57 +01:00
alan 3d35e8a863 fix(stage): export settled Pi native sessions as escaped HTML 2026-10-20 20:45:56 +01:00
alan d7e99a19d6 fix(audit): preserve complete native message data in session HTML 2026-10-20 20:45:56 +01:00
alan cb57da5dfc fix(stage): persist every V2 model generation in tracked sessions 2026-10-20 20:43:42 +01:00
alan 1b8d0f2a75 fix(opencode): read V2 session exports directly from authenticated API 2026-10-20 20:43:42 +01:00
alan 5014c9e61f fix(stage): supply runtime context when read is not declared 2026-10-20 19:19:07 +01:00
alan fdf0369ede Enforce runtime report contracts and recoverable session exports 2026-10-20 16:05:33 +01:00
alan 0219173327 stage: say that the shared public folder is the absolute path
A probe stage read "public/" in its task, created a workspace-relative public/
folder, and also copied to the run's shared path. The prompt now states that the
absolute path is the shared folder and a relative public/ is a different,
unshared directory.
2026-10-19 23:33:29 +01:00
alan 217e11da1d Merge branch 'main' into turn-integration
# Conflicts:
#	internal/server/runner.go
#	internal/stage/model_prompt.go
#	internal/stage/model_run.go
#	internal/stage/model_test.go
2026-10-19 22:32:13 +01:00
alan 19d7009510 stage: widen the timeout-reset test deadline
The successful retry in TestDefaultRetriesAndTimeoutResetEachAttempt was
racing its own 20ms deadline when the full suite ran in parallel. Keep the
two-attempt behavior and give the retry realistic headroom.
2026-10-19 22:30:34 +01:00
alan e37b864c40 stage turns: replace JSON results with file-based markdown turns
Each model visit now gets <run>/stages/<seq>-<stage>/ with input.md,
memory.md, output.md, private/ and a shared run-level public/. The model
reads the two input files, follows the stage's instructions verbatim and
returns complete markdown; only the # outcome section is parsed.

- add internal/turn layout, render and output parsing
- write input.md/memory.md before a visit and output.md from the final
  message; inventory all turn files as stage artifacts
- accumulate completed turns and system-written public file additions in
  memory, including across retries and resume
- remove the JSON envelope, strict field validation, line format and the
  repair ladder for model stages
- republish pipeline authoring prompts and docs in the new style

Checks: go build ./..., go vet ./..., go test -count=1 ./..., gofmt -l .
2026-10-19 22:27:44 +01:00
alan 72aecd8b1f Remove resource pools, leases and wait queues
Drop the resource allocation feature end to end: store tables and migration, runner scheduling and cleanup, protocol types and commands, CLI commands, TUI screens, tests and docs. Existing databases open cleanly and definitions carrying a retired resources block still validate.
2026-10-19 22:27:27 +01:00
alan 31d78cc065 stage: expose resource targets to model harnesses 2026-10-18 23:33:30 +01:00
alan a022b58c5c Wire pool resource targets through runner and repair quarantined-member handoff 2026-10-18 23:20:55 +01:00
alan 2cdb9a9e93 Stabilize guarded model delivery
Add validated OpenCode-only delivery capabilities, canonical linked-worktree access checks, isolated candidate verification, and guarded main settlement.

Wire the bounded reconnect-foreground controlled HTTP fixture through ordinary server construction so target verification obtains server-controlled provenance and rejects unknown or incompatible fixture evidence.

Checked packaged templates and packaged authoring skill references; no updates are needed because this draft-only infrastructure activates no definition. Recorded the stale reference and activation guidance in docs/notes/delivery-stabilization.md for the docs fold.
2026-10-18 14:50:18 +01:00
alan 9130ae8c7a Add stage-exclusive resource waiting
Add durable FIFO capacity-one resource leases for executable stages, including cleanup-confirmed release, conservative restart quarantine, queue state events, and CLI/TUI/Android waiting presentation. Add scheduler, cleanup, protocol, client, and Android coverage plus a proposed Android v3 resource draft.

Checked packaged templates and authoring skill references: neither needs updating in this item. The per-item docs note records the shared documentation that docs-fold must update; no shared README or packaged reference was edited.
2026-10-18 12:30:30 +01:00
alan 31aec05f99 Scope stage artifact access by run visit
Derive validated same-run visit artifact capabilities in the runner and pass them to OpenCode and Pi clients. Permit supported file tools to read completed prior visits and write only the current visit, preserving workspace, secret, database, and shell restrictions.\n\nChecked packaged templates and authoring skill references: neither needs updating in this item; docs/notes/scoped-artifact-access.md records the shared documentation staleness for the docs-fold writer.
2026-10-18 12:02:37 +01:00
alan 31d8f4a6d5 Distinguish active stage deadlines from harness transport failures
Identify configured attempt expiry during V2 active-session idle waits and retain bounded phase, timeout and session diagnostics without claiming a lost response. Preserve genuine operation failures, error identities, redaction, cleanup and admitted-work replay protections. Add stage regressions and scratch-server CLI/websocket retention coverage.

Checked packaged templates in examples and the pipeline template generator: none needs updating because timeout configuration and contracts are unchanged. Checked packaged authoring skill references: debugging.md needs a STAGE DEADLINE playbook and clarified transport guidance. Recorded that stale shared documentation in docs/notes/stage-timeout-diagnostics.md for docs-fold; shared documentation was deliberately not edited.

Verification: go build ./...; go vet ./...; go test ./...; go test -count=1 ./internal/server ./internal/stage ./internal/pipeline ./internal/protocol; go test -count=1 -run TestStageDeadlineDiagnosticThroughCLIAndWebsocket -v ./internal/server; gofmt -l .; git diff --check. All passed. Live-provider behavior not tested; no deploy or deployed-service restart.
2026-10-18 11:17:01 +01:00
alan 95362134aa session export: write only session.html, retire the markdown export
A stage's session was exported twice, as session.md and session.html, and both
files were presented. It is now one html file; the markdown export is retired.

- internal/stage/session_export.go: ExportSession renders and writes exactly one
  file, session.html, via writeSessionFile; renderSessionMarkdown and its helpers
  are gone; SessionExportResult carries HTML/HTMLBytes only. The source read, the
  8 MiB source / 2 MiB rendered bounds, the truncation banner, the
  never-overwrite rule and the honest empty-session handling are unchanged.
- internal/protocol/runs.go: SessionExport drops markdown/markdown_bytes (a
  record written before the change still decodes; unknown fields are ignored),
  and adds LegacySessionMarkdownArtifact with RunStep.PresentedArtifacts(), the
  one Go rule that hides the retired session.md from every artifact listing.
- internal/server/runner.go: evidence.Markdown/MarkdownBytes are no longer copied.
- internal/tui: the artifacts panel, the recorded count and the per-visit summary
  derive from PresentedArtifacts(), so the terminal never lists session.md.
- web/src/app.js: the spike's renderArtifacts applies the same filter.
- android: the Session section is the html export alone in a WebView — SessionView,
  the Markdown/HTML toggle and the session markdown path are removed;
  presentedArtifacts(step) filters the retired session.md out of the per-visit
  gallery, the run gallery and its count, the verdict/selection lists and the
  timeline indicator; data/protocol SessionExport drops the markdown fields.
- Tests pin the single html file, prove no session.md is written and that a
  pre-existing one is neither overwritten nor presented, and prove a legacy
  export record still loads and its session.md is hidden.

The legacy session.md of an older run stays on disk (dated evidence); it is only
no longer produced and no longer presented.

Checks (macOS, Go 1.24, Android Gradle 8.11.1, 18 Oct 2026): gofmt -l . prints
nothing; go build ./... && go vet ./... clean; go test ./internal/... ./cmd/...
-> 19 packages ok, 0 failures; node --check web/src/app.js ok and node --test
web/test -> 20/20; gradle --offline --no-daemon :app:assembleDebug
:app:testDebugUnitTest -> BUILD SUCCESSFUL.

Packaged references checked: internal/author/skill/references/delivery.md and
operations.md both described the session.md+session.html pair, so both are
updated here to describe the single session.html export and the retired, hidden
session.md. README.md and internal/author/skill/SKILL.md carry no session.md
reference and install.go's managed inventory is unchanged (no reference added or
removed). docs/notes/session-html-only.md records the remaining stale shared
documentation (docs/stage-artifacts.md, docs/app-integration-verification.md) for
the docs-fold writer; shared docs are not edited by this item.
2026-10-18 10:06:49 +01:00
alan c1652e2bc6 Split chat/model/run files by concern (pure move)
Pure move: split the three multi-feature server files into per-concern files,
with no behaviour change - same package, same exported and unexported
identifiers, same call graph, same tests.

- internal/server/chat.go -> chat.go (broker seam, client token, dispatcher),
  chat_hub.go, chat_claims.go, chat_permissions.go, chat_sessions.go,
  chat_stream.go, chat_commands.go
- internal/stage/model.go -> model.go, model_run.go, model_failure.go,
  model_validation.go
- internal/pipeline/runs.go -> runs.go (read side), runs_schema.go,
  runs_create.go, runs_mutate.go, runs_sessions.go

Checked before committing:
- Packaged templates and internal/author/skill/references: neither refers to
  internal/server/chat.go, internal/stage/model.go or internal/pipeline/runs.go,
  so nothing there needed updating (the change is a move with no behaviour
  change).
- gofmt -l on the three packages: clean. go build ./..., go vet ./... and
  go test ./... pass. go.mod/go.sum unchanged.
- No test, docs, android/, install or Docker files touched.

Known stale path pointers deliberately left to the single docs writer (shared
docs) and out of scope (android/): docs/chat-verification.md and
android/README.md name the old file paths.
2026-10-17 21:09:08 +01:00
alan 3f5c11b7bf Record and expose per-run model usage (tokens, split, cost)
Carry the usage a model stage already measures for its budget
(stage.Budget.Snapshot()) onto the step as typed evidence and total it in
one pass, rather than a second harness read, a transcript parse or an
output-length estimate. A shared budget across stage revisits records only
the visit's increment, and a revisit that observes no new report records no
usage instead of a fabricated known zero.

- protocol: StageUsage/RunUsage/TotalUsage and UsageTotals.
- pipeline: step_usage table + migration, COALESCEd into the one step
  projection, FinishStep persistence, one json_extract history aggregate,
  retention removes the rows with their run.
- server: stageUsage maps the budget snapshot, stamping per-stage model and
  usage for every model stage (including failures).
- cli: inspect/stats human and JSON output.
- budget/pi: retain the reported in/out split, mark a total-only (Pi) report
  split-unknown, and keep an unreported cost unknown (never zero).

Evidence and docs updated in the packaged skill references and docs/cli.md;
the live database has no step_usage rows yet (all history predates this), so
per-run figures are reported as unavailable, not zero.
2026-10-17 20:40:56 +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 890d267c71 run attention: publish to ntfy and surface what needs the operator
Nothing told the operator that a run was waiting for a person or had failed; they
found out by going looking. A run that needs attention now reaches the ntfy they
already run, and the app answers "what needs me now" in one live, ordered surface.

Server (smallest change, reusing the existing publisher):
- internal/server/notify.go adds notifyRun, called from finishRunState (failed)
  and when a run parks on a human (runner.go runLoop). It publishes to the same
  already-configured `system` destination through the unchanged stage.PublishNtfy,
  so there is no second publisher, topic or service and the token handling is the
  stage's own. runAttentionEvent maps only waiting and failed; queued, running,
  succeeded, canceled and interrupted publish nothing.
- No storms: runner.attentionSent records sequence:event per run before publishing,
  so a run that stays waiting is never republished on a re-request or restart, and
  a stage notify policy that already covers the same event marks it first so the
  run-level default is suppressed. The set is dropped when the run is terminal. A
  delivery failure is logged, never fails the run, and is not retried.
- The payload names the run and pipeline and carries a click action
  pipelines://run/<id> (validated: absolute URL, no userinfo, no fragment, no
  credentials). PublishNtfy gained the optional click parameter; existing callers
  pass "".

App:
- AndroidManifest/MainActivity declare the pipelines://run/<id> deep link
  (singleTop); runIdFromDeepLink parses it and PipelinesApp opens that run once,
  clearing the link. It opens a run; it starts nothing.
- ui/Attention.kt is the pure model (status -> Decision/Failed/Finished or
  nothing, ordered by kind then newest-first) and ui/components/AttentionSurface.kt
  is the floating indicator plus bottom sheet. It is derived from the same run
  events the server already pushes, so an entry appears with no refresh and clears
  when resolved; a finished run clears once looked at, and any entry can be
  dismissed, persisted in SettingsRepository. The existing destinations, pill and
  bottom strip are untouched and no competing navigation surface is added.

Checked before committing:
- Packaged authoring skill references: internal/author/skill/references/
  notifications.md documents the automatic run-attention notifications and the
  app surface. The only packaged "template" carrying notify is that reference; no
  pipeline definition template exists to update and install.go's managed file list
  is unchanged (notifications.md already existed).
- Repository guidelines: docs/ntfy.md gains an "Automatic run-attention
  notifications" section and no longer claims "No block means no notifications";
  the top-level README phone-notifications note now says a waiting/failed run
  notifies automatically; android/README.md gains the dated feature section and
  supersedes the previous section's note that the attention surface was absent.
- docker.md, install docs and the CLI/TUI docs describe mechanisms this change
  does not alter; left as they are.

Tests: go test ./internal/server/... ./internal/stage/... ./internal/author/...
all ok; notify_test.go covers the event mapping and the real HTTP delivery
(destination, topic, click, no duplicate). Android :app:testDebugUnitTest ->
BUILD SUCCESSFUL, 58 suites / 531 tests / 0 failures (new AttentionTest, 13 cases,
covering ordering, appearing from a push, clearing on resolution, dismissal, the
empty case, persistence and the deep link). Device screenshots and the phone's own
notification are visual review's per the brief's device policy.

Scope: android/ plus the smallest server change; no new dependency, no run started
from the app, no installer or Docker change.
2026-10-17 16:11:57 +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 c41bf4f5b0 State each model stage's permitted tools in its prompt
A planner had no machine-readable view of the tool set later stages would
have, so it could emit acceptance checks that required tools (shell) the
implementer was not permitted, causing a blocked run.

modelPrompt now emits exactly one authoritative line naming the stage's
permitted tools, derived from the definition via the new effectiveTools
helper. effectiveTools reuses ToolNames: a present tools block, including
an explicit empty one, is returned as parsed; an absent block yields the
legacy mutating read/glob/grep/edit/shell bundle so it is never
misrepresented as empty or read-only. The bundle is declared once as
legacyTools and reused by tools.go, agent.go, pi.go and permissions.go.

The redundant client-side strings.Replace of the tools line is removed
from AgentClient.Generate and PiClient.Generate; the agent-only guidance
sentence is preserved by appending it in agent.go, and Pi appends a short
mapping line derived from piTools. Edit-scope and permitted-shell text,
routing, review, budgets and retries are unchanged.

Adds internal/stage/model_prompt_test.go covering explicit, absent and
explicit-empty blocks plus derivation edge cases, and a guard that the
agent prompt still carries the tools, edit-scope and shell-command text.
2026-10-16 23:34:39 +01:00
alan b05277a57d Add line-oriented result format for model and agent stages
Introduce a short, markdown-ish result format whose first non-empty line is
the declared outcome and whose "# output" section carries the routing data,
so stage output stops carrying multi-kilobyte prose inside a JSON envelope.

- New internal/stage/line_result.go: resultFormat() gates legacy JSON ('{'
  first) vs the new line format; decodeLineResult() parses outcome-from-first
  line, requires a JSON-object "# output" section, stores extra sections
  verbatim under normalised keys, and records a reserved result_parse status
  (parsed/partial/failed). Failures return a salvage Result plus
  ErrInvalidModelResult, and never route an undeclared outcome.
- internal/stage/model.go: write the raw response to raw-output.md (0600,
  best-effort) before parsing, and route the line format through
  decodeLineResult while leaving the JSON path (stageResultText ->
  decodeModelResult -> repairModelResult) unchanged.
- internal/stage/agent.go: agentResultText returns line-format text verbatim
  so the "# output" body is not stripped by the JSON-object extractor.
- internal/server/runner.go: merge a non-empty salvage Result into the error
  envelope under "salvage" on failure (a no-op for the legacy JSON path).
- internal/stage/line_result_test.go: raw-text fixtures covering happy path,
  missing/undeclared outcome, missing "# output", best-effort extras,
  adversarial prose, legacy JSON unchanged, >=64KB responses, and
  raw-output.md written before parsing.
2026-10-16 21:34:33 +01:00
alan 98bbc2deac Report recorded decision evidence and harden the Pi artifacts env
Refinements on top of the human decision stage (a6aff47):

- `pipelines decide` now reports the feedback the server actually stored for
  the chosen option, so a repeated (idempotent) decision shows the recorded
  evidence instead of the ignored request text. A repeated decision is covered
  by a new assertion that also checks the step output does not change.
- The decision option/feedback output keys are defined once in protocol
  (DecisionOptionKey/DecisionFeedbackKey) with a DecisionEvidence reader, and
  the store and CLI use them instead of bare string literals.
- piEnvironment drops any inherited PIPELINES_ARTIFACTS_DIR before spawning Pi,
  so the artifactsDir argument is authoritative and an ambient directory (for
  example Pipelines' own when a stage runs inside another stage) never leaks
  into a child that was given none. Covered by a test with an ambient value set.
2026-10-16 17:25:48 +01:00
alan a6aff47117 Add a human decision stage that pauses a run for an operator's choice
A new registered stage type `human` (internal/stage/human.go) has no model,
agent, tools or configs: its required `prompt` block carries the operator
instructions and its non-error edges are the selectable options. It parses,
validates, renders, exports and imports like every other type (no parser
special-case, no config keys).

At runtime the runner parks the run instead of executing: the step and the run
persist `waiting` with self-contained {prompt, options} evidence, and the run
returns without starting later stages, capturing file diffs, scanning artifacts,
holding a goroutine/timer or applying a stage timeout. The wait is durable: a
restart leaves the waiting rows untouched (RecoverRuns excludes them) and a
rebuilt runtime over the same database still accepts the decision.

`pipelines decide <run-id> [stage] --option KEY [--feedback TEXT] [--json]` and
the TUI `c` picker resolve the decision from the pinned graph in one store
transaction, record the choice and feedback as the step's evidence and resume
along edges[KEY]. An unknown option is refused with the valid list, a stage that
is not waiting is refused, and a repeated decision for an already-decided visit
does not double-apply. Cancel and retry keep working while waiting and after a
decision; a human stage is never killed by a stage timeout or max_visits, and a
`notify` policy can fire an `on=waiting` event.

Docs: the authoring skill references (format.md, operations.md), docs/cli.md and
README describe the stage, the command and the TUI picker. Tests cover stage
validation, the parsing round-trip, the store transitions, a websocket wait/decide
integration, cancel/retry, waiting notifications and a persistence-layer rebuild
(second Open + newRunner over one database, no process restart).
2026-10-16 16:47:28 +01:00
alan 9f88e4ff71 Recover malformed model-stage results with a bounded, work-preserving repair
A model stage whose final result was malformed failed the whole run even when
the work and evidence had survived, because the only recovery was an isolated
formatter call on a fixed 30-second deadline that could time out on its own
(run 55, ui_reviewer of pipeline 9 v6).

Add an ordered, deterministic local repair pass (internal/stage/result_repair.go)
that runs before any model call: (a) append missing closing delimiters via the
existing closeJSONContainers; (b) remove one unambiguous trailing comma before a
closing } or ]; (c) insert exactly the single comma/colon the JSON parser reported
at its byte offset. Every candidate must pass losslessSyntaxRepair(original,
candidate) and decodeModelResult before it is accepted, so no field value is
invented, removed, reordered or rewritten. Ambiguous payloads (an unescaped quote
or colon inside a string value, or a stray delimiter with no single completion)
return not-ok and fall through to the bounded model re-emit rather than guessing.
stageResultText still strips surrounding prose and a single code fence first;
model_prompt.go now also strips prose around a single balanced-but-malformed
object span so the deterministic pass sees just the object.

Replace the fixed 30-second formatter deadline with repairDeadline(payloadBytes,
remaining), which grows monotonically with payload size, has a floor, and is
clamped to the attempt's remaining budget minus a safety margin, so the stage
context remains the outer bound and a large result is not guaranteed to time out.
The one-request-per-attempt, 32 KiB bound and the deny-all, retained, new-session
property of RepairFormat are unchanged for OpenCodeClient and PiClient.

Record an explicit recovery status on every terminal path: repaired, partial or
unrecoverable, plus a byte offset. A candidate that is valid JSON but still fails
envelope validation is marked partial and never returned as a completed result;
the unrecoverable path retains the bounded original payload, the precise parse
error (including its byte offset) and surfaces the status in the FINAL RESULT
VALIDATION diagnostic.

safeToReplay is intentionally unchanged. The deterministic local repair and the
fresh deny-all, no-tools, retained formatter session are independent of the
stage's tool set and never re-prompt or replay the admitted agent session, so a
shell-enabled review stage gains malformed-result recovery without any replay of
admitted work. Risk: no change to mutation safety; the only added cost is one
bounded formatter call, already budgeted. Replayability is not extended for shell
stages.

Docs and packaged skill references (docs/model-results.md,
internal/author/skill/references/{format,debugging,verification}.md) describe the
three-tier recovery, the status words and the derived deadline; the safeToReplay
decision and its risk are recorded there alongside the commit.

Tests add mocked, offline coverage for the deterministic and partial paths, a
repairDeadline monotonicity/floor/clamp table, and a shell-stage regression
proving a recoverable malformed result does not fail the run or replay tool work.
2026-10-16 13:02:53 +01:00
alan 5157b3a716 Add bounded one-line summariser using the configured default harness
internal/summarise performs a single tool-free generation through the
configured default harness (its interactive model), reusing the exact
stage.ModelGenerator/OpenCodeClient/PiClient construction provider-check
uses. It bounds input (InputCap), output (one line, OutputCap runes) and
time (DefaultTimeout), returns the NoSummary sentinel on any error/timeout/
unusable reply, never runs tools or writes files, and records the harness,
model and failed flag in one sanitized log line plus at most one
OperationEvidence.

Reuse: stage.TruncateRunes and stage.OperationLog.Record are the exported
forms of the existing rune-safe truncation and bounded evidence recording;
protocol.NormalizeText trims replies to one line. No new dependencies.

Not wired into titles/verdicts yet: protocol.OutputPreview and the
internal/server/notify.go notification summary are the obvious future call
sites.
2026-10-16 10:55:43 +01:00
alan f57457aec9 Make agent-stage retries safe and retain timeout failure evidence
Fix four stage failure-handling and observability defects (A2, A3, A6, A9).

- A2: add safeToReplay(def) as the single definition of retryable post-admission
  work - only an explicit tools block that selects neither edit nor shell. The
  agent/pi WorkStarted guards now break only when the stage is not safe to
  replay, so read-only stages genuinely retry a post-admission timeout while
  mutating and legacy-bundle stages still never replay admitted work.
- A6: re-emit a malformed final result on an explicit read-only stage up to the
  retry budget, preserving format_repairs evidence; mutating stages keep the
  immediate return and their session.
- A3: timed-out stages retain usable evidence. waitForSessionIdle records one
  bounded sanitized OperationEvidence on deadline; the agent deferred cleanup
  does a bounded best-effort latest-assistant readback and settles knowable V2
  usage; RetainSession adds a retained_session pointer to failed step
  transcripts so the session is visible beneath the BoundTranscript threshold.
- A9: a stage outcome routed to #failure now yields a non-empty run diagnostic
  ("stage <name> returned outcome <outcome>") while preferring an existing step
  diagnostic.

Adds focused stage and server tests for retry safety, malformed-result
re-emission, timeout evidence retention and run-level diagnostics; updates the
packaged skill references and docs/cli.md, docs/model-results.md.
2026-10-15 18:27:22 +01:00
alan 0f5a188c6a Record and serve per-stage artifacts
Every agent stage now writes into a per-run/step artifacts directory under
the data dir (<data>/artifacts/<run>/<step>), passed to Pi as
PIPELINES_ARTIFACTS_DIR, exposed on the OpenCode client env seam, and stated
in the agent prompt boilerplate so agents save images, screenshots, reports
and logs there.

After each step the server scans that directory with a bounded, symlink- and
traversal-safe inventory (os.OpenRoot + Lstat + O_NOFOLLOW) recording name,
size_bytes, content type (extension then 512-byte sniff fallback) and URL,
enforcing max files, per-file bytes and total bytes while counting skipped
and truncated entries. A missing, unreadable or oversized directory yields
only a best-effort diagnostic and never changes the step outcome.

The list is carried on protocol.RunStep as Artifacts []StageArtifact plus
skipped/truncated counters (omitempty, backwards compatible), persisted in a
new step_artifacts table keyed (run_id, sequence) alongside the
notifications/file-changes tables and loaded by GetRun.

GET /artifacts/{run}/{step}/{name} on the existing handler serves the bytes
with http.ServeContent, so Content-Type, Content-Length, HEAD and Range
(206/416) come from the stdlib; unknown runs/steps, absolute paths,
traversal, symlink escapes and non-regular files are refused.

The TUI lists each selected step's artifacts (name + human size) in the
retained-evidence section and adds an artifacts summary in the style of the
file-changes summary. Adds docs/stage-artifacts.md linked from README and an
artifacts subsection to the packaged operations skill reference.

Tests cover the scan records and caps, missing/oversized directories,
HTTP HEAD/Range/traversal/symlink/unknown refusals and protocol round-trips.
2026-10-15 17:51:18 +01:00
alan e6d00d4ee5 Scope agent session bookkeeping to the run for concurrent runs
The per-workspace concurrency added in 2618f0d exposed three places that assumed a
single run, and the second concurrent run failed with 'agent quiescence not
confirmed' because of them.

- ActiveAgentSessionsForRun(runID) scopes the end-of-step quiescence check to the
  run's own sessions, so another run's legitimately active agent no longer fails
  this one. A run still fails when its own session cannot be confirmed idle.
- The startup guard now uses ActiveSessionOwners (which carries the owning run id)
  and refuses only an ORPHANED session - one whose run is not active now - which is
  what restart recovery is actually about. A session owned by a currently active
  run no longer blocks new work.
- sessionActive examines only the target session: foreign entries in the
  /api/session/active map are ignored, the target's absence is inactive, and the
  target present with an unsupported state still fails closed.

Verified: go build, go vet and go test ./... pass, including ten concurrency tests
(two workspaces run concurrently, same-workspace refusal, symlink and default-cwd
equivalence, idempotent repeats, restart recovery, retry scoping, overlapping runs
not failing quiescence, and a run's own active session still failing it).

Operator verification, which a stage cannot perform because restarting the server
would abort the run doing it: the service was rebuilt and restarted on this
commit, then two runs in separate workspaces (/tmp/ws-c and /tmp/ws-d) executed
concurrently - both reported executing at the same time, a third run in ws-c was
refused naming run 46, and both finished succeeded with no diagnostic.
2026-10-15 15:38:50 +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 c42a19f7d3 Improve workflow UI, retain stage diffs, and add portable pipeline transfers
Make OpenCode authoring responsive and expand the managed skill references. Add conflict-aware import/export, real-provider reference workflows, and tracked V2 generation for reliable budget accounting.
2026-10-10 20:55:42 +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
alan 08b8647d5b Validate providers and retain complete run debugging context 2026-10-09 23:21:01 +01:00
alan f60599230c Retain OpenCode sessions and verify fresh retry isolation 2026-10-09 21:16:28 +01:00
alan a50e8648f6 Add service status and usage dashboard, refresh externally published edits 2026-10-09 20:20:44 +01:00
alan 67ac79765f Harden model results with lossless isolated repair and scoped permissions 2026-10-09 20:02:41 +01:00
alan b2dce357ca Accept a single model result wrapped in prose or Markdown 2026-10-09 14:59:52 +01:00
alan ed93d055bf Run tasks directly with language-independent project tools 2026-10-09 01:48:46 +01:00