Merge branch 'main' into chat-cross-client-echo-order
This commit is contained in:
+73
-2
@@ -49,7 +49,7 @@ type options struct {
|
||||
json, source, noOpen, yes, allow, createOnly, force, wait bool
|
||||
version, expected, limit, recoverySequence, retryVisit int
|
||||
recoveryRun int64
|
||||
recoveryStage, resource string
|
||||
recoveryStage, resource, poolFile string
|
||||
timeout, waitTimeout time.Duration
|
||||
stageModels stageModelFlags
|
||||
}
|
||||
@@ -193,6 +193,11 @@ func (a App) flags(command string) (*flag.FlagSet, *options) {
|
||||
f.StringVar(&o.actor, "actor", "operator", "Bounded operator identity")
|
||||
f.BoolVar(&o.allow, "no-mutating-action", false, "Evidence explicitly records that no mutating action occurred")
|
||||
f.BoolVar(&o.yes, "yes", false, "Confirm reconciliation without prompting")
|
||||
case "resource-pool-inspect":
|
||||
f.StringVar(&o.resource, "pool", "", "Resource pool name")
|
||||
case "resource-pool-configure":
|
||||
f.StringVar(&o.poolFile, "file", "", "JSON pool declaration, or - for stdin")
|
||||
f.BoolVar(&o.yes, "yes", false, "Confirm this mutation without prompting")
|
||||
case "debug":
|
||||
f.StringVar(&o.harness, "harness", "", "Debugging harness: configured opencode/pi, or nvim")
|
||||
f.BoolVar(&o.yes, "yes", false, "Approve opening a debugging session without prompting")
|
||||
@@ -479,7 +484,7 @@ func (a App) Run(ctx context.Context, args []string) error {
|
||||
requestTimeout = 30 * time.Second
|
||||
}
|
||||
connectURL := o.url
|
||||
if command == "resource-inspect" || command == "resource-reconcile" {
|
||||
if command == "resource-inspect" || command == "resource-reconcile" || command == "resource-pool-inspect" || command == "resource-pool-configure" {
|
||||
var transportErr error
|
||||
connectURL, transportErr = operatorTransportURL(o.url)
|
||||
if transportErr != nil {
|
||||
@@ -966,6 +971,72 @@ func (a App) Run(ctx context.Context, args []string) error {
|
||||
}
|
||||
_, err = fmt.Fprintf(a.Out, "Reconciled resource %s for run #%d\n", pos[0], runID)
|
||||
return err
|
||||
case "resource-pool-inspect":
|
||||
if len(pos) > 1 {
|
||||
return fmt.Errorf("resource-pool-inspect takes one pool name")
|
||||
}
|
||||
if o.resource == "" && len(pos) == 1 {
|
||||
o.resource = pos[0]
|
||||
}
|
||||
if strings.TrimSpace(o.resource) == "" {
|
||||
return fmt.Errorf("resource-pool-inspect requires a pool name")
|
||||
}
|
||||
r, err := call(protocol.Message{Type: protocol.InspectResourcePool, Resource: o.resource})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r.ResourcePool == nil {
|
||||
return fmt.Errorf("server did not return resource pool")
|
||||
}
|
||||
return a.output(r.ResourcePool)
|
||||
case "resource-pool-configure":
|
||||
if len(pos) > 1 {
|
||||
return fmt.Errorf("resource-pool-configure takes one JSON file")
|
||||
}
|
||||
file := o.poolFile
|
||||
if file == "" && len(pos) == 1 {
|
||||
file = pos[0]
|
||||
}
|
||||
if file == "" {
|
||||
return fmt.Errorf("resource-pool-configure requires a JSON file")
|
||||
}
|
||||
var data []byte
|
||||
if file == "-" {
|
||||
input := a.In
|
||||
if input == nil {
|
||||
input = os.Stdin
|
||||
}
|
||||
data, err = io.ReadAll(io.LimitReader(input, 256*1024+1))
|
||||
} else {
|
||||
var input *os.File
|
||||
input, err = os.Open(file)
|
||||
if err == nil {
|
||||
data, err = io.ReadAll(io.LimitReader(input, 256*1024+1))
|
||||
_ = input.Close()
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) > 256*1024 {
|
||||
return fmt.Errorf("resource pool input exceeds 262144 bytes")
|
||||
}
|
||||
var pool protocol.ResourcePool
|
||||
if err := json.Unmarshal(data, &pool); err != nil {
|
||||
return fmt.Errorf("invalid resource pool JSON: %w", err)
|
||||
}
|
||||
if err := a.confirmAction(fmt.Sprintf("Configure resource pool %s?", pool.Name), o.yes); err != nil {
|
||||
return err
|
||||
}
|
||||
r, err := call(protocol.Message{Type: protocol.ConfigureResourcePool, ResourcePool: &pool})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if o.json {
|
||||
return a.output(r)
|
||||
}
|
||||
_, err = fmt.Fprintf(a.Out, "Configured resource pool %s\n", pool.Name)
|
||||
return err
|
||||
case "inspect", "cancel", "retry":
|
||||
value, err := one()
|
||||
if err != nil {
|
||||
|
||||
+58
-55
@@ -2,64 +2,67 @@ package cli
|
||||
|
||||
// Help is also the public command inventory for agents and parity checks.
|
||||
var usage = map[string]string{
|
||||
"provider-check": "provider-check --model PROVIDER/MODEL [--yes] [--json]",
|
||||
"new": "new [name] [prompt] [--template KEY] [--no-open | --json]",
|
||||
"edit": "edit [name|id] [prompt] [--version N] [--no-open | --json]",
|
||||
"drafts": "drafts [--json]",
|
||||
"draft-delete": "draft-delete <draft.md> [--json]",
|
||||
"validate": "validate <draft.md> [--json]",
|
||||
"submit": "submit <draft.md> [--name NAME] [--create-only] [--yes] [--json]",
|
||||
"list": "list [--json]",
|
||||
"search": "search QUERY [--type KIND] [--limit N] [--json]",
|
||||
"show": "show <name|id> [--version N] [--json]",
|
||||
"versions": "versions <name|id> [--json]",
|
||||
"export": "export [name|id ...] [--output FILE.zip] [--all] [--version N]",
|
||||
"import": "import [FILE.zip] [--all] [--on-conflict ask|keep|both|import] [--yes] [--json]",
|
||||
"templates": "templates [--json]",
|
||||
"template": "template <key> [--source | --json]",
|
||||
"run": "run [name|id] [prompt] [--title TITLE] [--model PROVIDER/MODEL] [--stage-model STAGE=PROVIDER/MODEL ...] [--json [--wait [--wait-timeout DURATION]]]",
|
||||
"runs": "runs [--pipeline NAME] [--json]",
|
||||
"inspect": "inspect <run-id> [--json]",
|
||||
"wait": "wait <run-id> [run-id ...] [--timeout DURATION] [--json]",
|
||||
"cancel": "cancel <run-id> [--json]",
|
||||
"decide": "decide <run-id> [stage] --option KEY [--feedback TEXT] [--json]",
|
||||
"retry": "retry <run-id> [--mode resume|restart] [--stage KEY [--visit N]] [--version N] [--input-file FILE|-] [--json [--wait [--wait-timeout DURATION]]]",
|
||||
"title": "title <run-id> \"<title>\" [--json]",
|
||||
"debug": "debug <run-id> [--json | --no-open]",
|
||||
"chat-adopt": "chat-adopt <session-id> [--json]",
|
||||
"connection": "connection [--json]",
|
||||
"ping": "ping [--json]",
|
||||
"version": "version [--json]",
|
||||
"status": "status [--json]",
|
||||
"stats": "stats [--json]",
|
||||
"resource-inspect": "resource-inspect <resource> [--json]",
|
||||
"resource-reconcile": "resource-reconcile <resource> <run-id> <stage> <sequence> --evidence TEXT [--no-mutating-action] [--yes] [--json]",
|
||||
"rpc": "rpc <request.json|->",
|
||||
"retention": "retention report|apply [--older-than DURATION] [--keep N] [--db FILE] [--artifacts DIR] [--json] [--yes]",
|
||||
"tui": "tui",
|
||||
"provider-check": "provider-check --model PROVIDER/MODEL [--yes] [--json]",
|
||||
"new": "new [name] [prompt] [--template KEY] [--no-open | --json]",
|
||||
"edit": "edit [name|id] [prompt] [--version N] [--no-open | --json]",
|
||||
"drafts": "drafts [--json]",
|
||||
"draft-delete": "draft-delete <draft.md> [--json]",
|
||||
"validate": "validate <draft.md> [--json]",
|
||||
"submit": "submit <draft.md> [--name NAME] [--create-only] [--yes] [--json]",
|
||||
"list": "list [--json]",
|
||||
"search": "search QUERY [--type KIND] [--limit N] [--json]",
|
||||
"show": "show <name|id> [--version N] [--json]",
|
||||
"versions": "versions <name|id> [--json]",
|
||||
"export": "export [name|id ...] [--output FILE.zip] [--all] [--version N]",
|
||||
"import": "import [FILE.zip] [--all] [--on-conflict ask|keep|both|import] [--yes] [--json]",
|
||||
"templates": "templates [--json]",
|
||||
"template": "template <key> [--source | --json]",
|
||||
"run": "run [name|id] [prompt] [--title TITLE] [--model PROVIDER/MODEL] [--stage-model STAGE=PROVIDER/MODEL ...] [--json [--wait [--wait-timeout DURATION]]]",
|
||||
"runs": "runs [--pipeline NAME] [--json]",
|
||||
"inspect": "inspect <run-id> [--json]",
|
||||
"wait": "wait <run-id> [run-id ...] [--timeout DURATION] [--json]",
|
||||
"cancel": "cancel <run-id> [--json]",
|
||||
"decide": "decide <run-id> [stage] --option KEY [--feedback TEXT] [--json]",
|
||||
"retry": "retry <run-id> [--mode resume|restart] [--stage KEY [--visit N]] [--version N] [--input-file FILE|-] [--json [--wait [--wait-timeout DURATION]]]",
|
||||
"title": "title <run-id> \"<title>\" [--json]",
|
||||
"debug": "debug <run-id> [--json | --no-open]",
|
||||
"chat-adopt": "chat-adopt <session-id> [--json]",
|
||||
"connection": "connection [--json]",
|
||||
"ping": "ping [--json]",
|
||||
"version": "version [--json]",
|
||||
"status": "status [--json]",
|
||||
"stats": "stats [--json]",
|
||||
"resource-inspect": "resource-inspect <resource> [--json]",
|
||||
"resource-reconcile": "resource-reconcile <resource> <run-id> <stage> <sequence> --evidence TEXT [--no-mutating-action] [--yes] [--json]",
|
||||
"resource-pool-inspect": "resource-pool-inspect <pool> [--json]",
|
||||
"resource-pool-configure": "resource-pool-configure <pool.json|-> --yes [--json]",
|
||||
"rpc": "rpc <request.json|->",
|
||||
"retention": "retention report|apply [--older-than DURATION] [--keep N] [--db FILE] [--artifacts DIR] [--json] [--yes]",
|
||||
"tui": "tui",
|
||||
}
|
||||
|
||||
var notes = map[string]string{
|
||||
"version": "Identify the local CLI binary without connecting to a server. --version is an alias. Use ping --json to identify the running server separately.",
|
||||
"ping": "Pong includes the running server's compiled build.version, build.commit and build.dirty (null when unknown). This identifies the server, not the client or runtime workspace. Older servers omit build. The client compares its own build/protocol against the server: a same-protocol build mismatch prints one warning to stderr, a server speaking a newer protocol fails the command, and a response carrying a field this client does not model prints a one-time unrecognized-field notice instead of dropping it silently.",
|
||||
"connection": "Prints the server endpoint and phone notification endpoints. Like ping, it reports the client/server build relationship and warns or fails rather than silently proceeding against a mismatched server.",
|
||||
"status": "Reports server, host and ntfy publishing health. The client compares its build/protocol against the server and warns once (or fails on a newer protocol) rather than proceeding silently.",
|
||||
"export": "Without a name, select pipelines with Space and save a ZIP in the current directory. --output writes a portable definition bundle; --all skips selection. One name without --output prints Markdown as before. No runs, credentials or old versions are exported.",
|
||||
"import": "Select definitions from a ZIP. Identical existing definitions are skipped. For differing names, choose keep existing, keep both under a new name, or use imported as a new version (history retained). --on-conflict supplies an explicit automation policy; --yes only approves final publication. Schedules may activate; no run history is imported.",
|
||||
"new": "Create an optional template copy or a one-stage starter. Opens the configured default harness; --harness opencode|pi|nvim overrides it. No submission is performed.",
|
||||
"edit": "Omit the name to open fuzzy selection. Original immutable source is copied to a private draft. The configured harness edits that draft, never the live definition.",
|
||||
"validate": "Uses the same server parser as submission. Does not persist or activate schedules. Structural validity does not prove runtime/tool availability.",
|
||||
"submit": "Confirm publication at the prompt, or use --yes for explicit automation; schedules activate on acceptance. Managed drafts provide the name and base-version guard. --force never bypasses validation.",
|
||||
"run": "Runs in your current directory after action confirmation (--yes skips it). Select a pipeline and compose a multiline task with Ctrl+S. Stage tools are enabled automatically; no file list or typed RUN confirmation. Cancellation does not undo edits. --title sets an explicit run title; without it the title is derived from the prompt. --model PROVIDER/MODEL overrides the model for every stage of that run; --stage-model STAGE=PROVIDER/MODEL overrides one stage and is repeatable, with a repeated key last-wins. Precedence is per-stage > whole-run > the model pinned in the pipeline version; overrides apply to that run only and never change the pinned definition. An unknown stage key or a malformed provider/model is refused before the run starts, naming the valid stage keys. In JSON mode --wait polls until terminal; --wait-timeout bounds only the client wait after admission and is independent of per-request --timeout. A reached wait limit leaves the run active: inspect read-only with `inspect <run-id> --json`, or reattach with --wait reusing the original --request-key (never an automatic replay or cancel).",
|
||||
"retry": "Resume a failed stage by default, restoring the completed prefix handoff; use --mode=restart to start at entry. --stage selects a recorded stage (use --visit for repeated stages). --input-file accepts a bounded JSON object, merged with replacement at the selected stage; '-' reads stdin. Original history and pinned identity are retained; --version selects an explicit published version of the same pipeline only. --wait-timeout leaves an active retry for later read-only inspection or reattachment with the original --request-key, rather than starting a duplicate retry.",
|
||||
"title": "Rename a run's operator-facing title after the fact without touching its input, steps or execution. The title is collapsed to a single bounded line and recorded as explicitly set. `pipelines runs` and `pipelines inspect` then show it.",
|
||||
"wait": "Block until each named run reaches a terminal status - succeeded, failed, canceled or interrupted, and also through a run waiting on a person - then print one line per run with its id, status and outcome, its stage and how long it took, and exit 0 even for a run that finished unsuccessfully. Several ids wait together in one command. The exit is non-zero only for a client-side failure: an unknown run id, a connection that could not be established, or --timeout expiring while a run is still active; a timeout says so plainly, never cancels, retries or otherwise touches a run, and is never reported as its outcome. Read-only: it needs no workspace, is not refused by the workspace guard and writes nothing. --json prints the final run envelope instead of the line (one envelope for one id, an array for several).",
|
||||
"decide": "Choose an option for a run waiting on a human stage. The run must be `waiting`; the option must be one of that stage's non-error edges. The stage is inferred from the run's current stage unless named. The choice and optional --feedback are recorded as the step's evidence (visible in inspect and the TUI) and the run resumes along the chosen edge. An unknown option is refused with the valid list; a repeated decision for an already-decided visit does not double-apply. Works across a server restart because the wait is persisted.",
|
||||
"debug": "Open a fresh configured harness conversation to investigate a run using inspect/show/runs CLI queries. --harness opencode|pi|nvim chooses another configured harness or read-only nvim packet. Does not resume implementation or retry. --json returns the prompt without launching anything.",
|
||||
"rpc": "Accepts a JSON protocol envelope; '-' reads stdin. Every TUI server operation is available here too. Mutating commands are not dry runs. The omni-search command is `search` (fields query, optional kind and limit) and answers with ranked `search_results`.",
|
||||
"chat-adopt": "Adopt a session that already exists on the configured OpenCode endpoint so it appears in chat_sessions and can be continued. The id must be one the endpoint reports; its directory and title are taken from the endpoint's own record (never guessed), and a missing id records nothing. Adopting is always explicit and does not change the server's endpoint choice.",
|
||||
"retention": "Local, explicit run-history retention; never automatic and never a side effect of another command. `report` is strictly read-only and prints what a policy would remove; `apply` removes it after approval (--yes for scripted use). Policy: --older-than DURATION selects runs created before now minus that rolling UTC duration (Go durations plus d/w; not a calendar boundary), --keep N keeps the newest N runs by run id and selects older ranks (--keep 0 keeps none). Both together are the conservative intersection; at least one is required. Protected and never removed: queued/running runs, runs waiting on a person (waiting run or step), runs with an active cleanup agent, and any run referenced by a retained run's retry provenance (transitively). A run that becomes protected before deletion aborts the whole apply. Artifacts at <root>/<run> are removed with their run and kept with protected/retained runs; the database is VACUUMed and its WAL checkpointed, with measured reclaimed bytes. Definitions and versions are immutable and never touched. --db must name an existing database (default: the standard data directory); --artifacts defaults to artifacts/ beside --db. Works without a running server.",
|
||||
"search": "One read-only query over pipelines, versions, runs, steps, field text and artifacts. QUERY is free text, a bare status word (queued, running, succeeded, failed, canceled, interrupted) selecting those runs, or a lone date expression (today, yesterday, this week [Monday 00:00 local], or YYYY-MM-DD) selecting the runs created in that window. --type is the only narrowing mechanism and takes one kind: pipeline, version, run, step, field or artifact; an unknown kind is an error. Ranking: an exact name match (3) beats a name substring (2) beats a body-text match (1); equal tiers break by recency, then a stable kind/target tie-break, and every hit reports score, matched_field and recency so a client can re-rank. Bounds: the result cap defaults to 50 and clamps to 200 (0 = default); every kind scans at most 2000 rows and field-text scanning is additionally capped at 2000 steps / 1 MiB; Truncated plus scanned_steps, scanned_bytes and scan_bound_bytes report when a bound applied. Targets are stable: pipeline:<id>, pipeline:<id>:v<version>, run:<id>, run:<id>:<sequence>, run:<id>:<sequence>:<field>, or an artifact URL.",
|
||||
"version": "Identify the local CLI binary without connecting to a server. --version is an alias. Use ping --json to identify the running server separately.",
|
||||
"ping": "Pong includes the running server's compiled build.version, build.commit and build.dirty (null when unknown). This identifies the server, not the client or runtime workspace. Older servers omit build. The client compares its own build/protocol against the server: a same-protocol build mismatch prints one warning to stderr, a server speaking a newer protocol fails the command, and a response carrying a field this client does not model prints a one-time unrecognized-field notice instead of dropping it silently.",
|
||||
"connection": "Prints the server endpoint and phone notification endpoints. Like ping, it reports the client/server build relationship and warns or fails rather than silently proceeding against a mismatched server.",
|
||||
"status": "Reports server, host and ntfy publishing health. The client compares its build/protocol against the server and warns once (or fails on a newer protocol) rather than proceeding silently.",
|
||||
"export": "Without a name, select pipelines with Space and save a ZIP in the current directory. --output writes a portable definition bundle; --all skips selection. One name without --output prints Markdown as before. No runs, credentials or old versions are exported.",
|
||||
"import": "Select definitions from a ZIP. Identical existing definitions are skipped. For differing names, choose keep existing, keep both under a new name, or use imported as a new version (history retained). --on-conflict supplies an explicit automation policy; --yes only approves final publication. Schedules may activate; no run history is imported.",
|
||||
"new": "Create an optional template copy or a one-stage starter. Opens the configured default harness; --harness opencode|pi|nvim overrides it. No submission is performed.",
|
||||
"edit": "Omit the name to open fuzzy selection. Original immutable source is copied to a private draft. The configured harness edits that draft, never the live definition.",
|
||||
"validate": "Uses the same server parser as submission. Does not persist or activate schedules. Structural validity does not prove runtime/tool availability.",
|
||||
"submit": "Confirm publication at the prompt, or use --yes for explicit automation; schedules activate on acceptance. Managed drafts provide the name and base-version guard. --force never bypasses validation.",
|
||||
"run": "Runs in your current directory after action confirmation (--yes skips it). Select a pipeline and compose a multiline task with Ctrl+S. Stage tools are enabled automatically; no file list or typed RUN confirmation. Cancellation does not undo edits. --title sets an explicit run title; without it the title is derived from the prompt. --model PROVIDER/MODEL overrides the model for every stage of that run; --stage-model STAGE=PROVIDER/MODEL overrides one stage and is repeatable, with a repeated key last-wins. Precedence is per-stage > whole-run > the model pinned in the pipeline version; overrides apply to that run only and never change the pinned definition. An unknown stage key or a malformed provider/model is refused before the run starts, naming the valid stage keys. In JSON mode --wait polls until terminal; --wait-timeout bounds only the client wait after admission and is independent of per-request --timeout. A reached wait limit leaves the run active: inspect read-only with `inspect <run-id> --json`, or reattach with --wait reusing the original --request-key (never an automatic replay or cancel).",
|
||||
"retry": "Resume a failed stage by default, restoring the completed prefix handoff; use --mode=restart to start at entry. --stage selects a recorded stage (use --visit for repeated stages). --input-file accepts a bounded JSON object, merged with replacement at the selected stage; '-' reads stdin. Original history and pinned identity are retained; --version selects an explicit published version of the same pipeline only. --wait-timeout leaves an active retry for later read-only inspection or reattachment with the original --request-key, rather than starting a duplicate retry.",
|
||||
"title": "Rename a run's operator-facing title after the fact without touching its input, steps or execution. The title is collapsed to a single bounded line and recorded as explicitly set. `pipelines runs` and `pipelines inspect` then show it.",
|
||||
"wait": "Block until each named run reaches a terminal status - succeeded, failed, canceled or interrupted, and also through a run waiting on a person - then print one line per run with its id, status and outcome, its stage and how long it took, and exit 0 even for a run that finished unsuccessfully. Several ids wait together in one command. The exit is non-zero only for a client-side failure: an unknown run id, a connection that could not be established, or --timeout expiring while a run is still active; a timeout says so plainly, never cancels, retries or otherwise touches a run, and is never reported as its outcome. Read-only: it needs no workspace, is not refused by the workspace guard and writes nothing. --json prints the final run envelope instead of the line (one envelope for one id, an array for several).",
|
||||
"decide": "Choose an option for a run waiting on a human stage. The run must be `waiting`; the option must be one of that stage's non-error edges. The stage is inferred from the run's current stage unless named. The choice and optional --feedback are recorded as the step's evidence (visible in inspect and the TUI) and the run resumes along the chosen edge. An unknown option is refused with the valid list; a repeated decision for an already-decided visit does not double-apply. Works across a server restart because the wait is persisted.",
|
||||
"debug": "Open a fresh configured harness conversation to investigate a run using inspect/show/runs CLI queries. --harness opencode|pi|nvim chooses another configured harness or read-only nvim packet. Does not resume implementation or retry. --json returns the prompt without launching anything.",
|
||||
"rpc": "Accepts a JSON protocol envelope; '-' reads stdin. Every TUI server operation is available here too. Mutating commands are not dry runs. The omni-search command is `search` (fields query, optional kind and limit) and answers with ranked `search_results`.",
|
||||
"chat-adopt": "Adopt a session that already exists on the configured OpenCode endpoint so it appears in chat_sessions and can be continued. The id must be one the endpoint reports; its directory and title are taken from the endpoint's own record (never guessed), and a missing id records nothing. Adopting is always explicit and does not change the server's endpoint choice.",
|
||||
"retention": "Local, explicit run-history retention; never automatic and never a side effect of another command. `report` is strictly read-only and prints what a policy would remove; `apply` removes it after approval (--yes for scripted use). Policy: --older-than DURATION selects runs created before now minus that rolling UTC duration (Go durations plus d/w; not a calendar boundary), --keep N keeps the newest N runs by run id and selects older ranks (--keep 0 keeps none). Both together are the conservative intersection; at least one is required. Protected and never removed: queued/running runs, runs waiting on a person (waiting run or step), runs with an active cleanup agent, and any run referenced by a retained run's retry provenance (transitively). A run that becomes protected before deletion aborts the whole apply. Artifacts at <root>/<run> are removed with their run and kept with protected/retained runs; the database is VACUUMed and its WAL checkpointed, with measured reclaimed bytes. Definitions and versions are immutable and never touched. --db must name an existing database (default: the standard data directory); --artifacts defaults to artifacts/ beside --db. Works without a running server.",
|
||||
"search": "One read-only query over pipelines, versions, runs, steps, field text and artifacts. QUERY is free text, a bare status word (queued, running, succeeded, failed, canceled, interrupted) selecting those runs, or a lone date expression (today, yesterday, this week [Monday 00:00 local], or YYYY-MM-DD) selecting the runs created in that window. --type is the only narrowing mechanism and takes one kind: pipeline, version, run, step, field or artifact; an unknown kind is an error. Ranking: an exact name match (3) beats a name substring (2) beats a body-text match (1); equal tiers break by recency, then a stable kind/target tie-break, and every hit reports score, matched_field and recency so a client can re-rank. Bounds: the result cap defaults to 50 and clamps to 200 (0 = default); every kind scans at most 2000 rows and field-text scanning is additionally capped at 2000 steps / 1 MiB; Truncated plus scanned_steps, scanned_bytes and scan_bound_bytes report when a bound applied. Targets are stable: pipeline:<id>, pipeline:<id>:v<version>, run:<id>, run:<id>:<sequence>, run:<id>:<sequence>:<field>, or an artifact URL.",
|
||||
"resource-pool-configure": "Read a bounded full pool declaration from JSON and replace the declaration only after explicit --yes consent. Use '-' for stdin. This is local operator transport only; it never accepts or returns capabilities or credentials. resource-pool-inspect reads the declared members and status.",
|
||||
}
|
||||
|
||||
var serviceHelp = map[string]string{
|
||||
|
||||
@@ -250,6 +250,21 @@ func (s *Store) ConfigureResourcePool(ctx context.Context, pool protocol.Resourc
|
||||
return err
|
||||
}
|
||||
|
||||
// InspectResourcePool returns the declared pool, including only bounded,
|
||||
// non-secret member metadata and status.
|
||||
func (s *Store) InspectResourcePool(ctx context.Context, name string) (protocol.ResourcePool, error) {
|
||||
if !ValidResourceKey(name) {
|
||||
return protocol.ResourcePool{}, fmt.Errorf("invalid resource pool")
|
||||
}
|
||||
s.resourceMu.Lock()
|
||||
defer s.resourceMu.Unlock()
|
||||
members, err := s.resourcePool(ctx, s.db, name)
|
||||
if err != nil {
|
||||
return protocol.ResourcePool{}, err
|
||||
}
|
||||
return protocol.ResourcePool{Name: name, Members: members}, nil
|
||||
}
|
||||
|
||||
func (s *Store) resourcePool(ctx context.Context, tx interface {
|
||||
QueryRowContext(context.Context, string, ...any) *sql.Row
|
||||
}, name string) ([]protocol.ResourcePoolMember, error) {
|
||||
|
||||
@@ -20,6 +20,10 @@ const (
|
||||
ResourceInspectionResult = "resource_inspection"
|
||||
ReconcileResource = "reconcile_resource"
|
||||
ResourceReconciled = "resource_reconciled"
|
||||
InspectResourcePool = "inspect_resource_pool"
|
||||
ResourcePoolInspection = "resource_pool_inspection"
|
||||
ConfigureResourcePool = "configure_resource_pool"
|
||||
ResourcePoolConfigured = "resource_pool_configured"
|
||||
)
|
||||
|
||||
type Stage struct {
|
||||
@@ -212,4 +216,5 @@ type Message struct {
|
||||
Resource string `json:"resource,omitempty"`
|
||||
ResourceInspection *ResourceInspection `json:"resource_inspection,omitempty"`
|
||||
ResourceRecovery *ResourceRecoveryRequest `json:"resource_recovery,omitempty"`
|
||||
ResourcePool *ResourcePool `json:"resource_pool,omitempty"`
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ type ResourceInspection struct {
|
||||
Owner *ResourceOwner `json:"owner,omitempty"`
|
||||
Waiters []ResourceWaiter `json:"waiters,omitempty"`
|
||||
Audits []ResourceRecoveryAudit `json:"audits,omitempty"`
|
||||
Pool *ResourcePool `json:"pool,omitempty"`
|
||||
}
|
||||
|
||||
// ResourceTarget is bounded, non-secret metadata for the concrete member that
|
||||
|
||||
@@ -370,6 +370,9 @@ func TestRetryConflictsOnlyWithSameWorkspaceActiveRun(t *testing.T) {
|
||||
t.Fatalf("retry did not conflict with same-workspace active run: %v", err)
|
||||
}
|
||||
close(releaseA)
|
||||
// Execution returning does not instantly remove the workspace reservation.
|
||||
// Finish A's cleanup before asserting that only the unrelated B is active.
|
||||
r.wg.Wait()
|
||||
// A different active workspace must not block the retry of the original.
|
||||
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "active-b", Workspace: b, Input: map[string]any{"prompt": "task"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -162,3 +163,154 @@ func TestRepeatedStageVisitsRetainIndependentDiffs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetainedStageDiffsSurviveCommittedMergeAndNoopVisit(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := filepath.Join(t.TempDir(), "committed-diffs.db")
|
||||
store, err := pipeline.Open(db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := pipeline.Template([]string{"commit", "merge", "noop"}, true)
|
||||
if _, err := store.Submit(ctx, "committed-diffs", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
workspace := t.TempDir()
|
||||
runGit(t, workspace, "init", "-q")
|
||||
runGit(t, workspace, "config", "user.email", "test@example.invalid")
|
||||
runGit(t, workspace, "config", "user.name", "test")
|
||||
path := filepath.Join(workspace, "source.txt")
|
||||
if err := os.WriteFile(path, []byte("base\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, workspace, "add", "source.txt")
|
||||
runGit(t, workspace, "commit", "-qm", "base")
|
||||
branch := runGitOutput(t, workspace, "branch", "--show-current")
|
||||
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
git := func(args ...string) error {
|
||||
cmd := exec.Command("git", append([]string{"-C", workspace}, args...)...)
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("git %v: %w: %s", args, err, output)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
gitOutput := func(args ...string) (string, error) {
|
||||
cmd := exec.Command("git", append([]string{"-C", workspace}, args...)...)
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("git %v: %w", args, err)
|
||||
}
|
||||
return strings.TrimSpace(string(output)), nil
|
||||
}
|
||||
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
switch def.Key {
|
||||
case "commit":
|
||||
if err := os.WriteFile(path, []byte("committed change\n"), 0600); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := git("add", "source.txt"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := git("commit", "-qm", "stage commit"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
case "merge":
|
||||
if err := git("checkout", "-qb", "conflict-side"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("side change\n"), 0600); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := git("add", "source.txt"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := git("commit", "-qm", "side"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := git("checkout", "-q", branch); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("main change\n"), 0600); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := git("add", "source.txt"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := git("commit", "-qm", "main"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := git("merge", "--no-ff", "conflict-side", "-m", "merge"); err == nil {
|
||||
return stage.Result{}, errors.New("expected merge conflict")
|
||||
}
|
||||
conflicted, err := gitOutput("diff", "--name-only", "--diff-filter=U")
|
||||
if err != nil || conflicted != "source.txt" {
|
||||
return stage.Result{}, fmt.Errorf("merge did not leave the expected conflict: %q, %v", conflicted, err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("resolved merge\n"), 0600); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := git("add", "source.txt"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := git("commit", "-qm", "resolve merge"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
case "noop":
|
||||
if err := git("commit", "--allow-empty", "-qm", "no content change"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
}
|
||||
return stage.Result{Outcome: "success"}, nil
|
||||
}
|
||||
|
||||
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "committed-diffs", Workspace: workspace, Input: map[string]any{"prompt": "task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = pipeline.Open(db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
detail, err := store.GetRun(ctx, run.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Status != "succeeded" || len(detail.Steps) != 3 {
|
||||
t.Fatal(detail)
|
||||
}
|
||||
for _, assertion := range []struct {
|
||||
step int
|
||||
old string
|
||||
new string
|
||||
}{
|
||||
{step: 0, old: "base", new: "committed change"},
|
||||
{step: 1, old: "committed change", new: "resolved merge"},
|
||||
} {
|
||||
changes := detail.Steps[assertion.step].FileChanges
|
||||
if changes == nil || len(changes.Files) != 1 || !strings.Contains(changes.Files[0].Patch, "-"+assertion.old) || !strings.Contains(changes.Files[0].Patch, "+"+assertion.new) {
|
||||
t.Fatalf("committed stage patch was not retained after reopen: %+v", changes)
|
||||
}
|
||||
}
|
||||
if changes := detail.Steps[2].FileChanges; changes == nil || len(changes.Files) != 0 {
|
||||
t.Fatalf("commit-only stage changed source evidence: %+v", changes)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil || string(data) != "resolved merge\n" {
|
||||
t.Fatalf("merge resolution was not preserved: %q, %v", data, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Operator-invoked scratch fixture only. No devices or live databases are used.
|
||||
func TestExportReadyAttentionReviewFixture(t *testing.T) {
|
||||
dir := os.Getenv("PIPELINES_ATTENTION_REVIEW_DIR")
|
||||
if dir == "" {
|
||||
t.Skip("explicit export directory required")
|
||||
}
|
||||
if err := os.Mkdir(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
workspace := filepath.Join(dir, "workspace")
|
||||
if err := os.Mkdir(workspace, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
db := filepath.Join(dir, "attention.db")
|
||||
store, err := pipeline.Open(db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "Attention fixture", humanPipelineSource); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil || len(items) != 1 {
|
||||
t.Fatal("missing fixture definition", err)
|
||||
}
|
||||
definition, err := store.Get(ctx, items[0].ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, status := range []string{"failed", "succeeded"} {
|
||||
id, _, err := store.CreateRun(ctx, definition, "fixture-"+status, workspace, false, nil, map[string]any{"prompt": "Controlled " + status + " attention entry"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outcome := "success"
|
||||
if status == "failed" {
|
||||
outcome = "error"
|
||||
}
|
||||
capture := &protocol.StageFileChanges{Status: "complete", Files: []protocol.FileChange{}}
|
||||
if status == "failed" {
|
||||
capture.Status, capture.Skipped, capture.Diagnostic = "partial", 2, "Controlled partial fixture: files skipped."
|
||||
}
|
||||
if err := store.BeginStep(ctx, id, 1, "gate", map[string]any{"prompt": "Controlled fixture step"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.FinishStep(ctx, id, protocol.RunStep{Sequence: 1, Stage: "gate", Status: "completed", Outcome: outcome, FileChanges: capture}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.FinishRun(ctx, id, status, outcome, "Controlled fixture", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.execute = successExecute
|
||||
waiting, err := r.start(protocol.Message{PipelineID: definition.ID, Version: 1, RequestKey: "fixture-waiting", Workspace: workspace, Input: map[string]any{"prompt": "Controlled waiting attention entry"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
readback, err := store.GetRun(ctx, waiting.ID)
|
||||
if err != nil || readback.Status != protocol.RunStatusWaiting || len(readback.Steps) != 1 {
|
||||
t.Fatalf("waiting fixture invalid: %+v %v", readback, err)
|
||||
}
|
||||
data, err := json.MarshalIndent(map[string]any{"database": db, "workspace": workspace, "waiting_run": waiting.ID, "failed_run": 1, "finished_run": 2}, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "fixture.json"), data, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -365,6 +365,108 @@ func TestResourceOperatorTransportRejectsForgedForwardedPeer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourcePoolOperatorCLIConfigureReadbackAndPreserveLease(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
dbPath := filepath.Join(t.TempDir(), "pool-operator.db")
|
||||
store, err := pipeline.Open(dbPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if err := store.ConfigureResourcePool(ctx, protocol.ResourcePool{Name: "targets", Members: []protocol.ResourcePoolMember{{Member: "phone", Enabled: true, Metadata: map[string]string{"serial": "old"}}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Submit(ctx, "pool-owner", pipeline.Template([]string{"work"}, true)+"```resources\n{\"pool\":\"targets\"}\n```\n"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil || len(items) != 1 {
|
||||
t.Fatal("pool pipeline missing", err)
|
||||
}
|
||||
detail, err := store.Get(ctx, items[0].ID, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runID, _, err := store.CreateRun(ctx, detail, "pool-owner", t.TempDir(), false, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lease, ready, _, err := store.RequestResourcePool(ctx, "targets", pipeline.ResourceVisit{Resource: "targets", RunID: runID, Stage: "work", Sequence: 1})
|
||||
if err != nil || ready != nil {
|
||||
t.Fatalf("pool lease: ready=%v err=%v", ready, err)
|
||||
}
|
||||
|
||||
handler := Handler(ctx, store)
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
endpoint := "ws" + strings.TrimPrefix(srv.URL, "http") + "/connect"
|
||||
normal, err := client.Open(ctx, endpoint)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := normal.Call(ctx, protocol.Message{Type: protocol.ConfigureResourcePool, ResourcePool: &protocol.ResourcePool{Name: "targets", Members: []protocol.ResourcePoolMember{{Member: "phone", Enabled: true}}}}); err == nil || !strings.Contains(err.Error(), "operator transport") {
|
||||
t.Fatalf("remote configuration was accepted: %v", err)
|
||||
}
|
||||
normal.Close()
|
||||
|
||||
declaration := filepath.Join(t.TempDir(), "pool.json")
|
||||
if err := os.WriteFile(declaration, []byte(`{"name":"targets","members":[{"member":"phone","enabled":true,"metadata":{"serial":"new"}},{"member":"emulator","enabled":false}]}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
for _, fromStdin := range []bool{false, true} {
|
||||
oversized := strings.Repeat(" ", 256*1024+1)
|
||||
path := filepath.Join(t.TempDir(), "oversized.json")
|
||||
if err := os.WriteFile(path, []byte(oversized), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fromStdin {
|
||||
path = "-"
|
||||
}
|
||||
bounded := cli.App{Out: &out, Err: &out, In: strings.NewReader(oversized)}
|
||||
err := bounded.Run(ctx, []string{"--url", endpoint, "resource-pool-configure", path, "--yes", "--json"})
|
||||
if err == nil || !strings.Contains(err.Error(), "exceeds 262144 bytes") {
|
||||
t.Fatalf("oversized pool input (stdin=%v): %v", fromStdin, err)
|
||||
}
|
||||
out.Reset()
|
||||
}
|
||||
app := cli.App{Out: &out, Err: &out, In: strings.NewReader("")}
|
||||
if err := app.Run(ctx, []string{"--url", "ws" + strings.TrimPrefix(srv.URL, "http"), "resource-pool-configure", declaration, "--yes", "--json"}); err != nil {
|
||||
t.Fatalf("configure CLI: %v\n%s", err, out.String())
|
||||
}
|
||||
out.Reset()
|
||||
app = cli.App{Out: &out, Err: &out, In: strings.NewReader("")}
|
||||
if err := app.Run(ctx, []string{"--url", "ws" + strings.TrimPrefix(srv.URL, "http"), "resource-pool-inspect", "targets", "--json"}); err != nil {
|
||||
t.Fatalf("inspect CLI: %v\n%s", err, out.String())
|
||||
}
|
||||
var pool protocol.ResourcePool
|
||||
if err := json.Unmarshal(out.Bytes(), &pool); err != nil || len(pool.Members) != 2 || pool.Members[0].Metadata["serial"] != "new" {
|
||||
t.Fatalf("bad pool readback: %s (%v)", out.String(), err)
|
||||
}
|
||||
inspection, err := store.InspectResource(ctx, "phone")
|
||||
if err != nil || inspection.Owner == nil || inspection.Owner.RunID != runID {
|
||||
t.Fatalf("configuration released active lease: %#v (%v)", inspection, err)
|
||||
}
|
||||
if err := store.SetResourceCleanup(ctx, lease, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.ReleaseResource(ctx, lease); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.Close()
|
||||
store.Close()
|
||||
reopened, err := pipeline.Open(dbPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reopened.Close()
|
||||
persisted, err := reopened.InspectResourcePool(ctx, "targets")
|
||||
if err != nil || persisted.Members[0].Metadata["serial"] != "new" {
|
||||
t.Fatalf("pool did not survive reopen: %#v (%v)", persisted, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourceAndroidDraftPublishedV3Provenance(t *testing.T) {
|
||||
baseline, err := os.ReadFile("testdata/android-v3-published.md")
|
||||
if err != nil {
|
||||
|
||||
@@ -317,13 +317,19 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T
|
||||
if bCalls == 2 {
|
||||
wantTask = "corrected"
|
||||
}
|
||||
if bCalls == 3 {
|
||||
wantTask = "corrected-again"
|
||||
}
|
||||
if input["task"] != wantTask {
|
||||
t.Errorf("selected retry memory input = %#v, want task %q", input["task"], wantTask)
|
||||
}
|
||||
if bCalls == 2 && input["correction"] != "use-new-plan" {
|
||||
t.Errorf("selected retry lost input override: %#v", input)
|
||||
}
|
||||
if bCalls == 1 {
|
||||
if bCalls == 3 && input["correction"] != "use-new-plan-again" {
|
||||
t.Errorf("transitive selected retry lost input override: %#v", input)
|
||||
}
|
||||
if bCalls <= 2 {
|
||||
return stage.Result{}, fmt.Errorf("deliberate failure")
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"handoff": "from-b"}}, nil
|
||||
@@ -353,17 +359,29 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T
|
||||
}
|
||||
r.wg.Wait()
|
||||
retried, err = store.GetRun(ctx, retried.ID)
|
||||
if err != nil || retried.Status != "succeeded" || retried.RetryMode != "resume" || retried.RetrySource != original.ID {
|
||||
t.Fatalf("resume did not complete with provenance: %+v %v", retried, err)
|
||||
if err != nil || retried.Status != "failed" || retried.RetryMode != "resume" || retried.RetrySource != original.ID {
|
||||
t.Fatalf("first resume did not preserve failed provenance: %+v %v", retried, err)
|
||||
}
|
||||
if aCalls != 1 || bCalls != 2 || cCalls != 1 {
|
||||
transitive, err := r.retry(protocol.Message{RunID: retried.ID, RequestKey: "transitive-resume-key", RetryStage: "b", RetryInput: map[string]any{"task": "corrected-again", "correction": "use-new-plan-again"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
transitive, err = store.GetRun(ctx, transitive.ID)
|
||||
if err != nil || transitive.Status != "succeeded" || transitive.RetryMode != "resume" || transitive.RetrySource != retried.ID {
|
||||
t.Fatalf("transitive resume did not complete with provenance: %+v %v", transitive, err)
|
||||
}
|
||||
if aCalls != 1 || bCalls != 3 || cCalls != 1 {
|
||||
t.Fatalf("retry duplicated prefix or suffix: A=%d B=%d C=%d", aCalls, bCalls, cCalls)
|
||||
}
|
||||
if len(retried.Steps) != 2 || retried.Steps[0].Stage != "b" || retried.Steps[1].Stage != "c" {
|
||||
t.Fatalf("retry persisted the wrong steps: %+v", retried.Steps)
|
||||
if len(transitive.Steps) != 2 || transitive.Steps[0].Stage != "b" || transitive.Steps[1].Stage != "c" {
|
||||
t.Fatalf("retry persisted the wrong steps: %+v", transitive.Steps)
|
||||
}
|
||||
if retried.Steps[0].Input["task"] != "corrected" || retried.Steps[0].Input["correction"] != "use-new-plan" {
|
||||
t.Fatalf("retry persisted the wrong selected input: %#v", retried.Steps[0].Input)
|
||||
if transitive.Steps[0].Input["task"] != "corrected-again" || transitive.Steps[0].Input["correction"] != "use-new-plan-again" {
|
||||
t.Fatalf("retry persisted the wrong selected input: %#v", transitive.Steps[0].Input)
|
||||
}
|
||||
if transitive.Steps[0].Control == nil || transitive.Steps[0].Control.Memory["handoff"].Sequence != 1 {
|
||||
t.Fatalf("transitive retry lost prefix memory provenance: %#v", transitive.Steps[0].Control)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -377,8 +395,8 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replayed, err := r2.retry(protocol.Message{RunID: original.ID, RequestKey: "resume-key"})
|
||||
if err != nil || replayed.ID != retried.ID {
|
||||
replayed, err := r2.retry(protocol.Message{RunID: retried.ID, RequestKey: "transitive-resume-key"})
|
||||
if err != nil || replayed.ID != transitive.ID {
|
||||
t.Fatalf("persisted request-key replay lost its run: %+v %v", replayed, err)
|
||||
}
|
||||
}
|
||||
@@ -399,8 +417,9 @@ case "$3" in
|
||||
*/prompt) echo '{}' ;;
|
||||
*/wait) echo '{}' ;;
|
||||
*/message*)
|
||||
case "$3" in
|
||||
case "$3" in
|
||||
*/ses_native_2/*) echo '{"data":[{"finish":"stop","content":[{"type":"text","text":"{\\"outcome\\":\\"invalid\\",\\"output\\":{\\"wrong\\":\\"format\\"}}"}]}]}' ;;
|
||||
*/ses_native_3/*) echo '{}' ;;
|
||||
*/ses_native_3/*) echo '{"data":[{"finish":"stop","content":[{"type":"text","text":"{\\"outcome\\":\\"success\\",\\"output\\":{\\"handoff\\":\\"from-b\\"}}"}]}]}' ;;
|
||||
*) echo '{"data":[{"finish":"stop","content":[{"type":"text","text":"{\\"outcome\\":\\"success\\",\\"output\\":{\\"handoff\\":\\"from-a\\",\\"summary\\":\\"done\\"}}"}]}]}' ;;
|
||||
esac ;;
|
||||
@@ -417,6 +436,7 @@ esac
|
||||
}
|
||||
defer store.Close()
|
||||
source := "# stage a\n\n```output\n{ handoff, summary }\n```\n\n```prompt\nDo A.\n```\n\n```tools\nread\nglob\ngrep\nshell\n```\n\n```edges\nsuccess -> b\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage b\n\n```output\n{ handoff }\n```\n\n```prompt\nDo B.\n```\n\n```tools\nread\nglob\ngrep\nshell\n```\n\n```edges\nsuccess -> c\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage c\n\n```output\n{ handoff, summary }\n```\n\n```prompt\nDo C.\n```\n\n```tools\nread\nglob\ngrep\nshell\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n"
|
||||
source = strings.Replace(source, "# stage b\n\n```output", "# stage b\n\n```memory\n{\"task\":\"input.prompt\",\"handoff\":\"a.handoff\"}\n```\n\n```output", 1)
|
||||
if _, err := store.Submit(ctx, "native-resume", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -444,20 +464,48 @@ esac
|
||||
if err == nil || first.RunDetail == nil || first.RunDetail.Status != "failed" || len(first.RunDetail.Steps) != 2 {
|
||||
t.Fatalf("initial native run did not fail at B: %v %#v", err, first.RunDetail)
|
||||
}
|
||||
retried, err := runCLI("retry", fmt.Sprint(first.RunDetail.ID), "--yes", "--json", "--wait", "--timeout", "10s", "--request-key", "native-resume-key", "--mode", "resume")
|
||||
if err != nil || retried.RunDetail == nil || retried.RunDetail.Status != "succeeded" {
|
||||
t.Fatalf("native resume failed: %v %#v", err, retried.RunDetail)
|
||||
firstInput := filepath.Join(dir, "first-input.json")
|
||||
if err := os.WriteFile(firstInput, []byte(`{"task":"corrected-first","correction":"first"}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if retried.RunDetail.RetryOf != first.RunDetail.ID || len(retried.RunDetail.Steps) != 2 || retried.RunDetail.Steps[0].Stage != "b" || retried.RunDetail.Steps[1].Stage != "c" {
|
||||
retried, err := runCLI("retry", fmt.Sprint(first.RunDetail.ID), "--yes", "--json", "--wait", "--timeout", "10s", "--request-key", "native-resume-key", "--mode", "resume", "--stage", "b", "--input-file", firstInput)
|
||||
if err == nil || retried.RunDetail == nil || retried.RunDetail.Status != "failed" {
|
||||
t.Fatalf("first selected native resume did not fail at B: %v %#v", err, retried.RunDetail)
|
||||
}
|
||||
if retried.RunDetail.RetryOf != first.RunDetail.ID || len(retried.RunDetail.Steps) != 1 || retried.RunDetail.Steps[0].Stage != "b" {
|
||||
t.Fatalf("native resume lost provenance or replayed prefix: %#v", retried.RunDetail)
|
||||
}
|
||||
sessions, err := os.ReadFile(filepath.Join(dir, "sessions"))
|
||||
if err != nil || strings.TrimSpace(string(sessions)) != "4" {
|
||||
t.Fatalf("native stage execution count = %q, want 4 (A once, B twice, C once): %v", sessions, err)
|
||||
secondInput := filepath.Join(dir, "second-input.json")
|
||||
if err := os.WriteFile(secondInput, []byte(`{"task":"corrected-second","correction":"second"}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := runCLI("retry", fmt.Sprint(first.RunDetail.ID), "--yes", "--json", "--request-key", "native-resume-key")
|
||||
if err != nil || again.RunDetail == nil || again.RunDetail.ID != retried.RunDetail.ID {
|
||||
t.Fatalf("same-key replay was not idempotent: %v %#v", err, again.RunDetail)
|
||||
transitive, err := runCLI("retry", fmt.Sprint(retried.RunDetail.ID), "--yes", "--json", "--wait", "--timeout", "10s", "--request-key", "native-transitive-key", "--mode", "resume", "--stage", "b", "--input-file", secondInput)
|
||||
if err != nil || transitive.RunDetail == nil || transitive.RunDetail.Status != "succeeded" {
|
||||
t.Fatalf("transitive selected native resume failed: %v %#v", err, transitive.RunDetail)
|
||||
}
|
||||
if transitive.RunDetail.RetryOf != retried.RunDetail.ID || len(transitive.RunDetail.Steps) != 2 || transitive.RunDetail.Steps[0].Stage != "b" || transitive.RunDetail.Steps[1].Stage != "c" {
|
||||
t.Fatalf("transitive native resume lost provenance or replayed prefix: %#v", transitive.RunDetail)
|
||||
}
|
||||
if transitive.RunDetail.Steps[0].Input["task"] != "corrected-second" || transitive.RunDetail.Steps[0].Input["correction"] != "second" {
|
||||
t.Fatalf("transitive native resume persisted wrong selected input: %#v", transitive.RunDetail.Steps[0].Input)
|
||||
}
|
||||
if transitive.RunDetail.Steps[0].Control == nil || transitive.RunDetail.Steps[0].Control.Memory["handoff"].Sequence != 1 {
|
||||
t.Fatalf("transitive native resume lost prefix provenance: %#v", transitive.RunDetail.Steps[0].Control)
|
||||
}
|
||||
sessions, err := os.ReadFile(filepath.Join(dir, "sessions"))
|
||||
if err != nil || strings.TrimSpace(string(sessions)) != "5" {
|
||||
t.Fatalf("native stage execution count = %q, want 5 (A once, B three times, C once): %v", sessions, err)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = pipeline.Open(filepath.Join(dir, "runs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened, err := store.GetRun(ctx, transitive.RunDetail.ID)
|
||||
if err != nil || reopened.Status != "succeeded" || reopened.RetryOf != retried.RunDetail.ID {
|
||||
t.Fatalf("transitive retry did not survive database reopen: %#v %v", reopened, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+127
-26
@@ -420,6 +420,11 @@ type retryCheckpoint struct {
|
||||
handoff map[string]any
|
||||
}
|
||||
|
||||
type retryPrefixRecord struct {
|
||||
stage string
|
||||
sequence int
|
||||
}
|
||||
|
||||
const maxRetryInputBytes = 64 * 1024
|
||||
|
||||
func retryInputOverride(base map[string]any, override map[string]any) (map[string]any, error) {
|
||||
@@ -526,14 +531,16 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
|
||||
// stage's memory bindings must be resolved from the original prefix before
|
||||
// this override is applied at invocation time.
|
||||
handoff = map[string]any{"input": failed.Input, "override": override, "sequence": failed.Sequence, "stage": failed.Stage, "visit": failed.Sequence}
|
||||
prefix := map[string]any{}
|
||||
for _, step := range source.Steps {
|
||||
if step.Sequence >= failed.Sequence || step.Status != "completed" {
|
||||
continue
|
||||
}
|
||||
prefix[step.Stage] = step.Output
|
||||
prefix, prefixRecords, prefixErr := r.retryPrefix(sourceID, source, failed.Sequence)
|
||||
if prefixErr != nil {
|
||||
return retryCheckpoint{}, prefixErr
|
||||
}
|
||||
handoff["prefix"] = prefix
|
||||
serializedPrefix := make([]map[string]any, 0, len(prefixRecords))
|
||||
for _, record := range prefixRecords {
|
||||
serializedPrefix = append(serializedPrefix, map[string]any{"stage": record.stage, "sequence": record.sequence})
|
||||
}
|
||||
handoff["prefix_provenance"] = serializedPrefix
|
||||
// A newer explicitly selected version may continue only when every recorded
|
||||
// prefix stage still exists with the same kind. Its outputs are evidence from
|
||||
// the source attempt and cannot be safely handed to a changed stage contract.
|
||||
@@ -541,20 +548,21 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
|
||||
for _, declared := range source.Graph.Stages {
|
||||
sourceStages[declared.Key] = declared
|
||||
}
|
||||
for _, step := range source.Steps {
|
||||
if step.Sequence >= failed.Sequence {
|
||||
break
|
||||
for _, record := range prefixRecords {
|
||||
_, found := retryPrefixStep(source, record)
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
var pinnedStage *protocol.Stage
|
||||
for i := range pinned.Graph.Stages {
|
||||
if pinned.Graph.Stages[i].Key == step.Stage {
|
||||
if pinned.Graph.Stages[i].Key == record.stage {
|
||||
pinnedStage = &pinned.Graph.Stages[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
previous, ok := sourceStages[step.Stage]
|
||||
previous, ok := sourceStages[record.stage]
|
||||
if pinnedStage == nil || !ok || !retryStageContractEqual(previous, *pinnedStage) {
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d has incompatible changed prefix stage %q", sourceID, step.Stage)
|
||||
return retryCheckpoint{}, fmt.Errorf("retry source %d has incompatible changed prefix stage %q", sourceID, record.stage)
|
||||
}
|
||||
}
|
||||
var sourceSelected protocol.Stage
|
||||
@@ -775,7 +783,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
r.finishRunState(id, d.Name, workspace, "failed", "error", "retry checkpoint is missing handoff context", 0, 0, "", nil)
|
||||
return
|
||||
}
|
||||
state := rebuildRetryState(source, checkpoint.failed)
|
||||
state := rebuildRetryState(source, checkpoint.failed, storedHandoff)
|
||||
if override, ok := storedHandoff["override"].(map[string]any); ok {
|
||||
state.retryOverride = stage.Values(override)
|
||||
}
|
||||
@@ -897,31 +905,124 @@ func rebuildRunState(detail *protocol.RunDetail, decided protocol.RunStep) *runS
|
||||
// rebuildRetryState restores only the completed prefix. The failed visit is
|
||||
// deliberately not counted and its step/evidence is not copied into the new
|
||||
// attempt, so retries cannot duplicate execution or usage aggregates.
|
||||
func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep) *runState {
|
||||
func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep, handoff map[string]any) *runState {
|
||||
state := newRunState(failed.Stage, stage.Values(failed.Input))
|
||||
state.nextSequence = failed.Sequence
|
||||
if original, err := copyValues(stage.Values(detail.Input)); err == nil {
|
||||
state.memory["input"] = memoryValue{output: original}
|
||||
}
|
||||
for _, step := range detail.Steps {
|
||||
if step.Sequence >= failed.Sequence {
|
||||
break
|
||||
}
|
||||
state.visits[step.Stage]++
|
||||
if step.Status == "completed" {
|
||||
if values, err := copyValues(stage.Values(step.Output)); err == nil {
|
||||
state.memory[step.Stage] = memoryValue{output: values, sequence: step.Sequence}
|
||||
_, hasCheckpointPrefix := handoff["prefix"]
|
||||
if !hasCheckpointPrefix {
|
||||
for _, step := range detail.Steps {
|
||||
if step.Sequence >= failed.Sequence {
|
||||
break
|
||||
}
|
||||
state.visits[step.Stage]++
|
||||
if step.Status == "completed" {
|
||||
if values, err := copyValues(stage.Values(step.Output)); err == nil {
|
||||
state.memory[step.Stage] = memoryValue{output: values, sequence: step.Sequence}
|
||||
}
|
||||
state.completed++
|
||||
}
|
||||
state.recordChanges(step.FileChanges, step.Artifacts)
|
||||
if step.Status == "completed" {
|
||||
state.artifactDirs = append(state.artifactDirs, filepath.Join("", strconv.Itoa(step.Sequence)))
|
||||
}
|
||||
state.completed++
|
||||
}
|
||||
state.recordChanges(step.FileChanges, step.Artifacts)
|
||||
if step.Status == "completed" {
|
||||
state.artifactDirs = append(state.artifactDirs, filepath.Join("", strconv.Itoa(step.Sequence)))
|
||||
}
|
||||
// A selected-stage retry has no persisted rows for its inherited prefix.
|
||||
// Restore it from the immutable checkpoint instead of guessing from the
|
||||
// retry source's immediate steps (which is what made retry-of-retry fail
|
||||
// closed with "memory source ... has not completed").
|
||||
if prefix, ok := handoff["prefix"].(map[string]any); ok {
|
||||
for _, record := range retryPrefixRecords(handoff["prefix_provenance"]) {
|
||||
output, exists := prefix[record.stage].(map[string]any)
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
values, err := copyValues(stage.Values(output))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
state.memory[record.stage] = memoryValue{output: values, sequence: record.sequence}
|
||||
state.visits[record.stage]++
|
||||
state.completed++
|
||||
state.artifactDirs = append(state.artifactDirs, filepath.Join("", strconv.Itoa(record.sequence)))
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
// retryPrefix returns the completed prefix from the source attempt plus the
|
||||
// immutable prefix carried by that attempt's checkpoint. A retry attempt only
|
||||
// persists the selected stage onward, so immediate source steps are not a
|
||||
// complete representation of its memory.
|
||||
func (r *runner) retryPrefix(sourceID int64, source *protocol.RunDetail, failedSequence int) (map[string]any, []retryPrefixRecord, error) {
|
||||
prefix := map[string]any{}
|
||||
records := []retryPrefixRecord{}
|
||||
if source.RetryMode == "resume" && source.RetrySource > 0 {
|
||||
checkpointSource, mode, _, inherited, err := r.store.RetryCheckpoint(r.ctx, sourceID)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("retry source %d has no immutable prefix checkpoint: %w", sourceID, err)
|
||||
}
|
||||
if checkpointSource != source.RetrySource || mode != "resume" {
|
||||
return nil, nil, fmt.Errorf("retry source %d has an invalid prefix checkpoint", sourceID)
|
||||
}
|
||||
if values, ok := inherited["prefix"].(map[string]any); ok {
|
||||
for key, value := range values {
|
||||
prefix[key] = value
|
||||
}
|
||||
}
|
||||
for _, record := range retryPrefixRecords(inherited["prefix_provenance"]) {
|
||||
records = append(records, record)
|
||||
}
|
||||
}
|
||||
for _, step := range source.Steps {
|
||||
if step.Sequence >= failedSequence || step.Status != "completed" {
|
||||
continue
|
||||
}
|
||||
prefix[step.Stage] = step.Output
|
||||
records = append(records, retryPrefixRecord{stage: step.Stage, sequence: step.Sequence})
|
||||
}
|
||||
return prefix, records, nil
|
||||
}
|
||||
|
||||
func retryPrefixRecords(raw any) []retryPrefixRecord {
|
||||
items, ok := raw.([]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
result := make([]retryPrefixRecord, 0, len(items))
|
||||
for _, item := range items {
|
||||
entry, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
stageName, ok := entry["stage"].(string)
|
||||
if !ok || stageName == "" {
|
||||
continue
|
||||
}
|
||||
sequence, ok := entry["sequence"].(float64)
|
||||
if !ok || sequence < 1 {
|
||||
continue
|
||||
}
|
||||
result = append(result, retryPrefixRecord{stage: stageName, sequence: int(sequence)})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func retryPrefixStep(detail *protocol.RunDetail, record retryPrefixRecord) (protocol.RunStep, bool) {
|
||||
for _, step := range detail.Steps {
|
||||
if step.Stage == record.stage && step.Sequence == record.sequence {
|
||||
return step, true
|
||||
}
|
||||
}
|
||||
// Inherited rows intentionally are not present in a selected retry. The
|
||||
// contract check still uses the stage key; this marker keeps that check
|
||||
// independent from model-claimed output.
|
||||
return protocol.RunStep{Stage: record.stage, Sequence: record.sequence}, true
|
||||
}
|
||||
|
||||
// artifactAccess derives exact visit directories; it never consumes a path from
|
||||
// a definition or model result. An unreadable or symlinked root fails closed.
|
||||
func (r *runner) artifactAccess(runID int64, sequence int, prior []string, current string) stage.ArtifactAccess {
|
||||
|
||||
@@ -270,7 +270,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
response.Error = err.Error()
|
||||
}
|
||||
}
|
||||
} else if (request.Type == protocol.InspectResource || request.Type == protocol.ReconcileResource) && len(stores) > 0 {
|
||||
} else if (request.Type == protocol.InspectResource || request.Type == protocol.ReconcileResource || request.Type == protocol.InspectResourcePool || request.Type == protocol.ConfigureResourcePool) && len(stores) > 0 {
|
||||
var err error
|
||||
response.Type = protocol.ResourceInspectionResult
|
||||
// Recovery has a separate transport path. A stage/model client may
|
||||
@@ -280,6 +280,18 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
if r.URL.Path != "/operator-connect" || !isLoopbackPeer(r.RemoteAddr) {
|
||||
response.Type = protocol.Error
|
||||
response.Error = "resource recovery requires the local operator transport"
|
||||
} else if request.Type == protocol.InspectResourcePool {
|
||||
response.Type = protocol.ResourcePoolInspection
|
||||
var pool protocol.ResourcePool
|
||||
pool, err = stores[0].InspectResourcePool(ctx, request.Resource)
|
||||
response.ResourcePool = &pool
|
||||
} else if request.Type == protocol.ConfigureResourcePool {
|
||||
response.Type = protocol.ResourcePoolConfigured
|
||||
if request.ResourcePool == nil {
|
||||
err = fmt.Errorf("resource pool declaration is required")
|
||||
} else {
|
||||
err = stores[0].ConfigureResourcePool(ctx, *request.ResourcePool)
|
||||
}
|
||||
} else if request.Type == protocol.InspectResource {
|
||||
var inspection protocol.ResourceInspection
|
||||
inspection, err = stores[0].InspectResource(ctx, request.Resource)
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
var ErrInvalidModelResult = errors.New("invalid model stage result")
|
||||
@@ -36,6 +38,13 @@ func harnessUnreachable(err error) error {
|
||||
}
|
||||
|
||||
func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) {
|
||||
return modelPromptForTarget(def, spec, input, nil)
|
||||
}
|
||||
|
||||
// modelPromptForTarget carries a server-selected resource target separately from
|
||||
// task input. The target comes only from the runner context; task input remains
|
||||
// data and cannot select or replace it.
|
||||
func modelPromptForTarget(def Definition, spec ModelSpec, input Values, target *protocol.ResourceTarget) (string, error) {
|
||||
outcomes := make([]string, 0, len(def.Edges))
|
||||
for name := range def.Edges {
|
||||
outcomes = append(outcomes, name)
|
||||
@@ -59,15 +68,16 @@ func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) {
|
||||
toolsLine = "This call has these stage tools: " + strings.Join(tools, ", ") + "."
|
||||
}
|
||||
data, err := json.Marshal(struct {
|
||||
Key string `json:"stage"`
|
||||
Instructions string `json:"instructions"`
|
||||
OutputContract string `json:"output_contract"`
|
||||
Outcomes []string `json:"allowed_outcomes"`
|
||||
Input Values `json:"input"`
|
||||
ReportFileArtifacts bool `json:"report_file_artifacts"`
|
||||
ExecutionTime string `json:"execution_time"`
|
||||
Timezone string `json:"timezone"`
|
||||
}{def.Key, spec.Prompt, spec.Output, outcomes, input, def.ReportFileArtifacts, time.Now().Format(time.RFC3339), time.Local.String()})
|
||||
Key string `json:"stage"`
|
||||
Instructions string `json:"instructions"`
|
||||
OutputContract string `json:"output_contract"`
|
||||
Outcomes []string `json:"allowed_outcomes"`
|
||||
Input Values `json:"input"`
|
||||
ResourceTarget *protocol.ResourceTarget `json:"resource_target,omitempty"`
|
||||
ReportFileArtifacts bool `json:"report_file_artifacts"`
|
||||
ExecutionTime string `json:"execution_time"`
|
||||
Timezone string `json:"timezone"`
|
||||
}{def.Key, spec.Prompt, spec.Output, outcomes, input, target, def.ReportFileArtifacts, time.Now().Format(time.RFC3339), time.Local.String()})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("model stage input is not JSON-serializable: %w", err)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ func (m ModelStage) Run(ctx context.Context, def Definition, input Values) (Resu
|
||||
return Result{}, err
|
||||
}
|
||||
spec.Config.ResultSchema = resultSchema(def.Edges)
|
||||
prompt, err := modelPrompt(def, spec, input)
|
||||
target, _ := ResourceTarget(ctx)
|
||||
prompt, err := modelPromptForTarget(def, spec, input, target)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func modelDefinition() Definition {
|
||||
@@ -194,6 +196,107 @@ func TestModelRunUsesInstructionsAndStructuredOutput(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelRunForwardsOnlyServerGrantedResourceTarget(t *testing.T) {
|
||||
target := &protocol.ResourceTarget{Member: "emulator", Metadata: map[string]string{"serial": "emu-5554", "type": "emulator"}}
|
||||
budget := NewBudget(0, 0)
|
||||
input := Values{"resource_target": map[string]any{"member": "user-selected"}, "prompt": "task"}
|
||||
ctx := WithBudget(WithResourceTarget(context.Background(), target), budget)
|
||||
|
||||
var received ModelConfig
|
||||
client := generatorFunc(func(_ context.Context, config ModelConfig, prompt string) (string, error) {
|
||||
received = config
|
||||
assertPromptResourceTarget(t, prompt, target, input)
|
||||
return `{"outcome":"success","output":{}}`, nil
|
||||
})
|
||||
if _, err := (ModelStage{Client: client}).Run(ctx, modelDefinition(), input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if received.Budget != budget {
|
||||
t.Fatal("budget context was not preserved with resource target")
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelRunForwardsResourceTargetToNativeOpenCode(t *testing.T) {
|
||||
target := &protocol.ResourceTarget{Member: "phone", Metadata: map[string]string{"serial": "phone-serial"}}
|
||||
var prompt string
|
||||
client := &OpenCodeClient{Directory: "/work/repo", command: func(_ context.Context, _ string, args ...string) ([]byte, error) {
|
||||
switch args[2] {
|
||||
case "/api/session":
|
||||
return []byte(`{"data":{"id":"ses_target"}}`), nil
|
||||
case "/api/session/ses_target/generate":
|
||||
var body struct {
|
||||
Prompt string `json:"prompt"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(args[4]), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prompt = body.Prompt
|
||||
return []byte(`{"data":{"text":"{\"outcome\":\"success\",\"output\":{}}"}}`), nil
|
||||
default:
|
||||
t.Fatalf("unexpected fake OpenCode endpoint %q", args[2])
|
||||
return nil, nil
|
||||
}
|
||||
}}
|
||||
if _, err := (ModelStage{Client: client}).Run(WithResourceTarget(context.Background(), target), modelDefinition(), Values{"prompt": "task"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertPromptResourceTarget(t, prompt, target, Values{"prompt": "task"})
|
||||
}
|
||||
|
||||
func TestModelPromptWithoutResourceTargetPreservesLegacyInput(t *testing.T) {
|
||||
input := Values{"prompt": "task", "count": "1"}
|
||||
spec, err := (ModelStage{}).Spec(modelDefinition())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prompt, err := modelPrompt(modelDefinition(), spec, input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload struct {
|
||||
Input Values `json:"input"`
|
||||
ResourceTarget *protocol.ResourceTarget `json:"resource_target"`
|
||||
}
|
||||
if _, data, ok := strings.Cut(prompt, "Stage definition and runtime input:\n"); !ok || json.Unmarshal([]byte(data), &payload) != nil {
|
||||
t.Fatal("could not decode legacy runtime payload")
|
||||
}
|
||||
if payload.ResourceTarget != nil || !reflect.DeepEqual(payload.Input, input) {
|
||||
t.Fatalf("legacy runtime input changed: %#v", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func assertPromptResourceTarget(t *testing.T, prompt string, want *protocol.ResourceTarget, wantInput Values) {
|
||||
t.Helper()
|
||||
_, data, ok := strings.Cut(prompt, "Stage definition and runtime input:\n")
|
||||
if !ok {
|
||||
t.Fatal("missing runtime payload")
|
||||
}
|
||||
var payload struct {
|
||||
Input Values `json:"input"`
|
||||
ResourceTarget *protocol.ResourceTarget `json:"resource_target"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(data), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(payload.ResourceTarget, want) {
|
||||
t.Fatalf("resource target = %#v, want %#v", payload.ResourceTarget, want)
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(data), &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var targetFields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(fields["resource_target"], &targetFields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(targetFields) != 2 || targetFields["member"] == nil || targetFields["metadata"] == nil {
|
||||
t.Fatalf("resource target leaked non-target fields: %s", fields["resource_target"])
|
||||
}
|
||||
if !reflect.DeepEqual(payload.Input, wantInput) {
|
||||
t.Fatalf("input = %#v, want %#v", payload.Input, wantInput)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelResultValidationAndRetryBudget(t *testing.T) {
|
||||
for _, text := range []string{
|
||||
`not json`, `{"outcome":"missing","output":{}}`, `{"outcome":"success"}`,
|
||||
|
||||
Reference in New Issue
Block a user