@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,209 @@
|
|
|
1
|
+
// AIDEV-NOTE (PMR-45VS 2.1): row assembly — the WorkerRow shape and the
|
|
2
|
+
// attribution/coverage rules that build rows from the journal projections —
|
|
3
|
+
// split out of flow/cost-rows.ts so each cost-rows module stays small. This
|
|
4
|
+
// module is part of the cost-rows family and is held to the same rules; the
|
|
5
|
+
// load-bearing MODULE CONTRACT (node-only, daemon-reachable, byte-stable)
|
|
6
|
+
// lives in flow/cost-rows.ts and is not restated here.
|
|
7
|
+
|
|
8
|
+
import type { AssignmentRecord } from '@gtheys/pi-interactive-subagents/assignments'
|
|
9
|
+
import {
|
|
10
|
+
createUsageSummary,
|
|
11
|
+
summarizeEntriesUsage,
|
|
12
|
+
type UsageSummary,
|
|
13
|
+
} from '@gtheys/pi-interactive-subagents/usage'
|
|
14
|
+
import type { FlowPhase, FlowRunEvent } from '../run-state.ts'
|
|
15
|
+
import { agentRole, ORCHESTRATOR_ROLE } from './agent-role.ts'
|
|
16
|
+
import {
|
|
17
|
+
collectMainSessionFiles,
|
|
18
|
+
countToolCalls,
|
|
19
|
+
phaseWindows,
|
|
20
|
+
type SpawnNote,
|
|
21
|
+
type ToolCallCount,
|
|
22
|
+
} from './cost-rows-journal.ts'
|
|
23
|
+
|
|
24
|
+
/** Per-worker cost row. `sessionAvailable=false` means a coverage gap. */
|
|
25
|
+
export interface WorkerRow {
|
|
26
|
+
childId: string
|
|
27
|
+
name: string
|
|
28
|
+
/** groupable role (agent type, else name prefix); see flow/agent-role.ts */
|
|
29
|
+
role?: string
|
|
30
|
+
subtask: string | null
|
|
31
|
+
phase: FlowPhase | null
|
|
32
|
+
sessionFile: string | null
|
|
33
|
+
summary: UsageSummary
|
|
34
|
+
/** AIDEV-NOTE (PMR-NRH8): additive model metadata; empty sets preserve the byte-stable model-less body. */
|
|
35
|
+
models: ReadonlySet<string>
|
|
36
|
+
sessionAvailable: boolean
|
|
37
|
+
toolCalls: ToolCallCount[]
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Build one row per unique session file. Dedup rule: a file referenced by
|
|
42
|
+
* several notes (spawn then resume/reattach takeover) is attributed to the
|
|
43
|
+
* LAST note — cost follows whoever actually owns the work now. Notes with
|
|
44
|
+
* no resolvable session path become coverage-gap rows.
|
|
45
|
+
*/
|
|
46
|
+
export function buildWorkerRows(
|
|
47
|
+
notes: readonly SpawnNote[],
|
|
48
|
+
assignments: readonly AssignmentRecord[],
|
|
49
|
+
sessions: ReadonlyMap<string, readonly unknown[]>,
|
|
50
|
+
): WorkerRow[] {
|
|
51
|
+
const assignmentByChild = new Map<string, AssignmentRecord>()
|
|
52
|
+
for (const record of assignments) {
|
|
53
|
+
assignmentByChild.set(record.childId, record)
|
|
54
|
+
}
|
|
55
|
+
// Keyed by session file; null-session notes get synthetic unique keys.
|
|
56
|
+
const byFile = new Map<string, SpawnNote>()
|
|
57
|
+
let nullKeySeq = 0
|
|
58
|
+
for (const note of notes) {
|
|
59
|
+
let file = note.sessionFile
|
|
60
|
+
if (file === null) {
|
|
61
|
+
const record = assignmentByChild.get(note.childId)
|
|
62
|
+
if (record !== undefined && record.sessionFile.length > 0) {
|
|
63
|
+
file = record.sessionFile
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
let key: string
|
|
67
|
+
if (file === null) {
|
|
68
|
+
key = `\u0000null-${nullKeySeq}`
|
|
69
|
+
nullKeySeq += 1
|
|
70
|
+
} else {
|
|
71
|
+
key = file
|
|
72
|
+
}
|
|
73
|
+
byFile.set(key, { ...note, sessionFile: file })
|
|
74
|
+
}
|
|
75
|
+
const rows: WorkerRow[] = []
|
|
76
|
+
for (const note of byFile.values()) {
|
|
77
|
+
let subtask = note.subtask
|
|
78
|
+
if (subtask === null) {
|
|
79
|
+
const record = assignmentByChild.get(note.childId)
|
|
80
|
+
if (record !== undefined && record.subtask !== undefined) {
|
|
81
|
+
subtask = record.subtask
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
let summary = createUsageSummary()
|
|
85
|
+
let toolCalls: ToolCallCount[] = []
|
|
86
|
+
let sessionAvailable = false
|
|
87
|
+
if (note.sessionFile !== null) {
|
|
88
|
+
const entries = sessions.get(note.sessionFile)
|
|
89
|
+
if (entries !== undefined) {
|
|
90
|
+
summary = summarizeEntriesUsage(entries)
|
|
91
|
+
toolCalls = countToolCalls(entries)
|
|
92
|
+
sessionAvailable = true
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const record = assignmentByChild.get(note.childId)
|
|
96
|
+
rows.push({
|
|
97
|
+
childId: note.childId,
|
|
98
|
+
name: note.name,
|
|
99
|
+
role: agentRole(record?.agent, note.name),
|
|
100
|
+
subtask,
|
|
101
|
+
phase: note.phase,
|
|
102
|
+
sessionFile: note.sessionFile,
|
|
103
|
+
summary,
|
|
104
|
+
models: summary.models ?? new Set<string>(),
|
|
105
|
+
sessionAvailable,
|
|
106
|
+
toolCalls,
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
rows.sort((a, b) => {
|
|
110
|
+
if (a.phase !== b.phase) {
|
|
111
|
+
if (a.phase === null) return 1
|
|
112
|
+
if (b.phase === null) return -1
|
|
113
|
+
return a.phase.localeCompare(b.phase)
|
|
114
|
+
}
|
|
115
|
+
return a.name.localeCompare(b.name)
|
|
116
|
+
})
|
|
117
|
+
return rows
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function entryTimeMs(entry: unknown): number | null {
|
|
121
|
+
if (entry == null || typeof entry !== 'object') return null
|
|
122
|
+
const raw = (entry as Record<string, unknown>).timestamp
|
|
123
|
+
if (typeof raw !== 'string') return null
|
|
124
|
+
const ms = Date.parse(raw)
|
|
125
|
+
if (!Number.isFinite(ms)) return null
|
|
126
|
+
return ms
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Cost rows for the MAIN pi session(s): each session file's entries are split
|
|
131
|
+
* across the journal's phase windows by entry timestamp, one row per
|
|
132
|
+
* (session file, phase). Before this existed the rollup only counted spawned
|
|
133
|
+
* workers, so plan/implement (which run in the main session) had no cost at
|
|
134
|
+
* all. Rows are named "main" and carry no subtask. An unreadable session file
|
|
135
|
+
* yields ONE coverage-gap row (sessionAvailable=false), never an invented
|
|
136
|
+
* zero. Entries outside every window (chat before/after the flow) are
|
|
137
|
+
* ignored.
|
|
138
|
+
*/
|
|
139
|
+
export function buildMainRows(
|
|
140
|
+
events: readonly FlowRunEvent[],
|
|
141
|
+
sessions: ReadonlyMap<string, readonly unknown[]>,
|
|
142
|
+
): WorkerRow[] {
|
|
143
|
+
const files = collectMainSessionFiles(events)
|
|
144
|
+
const windows = phaseWindows(events)
|
|
145
|
+
const rows: WorkerRow[] = []
|
|
146
|
+
for (const file of files) {
|
|
147
|
+
const childId = `main-${sessionFileId(file)}`
|
|
148
|
+
const entries = sessions.get(file)
|
|
149
|
+
if (entries === undefined) {
|
|
150
|
+
rows.push({
|
|
151
|
+
childId,
|
|
152
|
+
name: 'main',
|
|
153
|
+
role: ORCHESTRATOR_ROLE,
|
|
154
|
+
subtask: null,
|
|
155
|
+
phase: null,
|
|
156
|
+
sessionFile: file,
|
|
157
|
+
summary: createUsageSummary(),
|
|
158
|
+
models: new Set<string>(),
|
|
159
|
+
sessionAvailable: false,
|
|
160
|
+
toolCalls: [],
|
|
161
|
+
})
|
|
162
|
+
continue
|
|
163
|
+
}
|
|
164
|
+
const byPhase = new Map<FlowPhase, unknown[]>()
|
|
165
|
+
for (const entry of entries) {
|
|
166
|
+
const ms = entryTimeMs(entry)
|
|
167
|
+
if (ms === null) continue
|
|
168
|
+
const window = windows.find((w) => ms >= w.startMs && ms < w.endMs)
|
|
169
|
+
if (window === undefined) continue
|
|
170
|
+
const list = byPhase.get(window.phase) ?? []
|
|
171
|
+
list.push(entry)
|
|
172
|
+
byPhase.set(window.phase, list)
|
|
173
|
+
}
|
|
174
|
+
for (const [phase, phaseEntries] of byPhase) {
|
|
175
|
+
const summary = summarizeEntriesUsage(phaseEntries)
|
|
176
|
+
if (!summary.sawUsage) continue
|
|
177
|
+
rows.push({
|
|
178
|
+
childId,
|
|
179
|
+
name: 'main',
|
|
180
|
+
role: ORCHESTRATOR_ROLE,
|
|
181
|
+
subtask: null,
|
|
182
|
+
phase,
|
|
183
|
+
sessionFile: file,
|
|
184
|
+
summary,
|
|
185
|
+
models: summary.models ?? new Set<string>(),
|
|
186
|
+
sessionAvailable: true,
|
|
187
|
+
toolCalls: countToolCalls(phaseEntries),
|
|
188
|
+
})
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
rows.sort((a, b) => {
|
|
192
|
+
if (a.phase !== b.phase) {
|
|
193
|
+
if (a.phase === null) return 1
|
|
194
|
+
if (b.phase === null) return -1
|
|
195
|
+
return a.phase.localeCompare(b.phase)
|
|
196
|
+
}
|
|
197
|
+
return a.childId.localeCompare(b.childId)
|
|
198
|
+
})
|
|
199
|
+
return rows
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Short stable id for a session file (basename without extension, last uuid part). */
|
|
203
|
+
function sessionFileId(file: string): string {
|
|
204
|
+
const base = file.slice(file.lastIndexOf('/') + 1).replace(/\.jsonl$/, '')
|
|
205
|
+
const underscore = base.lastIndexOf('_')
|
|
206
|
+
let id = base
|
|
207
|
+
if (underscore >= 0) id = base.slice(underscore + 1)
|
|
208
|
+
return id.slice(0, 8)
|
|
209
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
// AIDEV-NOTE (PMR-8MQH 1.2): node-only cost-row rollup for flow runs, moved
|
|
2
|
+
// out of flow/cost.ts so the daemon (server/daemon.ts) and flow/reconcile.ts
|
|
3
|
+
// can reach the rollup and the Pushgateway body builder. PMR-45VS split the
|
|
4
|
+
// single module into a family — this façade (rollup + re-exports) plus
|
|
5
|
+
// './cost-rows-journal.ts' (journal/session projections), './cost-rows-rows.ts'
|
|
6
|
+
// (row assembly), and './cost-rows-push.ts' (Prometheus exposition) — and the
|
|
7
|
+
// MODULE CONTRACT below covers the whole family. Three properties, all
|
|
8
|
+
// load-bearing:
|
|
9
|
+
// 1. NODE-ONLY. The set below is the SHARED façade allowlist — the union
|
|
10
|
+
// of edges the cost-rows family may draw on. cost-rows.ts and its
|
|
11
|
+
// siblings cost-rows-journal.ts, cost-rows-rows.ts, and
|
|
12
|
+
// cost-rows-push.ts may import ONLY node built-ins, '../run-state.ts'
|
|
13
|
+
// (types), './agent-role.ts', './cost-rows-journal.ts',
|
|
14
|
+
// './cost-rows-push.ts', './cost-rows-rows.ts', './run-health.ts',
|
|
15
|
+
// './push.ts', './reconcile-deps.ts', and the package subpaths
|
|
16
|
+
// '@gtheys/pi-interactive-subagents/usage' and '/assignments' — NEVER the
|
|
17
|
+
// package root, and never '@earendil-works/pi-coding-agent' (no pi
|
|
18
|
+
// extension runtime in the daemon process). The textual guard in
|
|
19
|
+
// test/cost-rows-node-only.test.ts enforces stricter per-root rules
|
|
20
|
+
// than this union: cost-rows.ts itself is checked against the full
|
|
21
|
+
// shared list, while each sibling is checked against its own exact,
|
|
22
|
+
// narrower ROOT_ALLOWLISTS entry derived from its actual imports
|
|
23
|
+
// (journal = run-state types only; rows = rollup deps; push =
|
|
24
|
+
// body-builder deps). That per-root narrowing is intentional — do not
|
|
25
|
+
// widen a sibling's entry to the shared list to silence a failure; a
|
|
26
|
+
// new edge here is a contract change needing its own justification.
|
|
27
|
+
// The daemon dependency contract is server/daemon.ts:8-19.
|
|
28
|
+
// 2. DAEMON-REACHABLE. Nothing in the family touches fs, env, timers, or
|
|
29
|
+
// the network. Every function is a pure projection of its arguments, so
|
|
30
|
+
// the daemon can rebuild identical rows/bodies from a journal dump
|
|
31
|
+
// without the pi runtime that produced them.
|
|
32
|
+
// AIDEV-NOTE (PMR-8MQH 1.2, RESOLVED): this property originally held for
|
|
33
|
+
// THIS file's own imports but not for its transitive closure: run-health
|
|
34
|
+
// imported labelString from './cost.ts', and cost.ts value-imports the
|
|
35
|
+
// package ROOT, so the real graph was cost-rows.ts -> run-health.ts ->
|
|
36
|
+
// cost.ts -> ROOT (proven by tracing `module.registerHooks` resolve
|
|
37
|
+
// parents while bare-node importing this file, not inferred). Decision
|
|
38
|
+
// (flow human, subtask 1.2): repoint run-health.ts at './cost-rows.ts',
|
|
39
|
+
// where labelString lives — since the PMR-45VS 3.1 split it is DECLARED
|
|
40
|
+
// in './cost-rows-push.ts' and re-exported through this façade, so the
|
|
41
|
+
// import site never moved — the ROOT drops out of the closure and the
|
|
42
|
+
// old cost.ts <-> run-health.ts cycle is gone (the remaining
|
|
43
|
+
// cost-rows <-> run-health seam is a pure function-declaration cycle,
|
|
44
|
+
// ESM-safe, both sides daemon-allowed). The closure guard in
|
|
45
|
+
// test/cost-rows-node-only.test.ts locks it so a re-introduced
|
|
46
|
+
// './cost.ts' or './cost-command.ts' edge fails in CI.
|
|
47
|
+
// 3. BYTE-STABLE BODY (ISC-7 of PMR-V36Y). buildPushBody's output is a
|
|
48
|
+
// consumed Prometheus exposition: the homelab dashboards key on the exact
|
|
49
|
+
// metric names, label sets, and line ORDER. Changing the body builder is
|
|
50
|
+
// a dashboard-breaking change, so since the PMR-45VS 3.1 split its home
|
|
51
|
+
// is flow/cost-rows-push.ts — character-for-character the code that
|
|
52
|
+
// flow/cost.ts used to hold — re-exported through this façade;
|
|
53
|
+
// flow/cost.ts re-exports the family so every existing importer keeps
|
|
54
|
+
// resolving the same functions.
|
|
55
|
+
//
|
|
56
|
+
// AIDEV-NOTE (PMR-8MQH 1.3): computeCostRollup + the CostRollup type moved
|
|
57
|
+
// here from flow/cost-command.ts so the daemon can reach the rollup too, and
|
|
58
|
+
// cost-command.ts re-exports them (no caller changed). Its dependencies are
|
|
59
|
+
// narrowed to CostRollupDeps (journal + assignments + session files) instead
|
|
60
|
+
// of Pick<FlowCostDeps, ...> — the push member stays session-side.
|
|
61
|
+
//
|
|
62
|
+
// AIDEV-NOTE (PMR-EA8X): offline ground-truth cost rollup for flow runs.
|
|
63
|
+
// The session jsonl files stay the authority — this module family only
|
|
64
|
+
// aggregates what Pi already recorded. COVERAGE DISCIPLINE (same rule as
|
|
65
|
+
// usage.ts): when a session's usage is unavailable (unreadable file, no
|
|
66
|
+
// usage blocks, no resolvable session path) the row carries a coverage flag,
|
|
67
|
+
// never an invented zero. Attribution rule: cost follows the assignment
|
|
68
|
+
// recorded at spawn time (subtask from the note, else the durable assignment
|
|
69
|
+
// record); a takeover (resume/reattach) re-attributes the session to whoever
|
|
70
|
+
// now owns the work, matching the journal's reassignment notes. The
|
|
71
|
+
// attribution/coverage mechanics themselves live in './cost-rows-rows.ts'.
|
|
72
|
+
|
|
73
|
+
import type { AssignmentRecord } from '@gtheys/pi-interactive-subagents/assignments'
|
|
74
|
+
import type { FlowRunEvent } from '../run-state.ts'
|
|
75
|
+
import { runTracking } from '../run-state.ts'
|
|
76
|
+
import type { PhaseDuration, PhaseStepSummary } from './cost-rows-journal.ts'
|
|
77
|
+
import {
|
|
78
|
+
collectMainSessionFiles,
|
|
79
|
+
collectSpawnNotes,
|
|
80
|
+
parseSessionEntries,
|
|
81
|
+
phaseDurations,
|
|
82
|
+
summarizeStepOutputs,
|
|
83
|
+
} from './cost-rows-journal.ts'
|
|
84
|
+
import type { WorkerRow } from './cost-rows-rows.ts'
|
|
85
|
+
import { buildMainRows, buildWorkerRows } from './cost-rows-rows.ts'
|
|
86
|
+
|
|
87
|
+
// AIDEV-NOTE (PMR-FQMW 1.1): the journal/session projections moved to
|
|
88
|
+
// './cost-rows-journal.ts' (character-for-character); this façade
|
|
89
|
+
// re-export keeps every existing importer of './cost-rows.ts' resolving
|
|
90
|
+
// the same symbols.
|
|
91
|
+
export {
|
|
92
|
+
collectMainSessionFiles,
|
|
93
|
+
collectSpawnNotes,
|
|
94
|
+
countToolCalls,
|
|
95
|
+
type PhaseDuration,
|
|
96
|
+
type PhaseStepSummary,
|
|
97
|
+
type PhaseWindow,
|
|
98
|
+
parseSessionEntries,
|
|
99
|
+
parseSpawnNote,
|
|
100
|
+
phaseDurations,
|
|
101
|
+
phaseWindows,
|
|
102
|
+
type SpawnNote,
|
|
103
|
+
summarizeStepOutputs,
|
|
104
|
+
type ToolCallCount,
|
|
105
|
+
} from './cost-rows-journal.ts'
|
|
106
|
+
// AIDEV-NOTE (PMR-45VS 3.1): the Prometheus exposition family (the label
|
|
107
|
+
// helpers and the byte-stable Pushgateway body builder) moved to
|
|
108
|
+
// './cost-rows-push.ts' (character-for-character); this façade re-export
|
|
109
|
+
// keeps every existing importer of './cost-rows.ts' resolving the same
|
|
110
|
+
// symbols — in particular run-health.ts and state-metrics.ts keep importing
|
|
111
|
+
// labelString from here, so the cycle
|
|
112
|
+
// cost-rows.ts → cost-rows-push.ts → run-health.ts → cost-rows.ts stays
|
|
113
|
+
// function-declaration-only and ESM-safe.
|
|
114
|
+
export {
|
|
115
|
+
buildPushBody,
|
|
116
|
+
escapeLabelValue,
|
|
117
|
+
labelString,
|
|
118
|
+
} from './cost-rows-push.ts'
|
|
119
|
+
// AIDEV-NOTE (PMR-45VS 2.1): the row-assembly family (the WorkerRow shape and
|
|
120
|
+
// the worker/main-session row builders) moved to './cost-rows-rows.ts'
|
|
121
|
+
// (character-for-character); this façade re-export keeps every existing
|
|
122
|
+
// importer of './cost-rows.ts' resolving the same symbols.
|
|
123
|
+
export {
|
|
124
|
+
buildMainRows,
|
|
125
|
+
buildWorkerRows,
|
|
126
|
+
type WorkerRow,
|
|
127
|
+
} from './cost-rows-rows.ts'
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* What computeCostRollup reads: the run journal, the durable assignment
|
|
131
|
+
* records, and the raw session jsonl bodies. All reads — the push transport is
|
|
132
|
+
* session-side (flow/cost-command.ts's FlowCostDeps adds it), which is why the
|
|
133
|
+
* rollup takes this narrower interface instead of FlowCostDeps itself.
|
|
134
|
+
*/
|
|
135
|
+
export interface CostRollupDeps {
|
|
136
|
+
/** Journal events for a ref; null when no journal exists. */
|
|
137
|
+
readRunEvents: (ref: string) => Promise<FlowRunEvent[] | null>
|
|
138
|
+
/** Durable assignment records (subagents data dir). */
|
|
139
|
+
listAssignmentRecords: () => readonly AssignmentRecord[]
|
|
140
|
+
/** Raw session jsonl body, or null when unreadable (coverage gap). */
|
|
141
|
+
readSessionFile: (file: string) => string | null
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export type CostRollup =
|
|
145
|
+
| { kind: 'no-journal' }
|
|
146
|
+
| { kind: 'empty' }
|
|
147
|
+
| {
|
|
148
|
+
kind: 'ok'
|
|
149
|
+
rows: WorkerRow[]
|
|
150
|
+
durations: PhaseDuration[]
|
|
151
|
+
/** Per-phase step-output submission counts (advisory evidence). */
|
|
152
|
+
steps?: PhaseStepSummary[]
|
|
153
|
+
/** ref the run is tracked by (Jira key in work mode); the metric `ref` label */
|
|
154
|
+
trackRef: string
|
|
155
|
+
mode: 'work' | 'personal'
|
|
156
|
+
/**
|
|
157
|
+
* AIDEV-NOTE: the raw journal events the rollup was computed from —
|
|
158
|
+
* the push call sites forward them to buildPushBody so the run-health
|
|
159
|
+
* metrics ride the same push (optional for back-compat with rollups
|
|
160
|
+
* built by older code or tests).
|
|
161
|
+
*/
|
|
162
|
+
events?: readonly FlowRunEvent[]
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Journal + session files -> cost rows. Shared by `/flow-cost` and the
|
|
167
|
+
* automatic push at run end, so both always agree. 'empty' = the journal has
|
|
168
|
+
* neither worker spawn notes nor a main-session record (pre-attribution run).
|
|
169
|
+
*/
|
|
170
|
+
export async function computeCostRollup(
|
|
171
|
+
ref: string,
|
|
172
|
+
deps: CostRollupDeps,
|
|
173
|
+
): Promise<CostRollup> {
|
|
174
|
+
const events = await deps.readRunEvents(ref)
|
|
175
|
+
if (events === null) return { kind: 'no-journal' }
|
|
176
|
+
const notes = collectSpawnNotes(events)
|
|
177
|
+
const mainFiles = collectMainSessionFiles(events)
|
|
178
|
+
if (notes.length === 0 && mainFiles.length === 0) return { kind: 'empty' }
|
|
179
|
+
const assignments = deps.listAssignmentRecords()
|
|
180
|
+
// read every distinct session file once (coverage gaps become flags)
|
|
181
|
+
const wanted = new Set<string>()
|
|
182
|
+
for (const note of notes) {
|
|
183
|
+
if (note.sessionFile !== null) wanted.add(note.sessionFile)
|
|
184
|
+
}
|
|
185
|
+
for (const file of mainFiles) wanted.add(file)
|
|
186
|
+
const byChild = new Map<string, AssignmentRecord>()
|
|
187
|
+
for (const record of assignments) {
|
|
188
|
+
byChild.set(record.childId, record)
|
|
189
|
+
}
|
|
190
|
+
for (const note of notes) {
|
|
191
|
+
if (note.sessionFile !== null) continue
|
|
192
|
+
const record = byChild.get(note.childId)
|
|
193
|
+
if (record !== undefined && record.sessionFile.length > 0) {
|
|
194
|
+
wanted.add(record.sessionFile)
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const sessions = new Map<string, readonly unknown[]>()
|
|
198
|
+
for (const file of wanted) {
|
|
199
|
+
const raw = deps.readSessionFile(file)
|
|
200
|
+
if (raw === null) continue
|
|
201
|
+
sessions.set(file, parseSessionEntries(raw))
|
|
202
|
+
}
|
|
203
|
+
const rows = [
|
|
204
|
+
...buildMainRows(events, sessions),
|
|
205
|
+
...buildWorkerRows(notes, assignments, sessions),
|
|
206
|
+
]
|
|
207
|
+
// AIDEV-NOTE: work/personal separation — the pushed `ref` label (and the
|
|
208
|
+
// Pushgateway group) is the run's TRACKING ref (Jira key in work mode),
|
|
209
|
+
// from the last run-start event; runs journaled before this existed fall
|
|
210
|
+
// back to the aven ref and personal mode. The derivation itself lives in
|
|
211
|
+
// run-state.ts's runTracking (PMR-MSDJ 1.2) so pushes and the PMR-05MQ
|
|
212
|
+
// tombstone group URL cannot drift apart.
|
|
213
|
+
const { trackRef, mode } = runTracking(events, ref)
|
|
214
|
+
// AIDEV-NOTE (PMR-C998): steps are advisory evidence from journal
|
|
215
|
+
// 'step-output' submissions; optional on the rollup for back-compat and
|
|
216
|
+
// omitted (not empty) so report consumers skip the section cleanly.
|
|
217
|
+
const steps = summarizeStepOutputs(events)
|
|
218
|
+
const okRollup: CostRollup & { steps?: PhaseStepSummary[] } = {
|
|
219
|
+
kind: 'ok' as const,
|
|
220
|
+
rows,
|
|
221
|
+
durations: phaseDurations(events),
|
|
222
|
+
trackRef,
|
|
223
|
+
events,
|
|
224
|
+
mode,
|
|
225
|
+
}
|
|
226
|
+
if (steps.length > 0) okRollup.steps = steps
|
|
227
|
+
return okRollup
|
|
228
|
+
}
|
package/flow/cost.ts
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// AIDEV-NOTE (PMR-EA8X): the human cost report for flow runs. The node-only
|
|
2
|
+
// rollup and the Pushgateway body builder moved to flow/cost-rows.ts in
|
|
3
|
+
// PMR-8MQH 1.2 (daemon reachability); everything moved is re-exported below,
|
|
4
|
+
// so existing importers (index.ts, flow/cost-command.ts, flow/cost-autopush.ts,
|
|
5
|
+
// flow-diagram/*, adhoc/tracker.ts, test/*) resolve the same symbols unchanged.
|
|
6
|
+
// What stays HERE is the session-side report path: it is the only place that
|
|
7
|
+
// imports the package ROOT for `totalTokens`, which is why the daemon contract
|
|
8
|
+
// forbids reaching this file (server/daemon.ts:15-18). See cost-rows.ts for
|
|
9
|
+
// the node-only contract — the moved half does not import back here (its
|
|
10
|
+
// run-health seam takes `labelString` from cost-rows.ts), so nothing in the
|
|
11
|
+
// daemon's closure reaches this file.
|
|
12
|
+
|
|
13
|
+
import { totalTokens } from '@gtheys/pi-interactive-subagents'
|
|
14
|
+
import type { PhaseDuration, PhaseStepSummary, WorkerRow } from './cost-rows.ts'
|
|
15
|
+
|
|
16
|
+
function groupThousands(value: number): string {
|
|
17
|
+
const rounded = Math.round(value)
|
|
18
|
+
const digits = `${Math.abs(rounded)}`
|
|
19
|
+
let grouped = ''
|
|
20
|
+
for (let i = 0; i < digits.length; i += 1) {
|
|
21
|
+
if (i > 0 && (digits.length - i) % 3 === 0) grouped += ','
|
|
22
|
+
grouped += digits[i]
|
|
23
|
+
}
|
|
24
|
+
let sign = ''
|
|
25
|
+
if (rounded < 0) sign = '-'
|
|
26
|
+
return `${sign}${grouped}`
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function padCell(value: string, width: number): string {
|
|
30
|
+
let padded = value
|
|
31
|
+
while (padded.length < width) padded += ' '
|
|
32
|
+
return padded
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Render the human report: per-worker table, per-phase subtotals, run
|
|
37
|
+
* total, and coverage-gap flags. Pure string building.
|
|
38
|
+
*/
|
|
39
|
+
export function formatCostReport(
|
|
40
|
+
ref: string,
|
|
41
|
+
rows: readonly WorkerRow[],
|
|
42
|
+
durations: readonly PhaseDuration[],
|
|
43
|
+
steps: readonly PhaseStepSummary[] = [],
|
|
44
|
+
): string {
|
|
45
|
+
const header = ['worker', 'subtask', 'phase', 'tokens', 'cost', 'coverage']
|
|
46
|
+
const table: string[][] = []
|
|
47
|
+
for (const row of rows) {
|
|
48
|
+
let subtaskCell = '-'
|
|
49
|
+
if (row.subtask !== null) subtaskCell = row.subtask
|
|
50
|
+
let phaseCell = '-'
|
|
51
|
+
if (row.phase !== null) phaseCell = row.phase
|
|
52
|
+
let tokensCell = '-'
|
|
53
|
+
let costCell = '-'
|
|
54
|
+
if (row.sessionAvailable) {
|
|
55
|
+
tokensCell = groupThousands(totalTokens(row.summary.totals))
|
|
56
|
+
costCell = `$${row.summary.totals.cost.toFixed(4)}`
|
|
57
|
+
}
|
|
58
|
+
let coverage = 'ok'
|
|
59
|
+
if (!row.sessionAvailable) coverage = 'NO SESSION'
|
|
60
|
+
else if (!row.summary.sawUsage) coverage = 'NO USAGE DATA'
|
|
61
|
+
table.push([
|
|
62
|
+
row.name,
|
|
63
|
+
subtaskCell,
|
|
64
|
+
phaseCell,
|
|
65
|
+
tokensCell,
|
|
66
|
+
costCell,
|
|
67
|
+
coverage,
|
|
68
|
+
])
|
|
69
|
+
}
|
|
70
|
+
const widths = header.map((cell, index) => {
|
|
71
|
+
let width = cell.length
|
|
72
|
+
for (const row of table) {
|
|
73
|
+
width = Math.max(width, row[index].length)
|
|
74
|
+
}
|
|
75
|
+
return width
|
|
76
|
+
})
|
|
77
|
+
const lines: string[] = []
|
|
78
|
+
lines.push(`flow-cost ${ref} — ${rows.length} worker session(s)`)
|
|
79
|
+
lines.push(
|
|
80
|
+
header
|
|
81
|
+
.map((cell, i) => padCell(cell, widths[i]))
|
|
82
|
+
.join(' ')
|
|
83
|
+
.trimEnd(),
|
|
84
|
+
)
|
|
85
|
+
for (const row of table) {
|
|
86
|
+
lines.push(
|
|
87
|
+
row
|
|
88
|
+
.map((cell, i) => padCell(cell, widths[i]))
|
|
89
|
+
.join(' ')
|
|
90
|
+
.trimEnd(),
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
// run total counts only rows that actually carried usage — never zeros
|
|
94
|
+
let totalTokensSum = 0
|
|
95
|
+
let totalCost = 0
|
|
96
|
+
let coveredRows = 0
|
|
97
|
+
for (const row of rows) {
|
|
98
|
+
if (row.summary.sawUsage) {
|
|
99
|
+
totalTokensSum += totalTokens(row.summary.totals)
|
|
100
|
+
totalCost += row.summary.totals.cost
|
|
101
|
+
coveredRows += 1
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
let coverageNote = 'no session reported usage'
|
|
105
|
+
if (coveredRows > 0) {
|
|
106
|
+
coverageNote = `${coveredRows}/${rows.length} session(s) reported usage`
|
|
107
|
+
}
|
|
108
|
+
lines.push(
|
|
109
|
+
`TOTAL ${groupThousands(totalTokensSum)} tokens $${totalCost.toFixed(4)} (${coverageNote})`,
|
|
110
|
+
)
|
|
111
|
+
if (durations.length > 0) {
|
|
112
|
+
lines.push('phase durations (journal wall-clock):')
|
|
113
|
+
for (const duration of durations) {
|
|
114
|
+
lines.push(` ${duration.phase}: ${duration.seconds.toFixed(0)}s`)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (steps.length > 0) {
|
|
118
|
+
lines.push('step outputs (advisory, never blocking):')
|
|
119
|
+
for (const step of steps) {
|
|
120
|
+
lines.push(
|
|
121
|
+
` ${step.phase}: ${step.total} step output(s) (${step.ok} ok, ${step.failed} failed)`,
|
|
122
|
+
)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return lines.join('\n')
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// AIDEV-NOTE (PMR-8MQH 1.2): the row/body half of the rollup + push-body
|
|
129
|
+
// code lives in the flow/cost-rows.ts module family (the cost-rows.ts facade
|
|
130
|
+
// plus its cost-rows-* submodules since PMR-45VS — node-only by their own
|
|
131
|
+
// import lists, see the facade header for the family import contract; its
|
|
132
|
+
// closure-edge AIDEV-QUESTION is RESOLVED and recorded there: run-health.ts
|
|
133
|
+
// now imports `labelString` from cost-rows.ts, so no session-side package-ROOT
|
|
134
|
+
// edge remains in the daemon's closure). Re-exported here so every existing
|
|
135
|
+
// importer keeps working unchanged; nothing was edited on the importing side.
|
|
136
|
+
// AIDEV-NOTE (PMR-8MQH 1.3): `computeCostRollup` + `CostRollup` /
|
|
137
|
+
// `CostRollupDeps` ALSO live in flow/cost-rows.ts (moved out of
|
|
138
|
+
// flow/cost-command.ts), but they are deliberately re-exported from THERE,
|
|
139
|
+
// not from this file — `flow/cost-autopush.ts` keeps its `./cost-command.ts`
|
|
140
|
+
// import, and this file stays off the daemon's allowlist because of the ROOT
|
|
141
|
+
// `totalTokens` import above.
|
|
142
|
+
export {
|
|
143
|
+
buildMainRows,
|
|
144
|
+
buildPushBody,
|
|
145
|
+
buildWorkerRows,
|
|
146
|
+
collectMainSessionFiles,
|
|
147
|
+
collectSpawnNotes,
|
|
148
|
+
countToolCalls,
|
|
149
|
+
escapeLabelValue,
|
|
150
|
+
labelString,
|
|
151
|
+
type PhaseDuration,
|
|
152
|
+
type PhaseStepSummary,
|
|
153
|
+
type PhaseWindow,
|
|
154
|
+
parseSessionEntries,
|
|
155
|
+
parseSpawnNote,
|
|
156
|
+
phaseDurations,
|
|
157
|
+
phaseWindows,
|
|
158
|
+
type SpawnNote,
|
|
159
|
+
summarizeStepOutputs,
|
|
160
|
+
type ToolCallCount,
|
|
161
|
+
type WorkerRow,
|
|
162
|
+
} from './cost-rows.ts'
|
|
163
|
+
|
|
164
|
+
// AIDEV-NOTE (PMR-XR43 1.1): the Pushgateway transport lives in flow/push.ts
|
|
165
|
+
// (node-only, daemon-reachable — see its header for the import contract). It is
|
|
166
|
+
// re-exported here so existing importers (index.ts, flow/cost-command.ts,
|
|
167
|
+
// test/cost.test.ts, test/work-mode-tracking.test.ts) keep working unchanged.
|
|
168
|
+
export {
|
|
169
|
+
groupSuffix,
|
|
170
|
+
type PushFetch,
|
|
171
|
+
type PushResult,
|
|
172
|
+
pushToGateway,
|
|
173
|
+
} from './push.ts'
|