@gtheys/pi-flow 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +833 -2
- package/adhoc/tracker.ts +360 -0
- package/aven/client.ts +996 -0
- package/aven/status.ts +395 -0
- package/brainstorm/args.ts +24 -0
- package/brainstorm/artifact.ts +67 -0
- package/brainstorm/paths.ts +43 -0
- package/brainstorm/prompt.ts +172 -0
- package/brainstorm/refs.ts +41 -0
- package/config.schema.json +161 -0
- package/config.ts +577 -0
- package/feedback/args.ts +21 -0
- package/feedback/prompt.ts +177 -0
- package/feedback/triage.ts +88 -0
- package/flow/agent-role.ts +46 -0
- package/flow/answer-wake.ts +212 -0
- package/flow/answer.ts +183 -0
- package/flow/args.ts +48 -0
- package/flow/ask-emitter.ts +331 -0
- package/flow/attribution.ts +145 -0
- package/flow/aven-resolve-exec.ts +95 -0
- package/flow/aven-resolve.ts +80 -0
- package/flow/awaiting-approval.ts +32 -0
- package/flow/binding-heal.ts +68 -0
- package/flow/cost-autopush.ts +162 -0
- package/flow/cost-command.ts +122 -0
- package/flow/cost-rows-journal.ts +296 -0
- package/flow/cost-rows-push.ts +112 -0
- package/flow/cost-rows-rows.ts +209 -0
- package/flow/cost-rows.ts +228 -0
- package/flow/cost.ts +173 -0
- package/flow/durable-refs.ts +287 -0
- package/flow/effect-gate.ts +137 -0
- package/flow/ensure-labels.ts +44 -0
- package/flow/frame.ts +172 -0
- package/flow/gates.ts +211 -0
- package/flow/jira-ref.ts +212 -0
- package/flow/label-gate.ts +149 -0
- package/flow/land-gate.ts +98 -0
- package/flow/lifecycle-policy.ts +162 -0
- package/flow/live-wait.ts +52 -0
- package/flow/liveness.ts +408 -0
- package/flow/loop-deps.ts +210 -0
- package/flow/loop-settle.ts +531 -0
- package/flow/loop.ts +437 -0
- package/flow/orchestrate.ts +45 -0
- package/flow/phase-command.ts +287 -0
- package/flow/phase-emoji.ts +13 -0
- package/flow/phase-prompts.ts +251 -0
- package/flow/picker.ts +307 -0
- package/flow/push.ts +475 -0
- package/flow/reconcile-command.ts +253 -0
- package/flow/reconcile-deps.ts +329 -0
- package/flow/reconcile.ts +738 -0
- package/flow/ref-kind.ts +80 -0
- package/flow/resume-picker.ts +222 -0
- package/flow/resume.ts +116 -0
- package/flow/run-health.ts +252 -0
- package/flow/run-liveness.ts +33 -0
- package/flow/state-metrics.ts +559 -0
- package/flow/status.ts +105 -0
- package/flow/step-output.ts +416 -0
- package/flow/steps.ts +73 -0
- package/flow/terminal-purge.ts +281 -0
- package/flow/turn-generation.ts +19 -0
- package/flow/v2-emission.ts +381 -0
- package/flow/v2-resume.ts +100 -0
- package/flow/vocabulary.ts +261 -0
- package/flow/widget.ts +448 -0
- package/flow/worktree-context.ts +136 -0
- package/flow-diagram/assemble.ts +27 -0
- package/flow-diagram/command.ts +252 -0
- package/flow-diagram/translate.ts +862 -0
- package/flow-diagram/vendor/harness-profiler/LICENSE +21 -0
- package/flow-diagram/vendor/harness-profiler/PIN.md +64 -0
- package/flow-diagram/vendor/harness-profiler/hp.js +960 -0
- package/flow-diagram/vendor/harness-profiler/load.ts +66 -0
- package/flow-diagram/vendor/harness-profiler/view.html +436 -0
- package/gates.ts +20 -0
- package/herdr/sync.ts +355 -0
- package/herdr/viewer.ts +432 -0
- package/implement/args.ts +21 -0
- package/implement/prompt.ts +98 -0
- package/implement/retry.ts +57 -0
- package/implement/routing.ts +31 -0
- package/index.ts +3206 -0
- package/mode-profile.ts +56 -0
- package/package.json +205 -4
- package/phase-state.ts +18 -0
- package/plan/args.ts +20 -0
- package/plan/prompt.ts +251 -0
- package/plan/size-check.ts +46 -0
- package/plan-tools/helpers.ts +177 -0
- package/plan-tools/jira-branch-tool.ts +54 -0
- package/plan-tools/jira-branch.ts +109 -0
- package/plan-tools/jira-issue.ts +85 -0
- package/plan-tools/resolve-feature-path.ts +30 -0
- package/plan-tools/resolve-notes-path.ts +37 -0
- package/plan-tools/resolve-spec-path.ts +31 -0
- package/pr-quality/index.ts +908 -0
- package/review/LICENSE +19 -0
- package/review/deviation.ts +252 -0
- package/review/review.ts +3053 -0
- package/review/sem-guidance.d.mts +8 -0
- package/review/sem-guidance.mjs +89 -0
- package/review/verdict.ts +13 -0
- package/run-state.ts +2046 -0
- package/run-title.ts +91 -0
- package/server/consumer.ts +146 -0
- package/server/daemon.ts +1094 -0
- package/server/lifecycle.ts +679 -0
- package/server/pending.ts +267 -0
- package/server/staleness.ts +320 -0
- package/server/writer.ts +86 -0
- package/shared/diff-base.ts +138 -0
- package/shared/flow-base.ts +210 -0
- package/shared/sonarqube-utils.ts +415 -0
- package/shared/stable-range.ts +102 -0
- package/slugify.ts +13 -0
- package/sonarqube/sonarqube.ts +821 -0
- package/spec-review/approve.ts +91 -0
- package/spec-review/args.ts +21 -0
- package/spec-review/aven-spec.ts +142 -0
- package/spec-review/commands.ts +336 -0
- package/spec-review/escape-regexp.ts +7 -0
- package/spec-review/open-in-pane.ts +166 -0
- package/spec-review/picker.ts +74 -0
- package/spec-review/prompt.ts +72 -0
- package/spec-review/publish-args.ts +33 -0
- package/spec-review/publish.ts +210 -0
- package/telemetry/attributes.ts +118 -0
- package/telemetry/content.ts +140 -0
- package/telemetry/dispatch.ts +521 -0
- package/telemetry/exporter.ts +124 -0
- package/telemetry/index.ts +776 -0
- package/telemetry/loki.ts +224 -0
- package/tools/code-review-parse.ts +518 -0
- package/tools/code-review.ts +312 -0
- package/tools/deviation.ts +737 -0
- package/tools/flow-submit.ts +302 -0
- package/tools/land.ts +608 -0
- package/tools/phase-complete.ts +476 -0
- package/tools/result.ts +18 -0
- package/tools/review-deps.ts +44 -0
- package/tools/run-attempt.ts +312 -0
- package/tools/spec-approve.ts +265 -0
- package/validate/args.ts +22 -0
- package/validate/deviation-gate.ts +229 -0
- package/validate/gate-target.ts +371 -0
- package/validate/gate.ts +79 -0
- package/validate/paths.ts +20 -0
- package/validate/personal.ts +104 -0
- package/validate/prompt.ts +525 -0
- package/validate/review-gate.ts +134 -0
- package/validate/subtask-range.ts +113 -0
- package/work-mode.ts +19 -0
- package/worktree/bootstrap.ts +243 -0
- package/worktree/branch.ts +168 -0
- package/worktree/herdr.ts +447 -0
- package/worktree/index.ts +1447 -0
- package/worktree/orphan.ts +384 -0
- package/worktree/remove-guards.ts +99 -0
- package/worktree/residue.ts +216 -0
- package/worktree/sweep.ts +526 -0
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// AIDEV-NOTE: PMR-06RH — tooling-owned retry budget. The agent reports each
|
|
2
|
+
// attempt's outcome here instead of counting in its head: the tool owns the
|
|
3
|
+
// RetryState (per ref; the in-memory Map is the runtime cache seeded from the
|
|
4
|
+
// durable ledger) and nextAttempt decides retry vs escalate. Escalation is
|
|
5
|
+
// surfaced as a tool error AND an aven note; after it, further attempts for
|
|
6
|
+
// the ref are refused without a new note (PMR-2HFC).
|
|
7
|
+
// AIDEV-NOTE: PMR-XTQQ 4.2 — the budget IS durable now: every transition is
|
|
8
|
+
// journaled as an `attempt-record` event via the writer seam, and a fresh
|
|
9
|
+
// instance seeds its Map from the journal's latest snapshot for the ref
|
|
10
|
+
// (null/absent → startRetry, i.e. today's fresh-session behavior). Degrade is
|
|
11
|
+
// best-effort like every journal write: a ledger read/io failure falls back
|
|
12
|
+
// to the in-memory-only Map — the budget must never brick the tool. The aven
|
|
13
|
+
// escalation-note path is unchanged.
|
|
14
|
+
|
|
15
|
+
import { promises as fs } from 'node:fs'
|
|
16
|
+
import type {
|
|
17
|
+
AgentToolResult,
|
|
18
|
+
ExtensionAPI,
|
|
19
|
+
} from '@earendil-works/pi-coding-agent'
|
|
20
|
+
import { getAgentDir } from '@earendil-works/pi-coding-agent'
|
|
21
|
+
import { Type } from 'typebox'
|
|
22
|
+
import { applyAvenErrorLabel, writeAvenNote } from '../aven/client.ts'
|
|
23
|
+
import {
|
|
24
|
+
type AttemptResult,
|
|
25
|
+
MAX_ATTEMPTS,
|
|
26
|
+
nextAttempt,
|
|
27
|
+
type RetryState,
|
|
28
|
+
startRetry,
|
|
29
|
+
} from '../implement/retry.ts'
|
|
30
|
+
import {
|
|
31
|
+
type FlowRunEvent,
|
|
32
|
+
isYoloRun,
|
|
33
|
+
readRunEvents,
|
|
34
|
+
recordRunEvent,
|
|
35
|
+
} from '../run-state.ts'
|
|
36
|
+
import { toolResult } from './result.ts'
|
|
37
|
+
|
|
38
|
+
export type AttemptOutcome = 'passed' | 'retry' | 'escalate'
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* AIDEV-NOTE: PMR-XTQQ 4.2 — durable twin of the in-memory RetryState Map.
|
|
42
|
+
* `seed` returns the ref's journaled budget count (null = no journal /
|
|
43
|
+
* unreadable / no snapshot yet); `record` journals the post-transition
|
|
44
|
+
* snapshot. Both are best-effort: callers swallow failures and degrade to
|
|
45
|
+
* in-memory behavior.
|
|
46
|
+
*/
|
|
47
|
+
export interface AttemptLedger {
|
|
48
|
+
seed(ref: string): Promise<number | null>
|
|
49
|
+
record(ref: string, outcome: AttemptOutcome, attempts: number): Promise<void>
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* AIDEV-NOTE: PMR-XTQQ 4.2 — default ledger over the run journal. Reads via
|
|
54
|
+
* readRunEvents (last-wins `attempt-record` per ref; 'passed' → 0). Writes
|
|
55
|
+
* via the injected `record` fn (index.ts threads the mode-aware writer seam,
|
|
56
|
+
* journal-only while the daemon owns the projection); absent = today's full
|
|
57
|
+
* recordRunEvent path. All io is swallowed by the tool — never brick.
|
|
58
|
+
*/
|
|
59
|
+
export function createAttemptLedger(
|
|
60
|
+
agentDir: string,
|
|
61
|
+
deps: {
|
|
62
|
+
readFile?: (p: string) => Promise<string>
|
|
63
|
+
record?: (event: FlowRunEvent) => Promise<void>
|
|
64
|
+
} = {},
|
|
65
|
+
): AttemptLedger {
|
|
66
|
+
const readFile = deps.readFile ?? ((p: string) => fs.readFile(p, 'utf8'))
|
|
67
|
+
return {
|
|
68
|
+
seed: async (ref) => {
|
|
69
|
+
const events = await readRunEvents(agentDir, ref, { readFile })
|
|
70
|
+
if (events === null) return null
|
|
71
|
+
// AIDEV-NOTE: PMR-5HTN — pick the TRUE latest by timestamp, not file
|
|
72
|
+
// order: a nested worker and the main session append to the same
|
|
73
|
+
// journal with O_APPEND, and file order can interleave an older
|
|
74
|
+
// snapshot after a newer one, which would seed the budget from a stale
|
|
75
|
+
// count and REGRESS it (fail-open). ISO timestamps from one host sort
|
|
76
|
+
// lexicographically; equal timestamps fall back to file order (>=).
|
|
77
|
+
let latest: number | null = null
|
|
78
|
+
let latestAt: string | null = null
|
|
79
|
+
for (const event of events) {
|
|
80
|
+
if (event.kind !== 'attempt-record') continue
|
|
81
|
+
if (event.ref !== ref) continue
|
|
82
|
+
const value = event.outcome === 'passed' ? 0 : event.attempts
|
|
83
|
+
if (latestAt === null || event.at >= latestAt) {
|
|
84
|
+
latestAt = event.at
|
|
85
|
+
latest = value
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return latest
|
|
89
|
+
},
|
|
90
|
+
record: async (ref, outcome, attempts) => {
|
|
91
|
+
const event: FlowRunEvent = {
|
|
92
|
+
kind: 'attempt-record',
|
|
93
|
+
at: new Date().toISOString(),
|
|
94
|
+
ref,
|
|
95
|
+
tool: 'flow_run_attempt',
|
|
96
|
+
outcome,
|
|
97
|
+
attempts,
|
|
98
|
+
}
|
|
99
|
+
if (deps.record !== undefined) {
|
|
100
|
+
try {
|
|
101
|
+
await deps.record(event)
|
|
102
|
+
} catch {
|
|
103
|
+
// best-effort — journal failures never break the budget
|
|
104
|
+
}
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
// AIDEV-NOTE: PMR-ZV9Y 4.3 (fan-out audit, scout §3 exception) — this
|
|
108
|
+
// direct recordRunEvent fallback is the ONE journal write on the tool
|
|
109
|
+
// paths that bypasses the mode-aware writer, so it also bypasses the
|
|
110
|
+
// telemetry fan-out wrapper. Deliberately NOT routed: the kind written
|
|
111
|
+
// here is `attempt-record`, not a v2 event, so there is nothing for
|
|
112
|
+
// Loki/Tempo to render, and index.ts always injects the `record` seam
|
|
113
|
+
// above anyway (the fallback only fires for bare-ledger callers). The
|
|
114
|
+
// escalation's v2 state-change rides deps.journalV2 -> the wrapped
|
|
115
|
+
// writer. Pinned by test/telemetry-dispatch.test.ts.
|
|
116
|
+
try {
|
|
117
|
+
await recordRunEvent(agentDir, event)
|
|
118
|
+
} catch {
|
|
119
|
+
// best-effort — journal failures never break the budget
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function registerRunAttemptTool(
|
|
126
|
+
pi: ExtensionAPI,
|
|
127
|
+
ledger: AttemptLedger = createAttemptLedger(getAgentDir()),
|
|
128
|
+
// AIDEV-NOTE: yolo 5.2 — injectable seams (production defaults), mirroring
|
|
129
|
+
// the 3.1/3.2 pattern in phase-complete/spec-approve: tests stub both the
|
|
130
|
+
// yolo read and the label write. `error` is a type label, outside
|
|
131
|
+
// lifecycleLabelMutation, applied on yolo escalations only; a label
|
|
132
|
+
// failure never changes the escalation result.
|
|
133
|
+
deps: {
|
|
134
|
+
isYoloRunFn?: (ref: string) => Promise<boolean>
|
|
135
|
+
applyErrorLabel?: (ref: string) => Promise<boolean>
|
|
136
|
+
/**
|
|
137
|
+
* AIDEV-NOTE: PMR-ZV9Y 2.2 — v2 state-machine emission seam for the
|
|
138
|
+
* escalation wait: index.ts wires this to the SAME mode-aware writer it
|
|
139
|
+
* threads into createAttemptLedger(...).record, so the durable
|
|
140
|
+
* attempt-record snapshot and the state-change land in one journal and
|
|
141
|
+
* reach the PMR-ZV9Y phase-4 fan-out together. It is a SEPARATE optional
|
|
142
|
+
* dep on purpose: the ledger's `record` builds an `attempt-record`
|
|
143
|
+
* event and cannot carry a v2 kind, and the pre-existing
|
|
144
|
+
* test/run-attempt-tool.test.ts fakes (hand-built `{seed, record}`
|
|
145
|
+
* ledgers and deps bags without this field) must stay byte-identical
|
|
146
|
+
* (ISC-A-2) — unset seam = no v2 events, never a crash. The tool wraps
|
|
147
|
+
* the call, so a throwing seam can NEVER change the escalation outcome
|
|
148
|
+
* (ISC-A-5).
|
|
149
|
+
*/
|
|
150
|
+
journalV2?(event: FlowRunEvent): Promise<void> | void
|
|
151
|
+
} = {},
|
|
152
|
+
): void {
|
|
153
|
+
const isYoloRunFn = deps.isYoloRunFn ?? isYoloRun
|
|
154
|
+
const applyErrorLabel = deps.applyErrorLabel ?? applyAvenErrorLabel
|
|
155
|
+
const retryStates = new Map<string, RetryState>()
|
|
156
|
+
pi.registerTool({
|
|
157
|
+
name: 'flow_run_attempt',
|
|
158
|
+
label: 'flow run attempt',
|
|
159
|
+
description:
|
|
160
|
+
'Record one test attempt for a flow task and get the retry decision from the owned budget (3 total attempts, then escalate). The 3rd failing attempt returns an escalation error — STOP and report to the human; further attempts are refused (the budget persists in the run journal and resets when an attempt passes).',
|
|
161
|
+
promptSnippet:
|
|
162
|
+
'Retry-budget tracking for flow test attempts — report every attempt result here.',
|
|
163
|
+
promptGuidelines: [
|
|
164
|
+
'After EVERY test run in this phase, call flow_run_attempt with the outcome before deciding the next step — never count attempts yourself.',
|
|
165
|
+
'An escalation result means STOP: report to the human, do not run further attempts.',
|
|
166
|
+
],
|
|
167
|
+
parameters: Type.Object({
|
|
168
|
+
ref: Type.String({ description: 'Aven ticket ref, e.g. PMR-ABC1' }),
|
|
169
|
+
result: Type.Object({
|
|
170
|
+
ok: Type.Boolean({ description: 'Whether the test attempt passed' }),
|
|
171
|
+
lastError: Type.Optional(
|
|
172
|
+
Type.String({ description: 'The failing test’s error message' }),
|
|
173
|
+
),
|
|
174
|
+
commands: Type.Optional(
|
|
175
|
+
Type.Array(Type.String(), {
|
|
176
|
+
description: 'Commands run in this attempt',
|
|
177
|
+
}),
|
|
178
|
+
),
|
|
179
|
+
hypothesis: Type.Optional(
|
|
180
|
+
Type.String({ description: 'What this attempt tried to change' }),
|
|
181
|
+
),
|
|
182
|
+
}),
|
|
183
|
+
}),
|
|
184
|
+
async execute(
|
|
185
|
+
_toolCallId: string,
|
|
186
|
+
params: {
|
|
187
|
+
ref: string
|
|
188
|
+
result: AttemptResult
|
|
189
|
+
},
|
|
190
|
+
): Promise<AgentToolResult<{ ok: boolean; status: string }>> {
|
|
191
|
+
// AIDEV-NOTE: PMR-XTQQ 4.2 — journal each transition outcome.
|
|
192
|
+
// Best-effort: an io failure is swallowed and the tool degrades to the
|
|
193
|
+
// in-memory Map — the budget must never brick the tool.
|
|
194
|
+
const journalOutcome = async (
|
|
195
|
+
outcome: AttemptOutcome,
|
|
196
|
+
attempts: number,
|
|
197
|
+
): Promise<void> => {
|
|
198
|
+
try {
|
|
199
|
+
await ledger.record(params.ref, outcome, attempts)
|
|
200
|
+
} catch {
|
|
201
|
+
// degrade to in-memory behavior
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
let state = retryStates.get(params.ref)
|
|
205
|
+
if (state === undefined) {
|
|
206
|
+
// AIDEV-NOTE: PMR-XTQQ 4.2 — first call per ref: seed from the
|
|
207
|
+
// journal's latest attempt-record; io failure → startRetry (degrade
|
|
208
|
+
// to in-memory, never brick).
|
|
209
|
+
let count: number | null
|
|
210
|
+
try {
|
|
211
|
+
count = await ledger.seed(params.ref)
|
|
212
|
+
} catch {
|
|
213
|
+
count = null
|
|
214
|
+
}
|
|
215
|
+
if (count === null) {
|
|
216
|
+
state = startRetry()
|
|
217
|
+
} else if (count >= MAX_ATTEMPTS) {
|
|
218
|
+
state = { attempts: MAX_ATTEMPTS }
|
|
219
|
+
} else {
|
|
220
|
+
state = { attempts: count }
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// AIDEV-NOTE: PMR-2HFC — already exhausted: refuse without re-running
|
|
224
|
+
// the machine, so no duplicate escalation note is written.
|
|
225
|
+
if (state.attempts >= MAX_ATTEMPTS) {
|
|
226
|
+
return toolResult(
|
|
227
|
+
`flow_run_attempt: retry budget already exhausted for ${params.ref} — attempt refused. STOP and report to the human; do not run further attempts.`,
|
|
228
|
+
{ ok: false, status: 'escalate' },
|
|
229
|
+
{ isError: true },
|
|
230
|
+
)
|
|
231
|
+
}
|
|
232
|
+
const transition = nextAttempt(state, params.result)
|
|
233
|
+
if (transition.status === 'passed') {
|
|
234
|
+
await journalOutcome('passed', 0)
|
|
235
|
+
retryStates.delete(params.ref)
|
|
236
|
+
return toolResult(
|
|
237
|
+
`flow_run_attempt: tests passed for ${params.ref} — commit the green change`,
|
|
238
|
+
{ ok: true, status: 'passed' },
|
|
239
|
+
)
|
|
240
|
+
}
|
|
241
|
+
if (transition.status === 'retry') {
|
|
242
|
+
await journalOutcome('retry', transition.state.attempts)
|
|
243
|
+
retryStates.set(params.ref, transition.state)
|
|
244
|
+
return toolResult(
|
|
245
|
+
`flow_run_attempt: attempt ${transition.state.attempts}/${MAX_ATTEMPTS} failed for ${params.ref} — retry permitted (${MAX_ATTEMPTS - transition.state.attempts} left in budget)`,
|
|
246
|
+
{ ok: false, status: 'retry' },
|
|
247
|
+
)
|
|
248
|
+
}
|
|
249
|
+
const e = transition.escalation
|
|
250
|
+
const note = `escalated after ${MAX_ATTEMPTS} failed attempts — commands: ${e.commands.join(' ; ') || 'none recorded'}; last error: ${e.lastError}; hypothesis: ${e.hypothesis}`
|
|
251
|
+
const noted = await writeAvenNote(params.ref, note)
|
|
252
|
+
// AIDEV-NOTE: yolo 5.2 — best-effort `error` label on the escalation
|
|
253
|
+
// path, yolo runs only. Mirrors 5.1: never throws, failure only adds a
|
|
254
|
+
// suffix and never changes the escalation result; further attempts stay
|
|
255
|
+
// refused as before.
|
|
256
|
+
let labelSuffix = ''
|
|
257
|
+
let yolo = false
|
|
258
|
+
try {
|
|
259
|
+
yolo = await isYoloRunFn(params.ref)
|
|
260
|
+
} catch {
|
|
261
|
+
yolo = false
|
|
262
|
+
}
|
|
263
|
+
if (yolo) {
|
|
264
|
+
let labeled = false
|
|
265
|
+
try {
|
|
266
|
+
labeled = await applyErrorLabel(params.ref)
|
|
267
|
+
} catch {
|
|
268
|
+
labeled = false
|
|
269
|
+
}
|
|
270
|
+
if (!labeled) {
|
|
271
|
+
labelSuffix = ' (error label write FAILED — record this manually)'
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
await journalOutcome('escalate', MAX_ATTEMPTS)
|
|
275
|
+
// AIDEV-NOTE: PMR-ZV9Y 2.2 — the escalation IS a human wait, so journal
|
|
276
|
+
// state-change{waiting_human, escalation} beside the attempt-record
|
|
277
|
+
// snapshot (plan mapping row "run-attempt escalate"). Escalate ONLY:
|
|
278
|
+
// passed/retry keep the run `running` and the loop owns that transition
|
|
279
|
+
// (no running→running-style duplicates from this site). The
|
|
280
|
+
// already-exhausted refusal above never reaches this line, so one
|
|
281
|
+
// escalation journals exactly one wait. Best-effort and optional:
|
|
282
|
+
// `journalV2?.()` + try/catch, a journal failure cannot change the
|
|
283
|
+
// escalation result (ISC-A-5). AUDITED in PMR-ZV9Y 4.3: index.ts wires
|
|
284
|
+
// this seam onto the SAME writer the fan-out wraps, so the escalation
|
|
285
|
+
// wait DOES reach Loki, and it never touches the recordRunEvent
|
|
286
|
+
// fallback above (that kind is non-v2 and stays unrouted by design).
|
|
287
|
+
try {
|
|
288
|
+
await deps.journalV2?.({
|
|
289
|
+
kind: 'state-change',
|
|
290
|
+
at: new Date().toISOString(),
|
|
291
|
+
ref: params.ref,
|
|
292
|
+
state: 'waiting_human',
|
|
293
|
+
reason: 'escalation',
|
|
294
|
+
})
|
|
295
|
+
} catch {
|
|
296
|
+
// best-effort — the budget decision is already made
|
|
297
|
+
}
|
|
298
|
+
// Keep the exhausted state so further reports keep escalating instead
|
|
299
|
+
// of silently restarting the budget.
|
|
300
|
+
retryStates.set(params.ref, { attempts: MAX_ATTEMPTS })
|
|
301
|
+
let suffix = labelSuffix
|
|
302
|
+
if (!noted) {
|
|
303
|
+
suffix += ' (aven note write FAILED — record this manually)'
|
|
304
|
+
}
|
|
305
|
+
return toolResult(
|
|
306
|
+
`flow_run_attempt: retry budget exhausted for ${params.ref} — ESCALATE to the human. ${note}${suffix}`,
|
|
307
|
+
{ ok: false, status: 'escalate' },
|
|
308
|
+
{ isError: true },
|
|
309
|
+
)
|
|
310
|
+
},
|
|
311
|
+
})
|
|
312
|
+
}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// AIDEV-NOTE: spec_approve (PMR-MR36 fix round). Agent-callable wrapper
|
|
2
|
+
// around approveSpec — the injected /spec-review prompt used to make the
|
|
3
|
+
// model run a raw `aven edit`, losing loud failure and the workspace pin.
|
|
4
|
+
// Workspace resolution mirrors the spec commands (resolveSpecWorkspace in
|
|
5
|
+
// aven/client.ts); failure is a loud tool error, never a silent no-op.
|
|
6
|
+
// PMR-R5VB: prompt guidelines alone were not model-proof, so the model-call
|
|
7
|
+
// path is gated on a human answer receipt: readGateAnswer must return
|
|
8
|
+
// 'approve' before any aven edit. That GATE receipt is read-only here — it
|
|
9
|
+
// is never consumed or cleared; its only use is the gate check itself. The
|
|
10
|
+
// separate JOURNAL receipt is different (PMR-CD46): recorded best-effort
|
|
11
|
+
// after a successful approval and adopted on later runs for dedup
|
|
12
|
+
// (current-run-bound since PMR-N0D5 — see the anchor above the find call).
|
|
13
|
+
// PMR-J6TW: tickets carrying the `oneshot` label skip the receipt gate —
|
|
14
|
+
// journal-first since PMR-N0D5: a journaled run-start switches the
|
|
15
|
+
// exemption to the run-start oneshot snapshot (mid-run label mutation
|
|
16
|
+
// cannot mint it); the live label exempts only truly standalone calls with
|
|
17
|
+
// no journal. The oneshot route (PMR-3HMZ) never produces a receipt by
|
|
18
|
+
// design. A failed labels read on the fallback path is NOT a new failure
|
|
19
|
+
// mode: it falls through to the legacy gate, mirroring approveSpec's own
|
|
20
|
+
// oneshot check.
|
|
21
|
+
// AIDEV-NOTE: PMR-AYMZ — the PLAN gate in tools/phase-complete.ts
|
|
22
|
+
// additionally honors a mid-run confirmed oneshot route (epoch-current
|
|
23
|
+
// ok=true plan.route-confirmed step-output AND the live oneshot label).
|
|
24
|
+
// spec_approve deliberately does NOT: a true oneshot never enters spec
|
|
25
|
+
// review (the oneshot route skips the plan file and approval entirely), so
|
|
26
|
+
// the broader leg is unreachable here and this gate keeps the strict
|
|
27
|
+
// journal-first snapshot exemption.
|
|
28
|
+
// AIDEV-NOTE: PMR-CD46 — single-use dedup realized via receipt adoption:
|
|
29
|
+
// a stored {ref, command:'spec_approve', target:'plan'} receipt (recorded
|
|
30
|
+
// best-effort after a prior successful approval, PMR-4S6V machinery) is
|
|
31
|
+
// adopted FIRST, before the human gate — a stored receipt can only exist
|
|
32
|
+
// because a prior human-gated approval succeeded, so adoption short-circuits
|
|
33
|
+
// even if the spec-answer metadata was later cleared. Missing/corrupt
|
|
34
|
+
// receipts fall forward to the gate + fresh edit exactly as before; journal
|
|
35
|
+
// failures never block an approval. PMR-FA3D — the dedup is FLOW-RUN-ONLY:
|
|
36
|
+
// recordRunEvent's projection gate drops receipt events for refs without run
|
|
37
|
+
// state, so outside a flow run (standalone /spec-review usage) the receipt is
|
|
38
|
+
// never journaled and every duplicate call re-checks the human gate — a
|
|
39
|
+
// deliberate fail-safe degradation (worst case: the human answers approve
|
|
40
|
+
// again), pinned by a test in test/run-state.test.ts.
|
|
41
|
+
// AIDEV-NOTE: PMR-N0D5 — the adoption is CURRENT-RUN-BOUND: the lookup
|
|
42
|
+
// passes currentRunEpoch:true, so only receipts minted at/after the latest
|
|
43
|
+
// journaled run-start dedupe (a receipt from a previous run epoch falls
|
|
44
|
+
// through to the human gate; no journaled run-start = never adopt). Same-run
|
|
45
|
+
// idempotent adoption is preserved, and the epoch rule is opt-in at the
|
|
46
|
+
// ReceiptQuery level so flow_land's landing-authority adoption is untouched.
|
|
47
|
+
// The human gate is additionally bound to the plan revision: the approve
|
|
48
|
+
// answer journaled by /flow answer carries the plan content hash at answer
|
|
49
|
+
// time (readSpecAnswerBinding / specAnswerBindingRefusal in run-state.ts);
|
|
50
|
+
// a plan edit after the answer — or an unbound/unresolvable journal answer
|
|
51
|
+
// — refuses with the re-answer recovery. With NO journal evidence the
|
|
52
|
+
// binding is skipped: standalone approvals keep the metadata-only gate
|
|
53
|
+
// (PMR-FA3D), and the oneshot exemption keeps its live-label fallback for
|
|
54
|
+
// truly standalone calls while a journaled run-start switches the exemption
|
|
55
|
+
// to the run-start snapshot (mid-run label mutation cannot mint it).
|
|
56
|
+
import type {
|
|
57
|
+
AgentToolResult,
|
|
58
|
+
ExtensionAPI,
|
|
59
|
+
} from '@earendil-works/pi-coding-agent'
|
|
60
|
+
import { getAgentDir } from '@earendil-works/pi-coding-agent'
|
|
61
|
+
import { Type } from 'typebox'
|
|
62
|
+
import {
|
|
63
|
+
readAvenLabels,
|
|
64
|
+
readGateAnswer,
|
|
65
|
+
readPlanRevision,
|
|
66
|
+
specApprove,
|
|
67
|
+
} from '../aven/client.ts'
|
|
68
|
+
import {
|
|
69
|
+
createReceiptJournal,
|
|
70
|
+
isYoloRunCurrent,
|
|
71
|
+
type ReceiptJournal,
|
|
72
|
+
readOneshotSnapshot,
|
|
73
|
+
readSpecAnswerBinding,
|
|
74
|
+
specAnswerBindingRefusal,
|
|
75
|
+
} from '../run-state.ts'
|
|
76
|
+
import type { EventWriter } from '../server/writer.ts'
|
|
77
|
+
import { toolResult } from './result.ts'
|
|
78
|
+
|
|
79
|
+
// AIDEV-NOTE: PMR-CD46 — best-effort receipt write; a journal failure never
|
|
80
|
+
// fails the tool result, mirroring recordPhaseReceipt (PMR-4S6V).
|
|
81
|
+
async function recordSpecReceipt(receipts: ReceiptJournal, ref: string) {
|
|
82
|
+
await receipts
|
|
83
|
+
.record({ ref, command: 'spec_approve', target: 'plan' })
|
|
84
|
+
.catch(() => {
|
|
85
|
+
// best-effort — journal failures never fail the tool result
|
|
86
|
+
})
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// AIDEV-NOTE: PMR-CD46 — signature mirrors registerPhaseCompleteTool
|
|
90
|
+
// (PMR-4S6V/PMR-XTQQ): receipts defaults to the real run-journal-backed
|
|
91
|
+
// journal so callers stay untouched; optional mode-aware writer routes
|
|
92
|
+
// receipt writes journal-only while the daemon owns the projection.
|
|
93
|
+
export function registerSpecApproveTool(
|
|
94
|
+
pi: ExtensionAPI,
|
|
95
|
+
receipts: ReceiptJournal = createReceiptJournal(getAgentDir()),
|
|
96
|
+
writer?: EventWriter,
|
|
97
|
+
// AIDEV-NOTE: yolo plan 3.2 — injectable for tests; the PMR-N0D5 default
|
|
98
|
+
// is the EPOCH-AWARE isYoloRunCurrent (journaled after the latest
|
|
99
|
+
// run-start, non-terminal loop, else no exemption — fail-closed). The
|
|
100
|
+
// exemption is this parameter's ONLY consumer in this tool.
|
|
101
|
+
isYoloRunFn: (ref: string) => Promise<boolean> = isYoloRunCurrent,
|
|
102
|
+
): void {
|
|
103
|
+
let effectiveReceipts = receipts
|
|
104
|
+
if (writer !== undefined) {
|
|
105
|
+
effectiveReceipts = createReceiptJournal(
|
|
106
|
+
getAgentDir(),
|
|
107
|
+
undefined,
|
|
108
|
+
writer.record,
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
pi.registerTool({
|
|
112
|
+
name: 'spec_approve',
|
|
113
|
+
label: 'spec approve',
|
|
114
|
+
description:
|
|
115
|
+
'Approve a spec under review: pins it to the plan label, sets plan-state=approved, moves it to todo. This is the ONLY way to approve a spec — never run `aven edit <ref> --metadata plan-state=approved` yourself. Tickets carrying the oneshot label OR runs journaled as yolo (--yolo) skip the receipt gate. Refuses when the approval receipt predates the latest run start for the ref, or when the plan file changed after the recorded approval (stale answer) — in both cases the human must re-record /flow answer <ref> approve. After this returns ok, call the spec_publish tool with the same ref.',
|
|
116
|
+
promptSnippet:
|
|
117
|
+
'Approval transition for specs in plan-state=review — call instead of raw aven edits.',
|
|
118
|
+
// AIDEV-NOTE: PMR-DMHH 4.2 — guideline 1 frames the recorded receipt
|
|
119
|
+
// as the sole approval signal: recording it auto-wakes the session
|
|
120
|
+
// (the dispatcher's onGateAnswered hook in index.ts wakes the waiting
|
|
121
|
+
// session), so the agent proceeds when re-prompted instead of waiting
|
|
122
|
+
// for a spoken "approve". A spoken word alone only means "go check" —
|
|
123
|
+
// call the tool and let the fail-closed receipt gate (PMR-R5VB)
|
|
124
|
+
// refuse when the receipt is absent. The oneshot (PMR-J6TW) and yolo
|
|
125
|
+
// (PMR-ZWX8) exemptions are unchanged.
|
|
126
|
+
promptGuidelines: [
|
|
127
|
+
'Call spec_approve for the ref the human named once the approval receipt has been recorded — the human runs `/flow answer <ref> approve` (human-only), and that recorded receipt is the sole approval signal. After the receipt is recorded this session is woken automatically, so proceed without waiting for a spoken "approve". A spoken "approve <REF>" without a receipt only means "go check": call the tool anyway and let it refuse fail-closed when the receipt is absent, then tell the human to record the answer with `/flow answer <ref> approve`. Tickets carrying the `oneshot` label skip this receipt, and so do runs the human started with --yolo.',
|
|
128
|
+
'After spec_approve returns ok, call the spec_publish tool with that ref (never the /spec-publish slash command — agents cannot run slash commands). On a tool error, report the reason to the user — do not retry with raw aven commands. If spec_approve refuses with "no human approval receipt", tell the human to run `/flow answer <ref> approve`, then re-call spec_approve once the receipt exists.',
|
|
129
|
+
'Dedup is flow-run-only (PMR-FA3D): outside an active flow run the approval receipt is not journaled, so a repeated spec_approve re-checks the human gate instead of adopting a stored receipt. That is expected fail-safe behavior, not an error — the human gate simply applies again.',
|
|
130
|
+
'Freshness (PMR-N0D5): spec_approve only adopts receipts minted in the CURRENT run (after the latest run start), and it refuses when the plan file changed after the approval was recorded (stale answer) or when the journaled answer carries no plan-revision binding. On either refusal, tell the human to re-run `/flow answer <ref> approve` after the plan is final, then re-call spec_approve.',
|
|
131
|
+
],
|
|
132
|
+
parameters: Type.Object({
|
|
133
|
+
ref: Type.String({ description: 'Aven ticket ref, e.g. PMR-ABC1' }),
|
|
134
|
+
workspace: Type.Optional(
|
|
135
|
+
Type.String({
|
|
136
|
+
description:
|
|
137
|
+
'Aven workspace name — only when the spec lives outside the default workspace; normally omitted (config/per-ref resolution applies)',
|
|
138
|
+
}),
|
|
139
|
+
),
|
|
140
|
+
}),
|
|
141
|
+
async execute(
|
|
142
|
+
_toolCallId: string,
|
|
143
|
+
params: { ref: string; workspace?: string },
|
|
144
|
+
): Promise<AgentToolResult<{ ok: boolean; reason: string }>> {
|
|
145
|
+
// AIDEV-NOTE: PMR-CD46 — receipt adoption comes FIRST: a stored
|
|
146
|
+
// receipt implies a prior human-gated approval succeeded, so the
|
|
147
|
+
// dedup check safely short-circuits the gate and the aven edit.
|
|
148
|
+
// PMR-N0D5: currentRunEpoch binds the adoption to the latest run
|
|
149
|
+
// epoch — a receipt minted before the latest run-start no longer
|
|
150
|
+
// dedupes and the flow falls through to the human gate below.
|
|
151
|
+
const stored = await effectiveReceipts.find({
|
|
152
|
+
ref: params.ref,
|
|
153
|
+
command: 'spec_approve',
|
|
154
|
+
target: 'plan',
|
|
155
|
+
currentRunEpoch: true,
|
|
156
|
+
})
|
|
157
|
+
if (stored !== null) {
|
|
158
|
+
const text = `spec_approve: ${params.ref} was already approved — adopting the stored approval receipt; the aven edit was skipped. Proceed to spec_publish.`
|
|
159
|
+
return toolResult(text, { ok: true, reason: 'adopted' })
|
|
160
|
+
}
|
|
161
|
+
// PMR-R5VB receipt gate: fail closed. null covers both a missing
|
|
162
|
+
// spec-answer metadata block and an aven read failure; 'reject' and
|
|
163
|
+
// any non-'approve' choice refuse too. Workspace threading matches
|
|
164
|
+
// specApprove/approveSpec.
|
|
165
|
+
// AIDEV-NOTE: PMR-J6TW — oneshot exemption, now JOURNAL-FIRST
|
|
166
|
+
// (PMR-N0D5 policy decision): when a journaled run-start exists for
|
|
167
|
+
// the ref, the exemption keys on the run-start ONESHOT SNAPSHOT (the
|
|
168
|
+
// ticket's label state at start time), so a mid-run label add cannot
|
|
169
|
+
// mint it; the live `oneshot` label exempts only truly standalone
|
|
170
|
+
// calls with no journal (null snapshot). The labels read stays
|
|
171
|
+
// best-effort and only runs on the fallback path; PMR-3VWM workspace
|
|
172
|
+
// threading is unchanged. PMR-ZWX8 context: the oneshot exemption is
|
|
173
|
+
// a prompt-level checkpoint by accepted design; see the full anchor
|
|
174
|
+
// on the plan-gate check in tools/phase-complete.ts.
|
|
175
|
+
// AIDEV-NOTE: yolo plan 3.2 — third exemption path beside the oneshot
|
|
176
|
+
// label (PMR-ZWX8), mirroring tools/phase-complete.ts (3.1):
|
|
177
|
+
// input.yolo === true is journaled by the run server from the human's
|
|
178
|
+
// CLI invocation (--yolo), not from any agent-writable label or
|
|
179
|
+
// metadata, so a yolo ref cannot be self-granted by the agent and may
|
|
180
|
+
// approve the spec without the approval receipt. The PMR-N0D5 default
|
|
181
|
+
// reader is EPOCH-AWARE (isYoloRunCurrent): a bit journaled before
|
|
182
|
+
// the latest run-start, or a terminal (halted/done) run, yields no
|
|
183
|
+
// exemption and the full gate applies. The isYoloRun read is
|
|
184
|
+
// fail-closed (absent journal / read failure = not yolo → full gate).
|
|
185
|
+
// The receiptMetadataMutation bash interceptor is untouched —
|
|
186
|
+
// synthetic plan-state receipts remain blocked at the shell.
|
|
187
|
+
const oneshotSnapshot = await readOneshotSnapshot(params.ref)
|
|
188
|
+
let labels: string[] | null = null
|
|
189
|
+
if (oneshotSnapshot === null) {
|
|
190
|
+
labels = await readAvenLabels(params.ref, params.workspace)
|
|
191
|
+
}
|
|
192
|
+
let isOneshot: boolean
|
|
193
|
+
if (oneshotSnapshot !== null) {
|
|
194
|
+
isOneshot = oneshotSnapshot
|
|
195
|
+
} else {
|
|
196
|
+
isOneshot = labels?.includes('oneshot') === true
|
|
197
|
+
}
|
|
198
|
+
const isYolo = await isYoloRunFn(params.ref)
|
|
199
|
+
if (!isOneshot && !isYolo) {
|
|
200
|
+
const answer = await readGateAnswer(
|
|
201
|
+
params.ref,
|
|
202
|
+
'spec',
|
|
203
|
+
params.workspace,
|
|
204
|
+
)
|
|
205
|
+
if (answer !== 'approve') {
|
|
206
|
+
let found: string
|
|
207
|
+
if (answer === null) {
|
|
208
|
+
found = 'none/unreadable'
|
|
209
|
+
} else {
|
|
210
|
+
found = answer
|
|
211
|
+
}
|
|
212
|
+
const text = `spec_approve refused: no human approval receipt for ${params.ref} — the human must run /flow answer ${params.ref} approve (human-only slash command; the receipt is the exact-ref-guarded aven spec-answer metadata). Found: ${found}. After the human answers, re-call spec_approve.`
|
|
213
|
+
return toolResult(
|
|
214
|
+
text,
|
|
215
|
+
{ ok: false, reason: text },
|
|
216
|
+
{
|
|
217
|
+
isError: true,
|
|
218
|
+
},
|
|
219
|
+
)
|
|
220
|
+
}
|
|
221
|
+
// AIDEV-NOTE: PMR-N0D5 — plan-revision binding of the approve
|
|
222
|
+
// answer: with journal evidence for the ref, the answer must be
|
|
223
|
+
// bound to the CURRENT plan content hash. Mismatch (plan edited
|
|
224
|
+
// after the answer), an unbound journaled answer, or an
|
|
225
|
+
// unresolvable plan revision all refuse with the re-answer
|
|
226
|
+
// recovery. No journal at all skips this check — the standalone
|
|
227
|
+
// metadata-only gate (PMR-FA3D) is preserved, and the plan read
|
|
228
|
+
// (an extra aven shell-out) only runs on the journaled path.
|
|
229
|
+
const binding = await readSpecAnswerBinding(params.ref)
|
|
230
|
+
if (binding.hasJournal) {
|
|
231
|
+
const currentRevision = await readPlanRevision(
|
|
232
|
+
params.ref,
|
|
233
|
+
params.workspace,
|
|
234
|
+
)
|
|
235
|
+
const bindingRefusal = specAnswerBindingRefusal(
|
|
236
|
+
binding,
|
|
237
|
+
currentRevision,
|
|
238
|
+
params.ref,
|
|
239
|
+
)
|
|
240
|
+
if (bindingRefusal !== null) {
|
|
241
|
+
const text = `spec_approve refused: ${bindingRefusal}`
|
|
242
|
+
return toolResult(
|
|
243
|
+
text,
|
|
244
|
+
{ ok: false, reason: text },
|
|
245
|
+
{ isError: true },
|
|
246
|
+
)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const result = await specApprove(params)
|
|
251
|
+
if (!result.ok) {
|
|
252
|
+
return toolResult(
|
|
253
|
+
result.text,
|
|
254
|
+
{ ok: false, reason: result.text },
|
|
255
|
+
{ isError: true },
|
|
256
|
+
)
|
|
257
|
+
}
|
|
258
|
+
// AIDEV-NOTE: PMR-CD46 — journal-after-success only (mirrors
|
|
259
|
+
// phase-complete): never recorded on refusal/failure paths, so a
|
|
260
|
+
// stored receipt always proves a committed approval.
|
|
261
|
+
await recordSpecReceipt(effectiveReceipts, params.ref)
|
|
262
|
+
return toolResult(result.text, { ok: true, reason: '' })
|
|
263
|
+
},
|
|
264
|
+
})
|
|
265
|
+
}
|
package/validate/args.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// AIDEV-NOTE: Pure /validate arg parsing — mirrors implement/args.ts minus the
|
|
2
|
+
// --skip-research flag (validate has no skip; the Jira evidence comment is
|
|
3
|
+
// mandatory in work mode).
|
|
4
|
+
|
|
5
|
+
import { parseRefKind } from '../flow/ref-kind.ts'
|
|
6
|
+
|
|
7
|
+
export type ValidateArgs =
|
|
8
|
+
| { kind: 'jira'; jiraId: string }
|
|
9
|
+
| { kind: 'aven'; ref: string }
|
|
10
|
+
| { kind: 'help' }
|
|
11
|
+
|
|
12
|
+
export function parseValidateArgs(raw: string): ValidateArgs {
|
|
13
|
+
const trimmed = raw.trim()
|
|
14
|
+
if (trimmed === '') return { kind: 'help' }
|
|
15
|
+
const parts = trimmed.split(/\s+/)
|
|
16
|
+
if (parts.length !== 1) return { kind: 'help' }
|
|
17
|
+
const parsed = parseRefKind(parts[0] ?? '')
|
|
18
|
+
if (parsed.kind === 'jira') {
|
|
19
|
+
return { kind: 'jira', jiraId: parsed.jiraId }
|
|
20
|
+
}
|
|
21
|
+
return { kind: 'aven', ref: parsed.ref }
|
|
22
|
+
}
|