@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
package/flow/push.ts
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
// AIDEV-NOTE (PMR-XR43 1.1): node-only Pushgateway plumbing, moved out of
|
|
2
|
+
// flow/cost.ts so the daemon (server/daemon.ts) and flow/reconcile.ts can reach
|
|
3
|
+
// it. This file must import ONLY node built-ins — no @earendil-works/
|
|
4
|
+
// pi-coding-agent, no @gtheys/pi-interactive-subagents (the daemon header
|
|
5
|
+
// contract, server/daemon.ts:1-11). cost.ts re-exports these symbols, so the
|
|
6
|
+
// extension-side imports (index.ts, flow/cost-command.ts, test/cost.test.ts)
|
|
7
|
+
// are unchanged.
|
|
8
|
+
//
|
|
9
|
+
// Why `fetchGroupBody` reads the FULL dump instead of the group:
|
|
10
|
+
// AIDEV-NOTE: a per-group GET (`GET {base}/metrics/job/pi-flow/ref/<ref>`) is
|
|
11
|
+
// **405 Method Not Allowed** on this gateway (verified live 2026-11-24) —
|
|
12
|
+
// Pushgateway only serves stored groups through the single exposition dump at
|
|
13
|
+
// `GET {base}/metrics`. So reading one group back means fetching the whole
|
|
14
|
+
// dump and filtering lines by their label set. Two dump quirks decide the
|
|
15
|
+
// filter, both verified against the live gateway:
|
|
16
|
+
// (a) the gateway injects `instance=""` into every exposed line; that label
|
|
17
|
+
// pair is stripped before a body is re-POSTed, otherwise the re-POSTed
|
|
18
|
+
// series gets a different identity;
|
|
19
|
+
// (b) the dump covers ALL groups behind `# HELP`/`# TYPE` family comments —
|
|
20
|
+
// every `#` line is dropped (`buildPushBody` never emits comments, so
|
|
21
|
+
// keeping them would change the group).
|
|
22
|
+
// Grouping labels injected from the URL path (`job`, `ref`, and `mode` for
|
|
23
|
+
// work pushes) come back inside the label set, which is what the filter keys
|
|
24
|
+
// on — but the label set alone is NOT enough. AIDEV-NOTE (PMR-WBC2): the
|
|
25
|
+
// gateway's own bookkeeping metrics (`push_time_seconds` /
|
|
26
|
+
// `push_failure_time_seconds`) carry the SAME group labels, and re-POSTing
|
|
27
|
+
// them is fatal: the `#`-line drop strips their `# TYPE … gauge` family
|
|
28
|
+
// comments, so the body arrives with those metrics UNTYPED while the gateway
|
|
29
|
+
// stores them as gauge — the WHOLE push 400s ("… is not a GAUGE"). That made
|
|
30
|
+
// every tombstone re-POST fail. They are not ours to send: the gateway
|
|
31
|
+
// regenerates them on every accepted POST (observed live). The filter
|
|
32
|
+
// therefore keeps only lines whose metric name starts with `pi_flow`.
|
|
33
|
+
//
|
|
34
|
+
// AIDEV-NOTE (PMR-WBC2, verified live 2026-11-24 against the homelab
|
|
35
|
+
// gateway): this deployment MERGES on write — a series omitted from an
|
|
36
|
+
// accepted POST KEEPS being served (probe: posted {A,B}, re-posted {A} only,
|
|
37
|
+
// B survived; same mechanism is why tombstoned refs still serve
|
|
38
|
+
// `pi_flow_run_halt_reason` — it does NOT age out). That contradicts the
|
|
39
|
+
// official Pushgateway Replace semantics assumed by the P2-5 fail-closed rule
|
|
40
|
+
// below and by plan PMR-MSDJ Risk #1. The fail-closed rule and the
|
|
41
|
+
// full-body round-trip STAY: they are cheap, correct under official
|
|
42
|
+
// semantics, and this gateway's merge behavior is an implementation detail
|
|
43
|
+
// that could change with any redeploy. Consequence for tombstones: dropping
|
|
44
|
+
// halt_reason from the body does not remove the stored series here — no
|
|
45
|
+
// alert keys on halt_reason, so alerting is unaffected; dashboards may show
|
|
46
|
+
// a stale halt reason until the series is overwritten.
|
|
47
|
+
// AIDEV-NOTE (PMR-ZV9Y 7.2): `pi_flow_run_halt_reason` is RETIRED — it is no
|
|
48
|
+
// longer rendered by flow/run-health.ts, so the tombstone engine no longer
|
|
49
|
+
// drops it (the only drop it ever made; see flow/reconcile.ts). The
|
|
50
|
+
// merge-on-write behaviour this note documents is unchanged and still governs
|
|
51
|
+
// every v2 line: a re-POSTed body that OMITS a stored `pi_flow*` series leaves
|
|
52
|
+
// that stale series served. The TYPE-line failure mode described above (a
|
|
53
|
+
// typed first push plus an untyped tombstone re-POST 400s the whole group) is
|
|
54
|
+
// documented here for any future typed family, even though the v1 metric that
|
|
55
|
+
// first exposed it is gone.
|
|
56
|
+
|
|
57
|
+
export interface PushResult {
|
|
58
|
+
ok: boolean
|
|
59
|
+
/** Present only when ok=false — the caller shows a warning, never fails. */
|
|
60
|
+
error?: string
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export type PushFetch = (
|
|
64
|
+
url: string,
|
|
65
|
+
init: { method: string; headers: Record<string, string>; body: string },
|
|
66
|
+
) => Promise<{
|
|
67
|
+
status: number
|
|
68
|
+
statusText: string
|
|
69
|
+
/** PMR-WBC2: read on non-2xx only — the gateway explains every 4xx in the
|
|
70
|
+
* body. Optional so minimal test fakes keep working. */
|
|
71
|
+
text?: () => Promise<string>
|
|
72
|
+
}>
|
|
73
|
+
|
|
74
|
+
/** Fetch shape for reading the exposition back. `globalThis.fetch` satisfies
|
|
75
|
+
* it (only `status`/`statusText`/`text()` are used). */
|
|
76
|
+
export type GroupFetch = (
|
|
77
|
+
url: string,
|
|
78
|
+
init: { method: string; headers: Record<string, string> },
|
|
79
|
+
) => Promise<{
|
|
80
|
+
status: number
|
|
81
|
+
statusText: string
|
|
82
|
+
text: () => Promise<string>
|
|
83
|
+
}>
|
|
84
|
+
|
|
85
|
+
export type GroupBodyResult =
|
|
86
|
+
| { ok: true; body: string }
|
|
87
|
+
| { ok: false; error: string }
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Extra Pushgateway grouping segment. AIDEV-NOTE: only WORK mode adds a
|
|
91
|
+
* `mode` grouping label — personal pushes keep their historical group
|
|
92
|
+
* (`…/ref/<ref>`, no mode label) so existing series are replaced in place, not
|
|
93
|
+
* duplicated. Dashboards treat a missing mode label as personal.
|
|
94
|
+
*/
|
|
95
|
+
export function groupSuffix(mode: 'work' | 'personal' | undefined): string {
|
|
96
|
+
if (mode === 'work') return '/mode/work'
|
|
97
|
+
return ''
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Single-sourced Pushgroup URL builder: the grouping keys put ref (and, for
|
|
102
|
+
* work mode, mode) in the URL path so separate runs keep separate metric
|
|
103
|
+
* groups. Used for both the POST (push) and the reconcile-side re-POST.
|
|
104
|
+
*/
|
|
105
|
+
export function groupUrl(
|
|
106
|
+
base: string,
|
|
107
|
+
ref: string,
|
|
108
|
+
mode?: 'work' | 'personal',
|
|
109
|
+
): string {
|
|
110
|
+
const root = base.replace(/\/+$/, '')
|
|
111
|
+
return `${root}/metrics/job/pi-flow/ref/${encodeURIComponent(ref)}${groupSuffix(mode)}`
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Push the exposition body to a Pushgateway. Grouping keys put ref in the
|
|
116
|
+
* URL path so separate runs keep separate metric groups; the bearer token
|
|
117
|
+
* (when configured) rides the Authorization header. Failures return
|
|
118
|
+
* {ok:false} — /flow-cost treats them as warnings, never fatal.
|
|
119
|
+
*/
|
|
120
|
+
export async function pushToGateway(
|
|
121
|
+
url: string,
|
|
122
|
+
ref: string,
|
|
123
|
+
body: string,
|
|
124
|
+
fetchImpl: PushFetch,
|
|
125
|
+
token?: string,
|
|
126
|
+
mode?: 'work' | 'personal',
|
|
127
|
+
): Promise<PushResult> {
|
|
128
|
+
const headers: Record<string, string> = {
|
|
129
|
+
'content-type': 'text/plain',
|
|
130
|
+
}
|
|
131
|
+
if (token !== undefined && token.length > 0) {
|
|
132
|
+
headers.authorization = `Bearer ${token}`
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
const response = await fetchImpl(groupUrl(trimBase(url), ref, mode), {
|
|
136
|
+
method: 'POST',
|
|
137
|
+
headers,
|
|
138
|
+
body,
|
|
139
|
+
})
|
|
140
|
+
if (response.status < 200 || response.status >= 300) {
|
|
141
|
+
const reason = await errorSnippet(response)
|
|
142
|
+
return {
|
|
143
|
+
ok: false,
|
|
144
|
+
error: `pushgateway responded ${response.status} ${response.statusText}${reason}`,
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return { ok: true }
|
|
148
|
+
} catch (err) {
|
|
149
|
+
const message = err instanceof Error ? err.message : `${err}`
|
|
150
|
+
return { ok: false, error: message }
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** PMR-WBC2: Pushgateway always explains a 400 in the response body —
|
|
155
|
+
* throwing it away made the tombstone 400s undiagnosable without a manual
|
|
156
|
+
* repro. Keep a bounded, whitespace-flattened snippet in the error instead.
|
|
157
|
+
* Never fails: an unreadable body degrades to the bare status line. */
|
|
158
|
+
const ERROR_SNIPPET_MAX_CHARS = 300
|
|
159
|
+
|
|
160
|
+
async function errorSnippet(response: {
|
|
161
|
+
text?: () => Promise<string>
|
|
162
|
+
}): Promise<string> {
|
|
163
|
+
if (typeof response.text !== 'function') return ''
|
|
164
|
+
try {
|
|
165
|
+
const body = (await response.text()).trim().replace(/\s+/g, ' ')
|
|
166
|
+
if (body.length === 0) return ''
|
|
167
|
+
if (body.length > ERROR_SNIPPET_MAX_CHARS) {
|
|
168
|
+
return `: ${body.slice(0, ERROR_SNIPPET_MAX_CHARS)}…`
|
|
169
|
+
}
|
|
170
|
+
return `: ${body}`
|
|
171
|
+
} catch {
|
|
172
|
+
return ''
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function trimBase(url: string): string {
|
|
177
|
+
return url.replace(/\/+$/, '')
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Delete one stored group (PMR-2EGV). The homelab gateway MERGES on write
|
|
182
|
+
* (PMR-WBC2 note at the top of this file), so a POST that omits a series can
|
|
183
|
+
* never remove it — the terminal purge (done) and the tombstone (stale)
|
|
184
|
+
* DELETE the group first, then re-POST the surviving lines. Same posture as
|
|
185
|
+
* {@link pushToGateway}: the bearer token (when configured) rides the
|
|
186
|
+
* Authorization header, non-2xx returns {ok:false} with the bounded error
|
|
187
|
+
* snippet, and it never throws — the caller decides whether a failed DELETE
|
|
188
|
+
* skips the re-POST (it must: a re-POST after a failed DELETE would leave the
|
|
189
|
+
* stale series served).
|
|
190
|
+
*/
|
|
191
|
+
export async function deleteGroup(
|
|
192
|
+
url: string,
|
|
193
|
+
ref: string,
|
|
194
|
+
fetchImpl: PushFetch,
|
|
195
|
+
token?: string,
|
|
196
|
+
mode?: 'work' | 'personal',
|
|
197
|
+
): Promise<PushResult> {
|
|
198
|
+
const headers: Record<string, string> = {}
|
|
199
|
+
if (token !== undefined && token.length > 0) {
|
|
200
|
+
headers.authorization = `Bearer ${token}`
|
|
201
|
+
}
|
|
202
|
+
try {
|
|
203
|
+
const response = await fetchImpl(groupUrl(trimBase(url), ref, mode), {
|
|
204
|
+
method: 'DELETE',
|
|
205
|
+
headers,
|
|
206
|
+
body: '',
|
|
207
|
+
})
|
|
208
|
+
if (response.status < 200 || response.status >= 300) {
|
|
209
|
+
const reason = await errorSnippet(response)
|
|
210
|
+
return {
|
|
211
|
+
ok: false,
|
|
212
|
+
error: `pushgateway DELETE responded ${response.status} ${response.statusText}${reason}`,
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return { ok: true }
|
|
216
|
+
} catch (err) {
|
|
217
|
+
const message = err instanceof Error ? err.message : `${err}`
|
|
218
|
+
return { ok: false, error: message }
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Read one stored group back: GET the full exposition dump and keep only the
|
|
224
|
+
* lines whose label set belongs to this group — `job="pi-flow"`,
|
|
225
|
+
* `ref=<ref>`, and `mode="work"` present iff `mode === 'work'` (matching
|
|
226
|
+
* {@link groupSuffix} semantics: a personal group is a group with NO mode
|
|
227
|
+
* label). The injected `instance=""` pair is stripped and every `#` comment
|
|
228
|
+
* line dropped, so the result can be re-POSTed to {@link groupUrl} unchanged
|
|
229
|
+
* and replace the group in place. Never throws: a non-2xx response or a
|
|
230
|
+
* network error returns {ok:false}. A group with no lines returns
|
|
231
|
+
* {ok:true, body:""} — the caller treats an empty body as "group gone".
|
|
232
|
+
*
|
|
233
|
+
* AIDEV-NOTE (PMR-MSDJ fix round, P2-5): an unparseable line that could be
|
|
234
|
+
* one of OURS also returns {ok:false}, and that direction is the whole point.
|
|
235
|
+
* Under official Pushgateway semantics a POST REPLACES the entire group (the
|
|
236
|
+
* Replace path deletes every stored family the body omits), so silently
|
|
237
|
+
* SKIPPING one of our lines this parser cannot read would be silent,
|
|
238
|
+
* permanent DATA LOSS — a lost `pi_flow_run_cost_usd` row is gone from the
|
|
239
|
+
* runs board for good. Failing the read loses the TOMBSTONE instead:
|
|
240
|
+
* {ok:false} costs one skip entry plus one warning, and the group keeps
|
|
241
|
+
* every byte it had until the next pass. (The homelab build merges on write
|
|
242
|
+
* rather than replacing — see the PMR-WBC2 note at the top of this file —
|
|
243
|
+
* but the fail-closed rule stays correct under either semantics.)
|
|
244
|
+
*
|
|
245
|
+
* The failure is scoped to lines that could belong to THIS group
|
|
246
|
+
* ({@link couldBelongToGroup}), and that scoping is measured, not defensive
|
|
247
|
+
* polish: the live gateway dump carries 38 label-less NON-comment lines
|
|
248
|
+
* (pushgateway's own runtime metrics, `go_goroutines 11`,
|
|
249
|
+
* `go_memstats_alloc_bytes …`), so failing on every unreadable line would
|
|
250
|
+
* have made every read fail and quietly disabled tombstoning everywhere — a
|
|
251
|
+
* worse bug than the one it fixes. A line with no label section at all can
|
|
252
|
+
* never be a group member: the gateway re-forces the grouping labels (`job`,
|
|
253
|
+
* `ref`, `instance`, `mode`) onto every stored series, so all of this group's
|
|
254
|
+
* lines are labelled, and dropping an unlabelled one erases nothing.
|
|
255
|
+
*
|
|
256
|
+
* AIDEV-NOTE (PMR-WBC2 fix round): since the keep-rule requires a `pi_flow*`
|
|
257
|
+
* metric NAME, "could be one of ours" is judged the same way — the raw text
|
|
258
|
+
* must start with `pi_flow` (carrying our group LABELS no longer qualifies).
|
|
259
|
+
* That rests on an emitter-side invariant: every metric `buildPushBody`
|
|
260
|
+
* emits is `pi_flow`-prefixed (pinned by the keep-rule invariant test in
|
|
261
|
+
* test/cost.test.ts — if a future emitter adds another prefix, that test
|
|
262
|
+
* fails LOUDLY instead of the series being silently omitted here). The
|
|
263
|
+
* lines this narrowing stops failing on are exactly the gateway's own
|
|
264
|
+
* bookkeeping lines (`push_time_seconds` etc., possibly malformed): they can
|
|
265
|
+
* never be kept anyway, so failing the read on them would block tombstoning
|
|
266
|
+
* on a line we must drop — and dropping them loses nothing even under
|
|
267
|
+
* replace semantics, because the gateway regenerates them on every accepted
|
|
268
|
+
* POST. They are not ours.
|
|
269
|
+
*/
|
|
270
|
+
export async function fetchGroupBody(
|
|
271
|
+
url: string,
|
|
272
|
+
ref: string,
|
|
273
|
+
mode: 'work' | 'personal',
|
|
274
|
+
token: string | undefined,
|
|
275
|
+
fetchImpl: GroupFetch,
|
|
276
|
+
): Promise<GroupBodyResult> {
|
|
277
|
+
const headers: Record<string, string> = {}
|
|
278
|
+
if (token !== undefined && token.length > 0) {
|
|
279
|
+
headers.authorization = `Bearer ${token}`
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
const response = await fetchImpl(`${trimBase(url)}/metrics`, {
|
|
283
|
+
method: 'GET',
|
|
284
|
+
headers,
|
|
285
|
+
})
|
|
286
|
+
if (response.status < 200 || response.status >= 300) {
|
|
287
|
+
const reason = await errorSnippet(response)
|
|
288
|
+
return {
|
|
289
|
+
ok: false,
|
|
290
|
+
error: `pushgateway GET responded ${response.status} ${response.statusText}${reason}`,
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const dump = await response.text()
|
|
294
|
+
return filterGroupLines(dump, ref, mode)
|
|
295
|
+
} catch (err) {
|
|
296
|
+
const message = err instanceof Error ? err.message : `${err}`
|
|
297
|
+
return { ok: false, error: message }
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** One `key="value"` label as it appeared in the dump, raw text included so
|
|
302
|
+
* kept lines stay byte-identical apart from the stripped pair. */
|
|
303
|
+
interface LabelToken {
|
|
304
|
+
key: string
|
|
305
|
+
/** Escaped value decoded for comparisons; raw kept for the output line. */
|
|
306
|
+
value: string
|
|
307
|
+
raw: string
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Split a `{...}` label section into tokens. Returns null on anything
|
|
312
|
+
* malformed. AIDEV-NOTE: null is NOT "not this group" — it is "unreadable",
|
|
313
|
+
* and {@link filterGroupLines} turns it into a failed READ, because a POST
|
|
314
|
+
* replaces the whole group and an unreadable line may be one this group owns
|
|
315
|
+
* (P2-5 in {@link fetchGroupBody}).
|
|
316
|
+
*/
|
|
317
|
+
function splitLabels(inner: string): LabelToken[] | null {
|
|
318
|
+
const tokens: LabelToken[] = []
|
|
319
|
+
let i = 0
|
|
320
|
+
while (i < inner.length) {
|
|
321
|
+
while (i < inner.length && inner[i] === ' ') i += 1
|
|
322
|
+
if (i === inner.length) break
|
|
323
|
+
const label = readLabel(inner, i)
|
|
324
|
+
if (label === null) return null
|
|
325
|
+
tokens.push(label.token)
|
|
326
|
+
i = skipSpaces(inner, label.next)
|
|
327
|
+
if (i === inner.length) break
|
|
328
|
+
if (inner[i] !== ',') return null
|
|
329
|
+
i = skipSpaces(inner, i + 1)
|
|
330
|
+
}
|
|
331
|
+
return tokens
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function skipSpaces(text: string, from: number): number {
|
|
335
|
+
let i = from
|
|
336
|
+
while (i < text.length && text[i] === ' ') i += 1
|
|
337
|
+
return i
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** Read one `key="value"` token beginning at `start` (Prometheus exposition
|
|
341
|
+
* escaping: `\\`, `\"`, `\n`). Returns the token plus the index just past it. */
|
|
342
|
+
function readLabel(
|
|
343
|
+
inner: string,
|
|
344
|
+
start: number,
|
|
345
|
+
): { token: LabelToken; next: number } | null {
|
|
346
|
+
const eq = inner.indexOf('=', start)
|
|
347
|
+
if (eq < 0) return null
|
|
348
|
+
const key = inner.slice(start, eq).trim()
|
|
349
|
+
if (key.length === 0) return null
|
|
350
|
+
let i = skipSpaces(inner, eq + 1)
|
|
351
|
+
if (inner[i] !== '"') return null
|
|
352
|
+
i += 1
|
|
353
|
+
let value = ''
|
|
354
|
+
let end = -1
|
|
355
|
+
for (let j = i; j < inner.length; j += 1) {
|
|
356
|
+
const ch = inner[j]
|
|
357
|
+
if (ch === '\\' && j + 1 < inner.length) {
|
|
358
|
+
const esc = inner[j + 1]
|
|
359
|
+
if (esc === 'n') value += '\n'
|
|
360
|
+
else if (esc === '"') value += '"'
|
|
361
|
+
else if (esc === '\\') value += '\\'
|
|
362
|
+
else value += esc
|
|
363
|
+
j += 1
|
|
364
|
+
continue
|
|
365
|
+
}
|
|
366
|
+
if (ch === '"') {
|
|
367
|
+
end = j + 1
|
|
368
|
+
break
|
|
369
|
+
}
|
|
370
|
+
value += ch
|
|
371
|
+
}
|
|
372
|
+
if (end < 0) return null
|
|
373
|
+
return { token: { key, value, raw: inner.slice(start, end) }, next: end }
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function labelMatches(
|
|
377
|
+
tokens: readonly LabelToken[],
|
|
378
|
+
ref: string,
|
|
379
|
+
mode: 'work' | 'personal',
|
|
380
|
+
): boolean {
|
|
381
|
+
let job: string | undefined
|
|
382
|
+
let lineRef: string | undefined
|
|
383
|
+
let lineMode: string | undefined
|
|
384
|
+
for (const token of tokens) {
|
|
385
|
+
if (token.key === 'job') job = token.value
|
|
386
|
+
else if (token.key === 'ref') lineRef = token.value
|
|
387
|
+
else if (token.key === 'mode') lineMode = token.value
|
|
388
|
+
}
|
|
389
|
+
if (job !== 'pi-flow') return false
|
|
390
|
+
if (lineRef !== ref) return false
|
|
391
|
+
if (mode === 'work') return lineMode === 'work'
|
|
392
|
+
return lineMode === undefined
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Drop `#` comment lines and foreign lines, keep this group's lines with the
|
|
396
|
+
* injected `instance=""` pair stripped. One drop is deliberate: metric names
|
|
397
|
+
* outside `pi_flow*` (the gateway's own `push_*` bookkeeping, PMR-WBC2). A
|
|
398
|
+
* non-comment line that could belong to this group but cannot be PARSED
|
|
399
|
+
* fails the WHOLE read ({@link unparseableLine}) rather than being dropped —
|
|
400
|
+
* see P2-5 in {@link fetchGroupBody}. */
|
|
401
|
+
function filterGroupLines(
|
|
402
|
+
dump: string,
|
|
403
|
+
ref: string,
|
|
404
|
+
mode: 'work' | 'personal',
|
|
405
|
+
): GroupBodyResult {
|
|
406
|
+
const kept: string[] = []
|
|
407
|
+
for (const line of dump.split('\n')) {
|
|
408
|
+
const trimmed = line.trim()
|
|
409
|
+
if (trimmed.length === 0) continue
|
|
410
|
+
if (trimmed.startsWith('#')) continue
|
|
411
|
+
const open = line.indexOf('{')
|
|
412
|
+
const close = line.lastIndexOf('}')
|
|
413
|
+
const tokens =
|
|
414
|
+
open >= 0 && close > open
|
|
415
|
+
? splitLabels(line.slice(open + 1, close))
|
|
416
|
+
: null
|
|
417
|
+
if (tokens === null) {
|
|
418
|
+
// Unreadable: either it is provably not ours (drop it — every line this
|
|
419
|
+
// group owns starts with a `pi_flow` metric name), or it might be ours
|
|
420
|
+
// and re-posting without it would erase it. Never guess: fail the read.
|
|
421
|
+
if (couldBelongToGroup(line)) return unparseableLine(line)
|
|
422
|
+
continue
|
|
423
|
+
}
|
|
424
|
+
if (!labelMatches(tokens, ref, mode)) continue
|
|
425
|
+
// PMR-WBC2: the gateway's own bookkeeping metrics (push_time_seconds,
|
|
426
|
+
// push_failure_time_seconds) carry the group labels but must never be
|
|
427
|
+
// re-POSTed — see the header note. Only `pi_flow*` metrics are ours.
|
|
428
|
+
if (!line.slice(0, open).trim().startsWith('pi_flow')) continue
|
|
429
|
+
// AIDEV-NOTE (PMR-2EGV, supersedes the PMR-9DZ0 2.2 / PMR-2CPZ prune):
|
|
430
|
+
// `pi_flow_run_title_info` is KEPT in fetched bodies. Terminal
|
|
431
|
+
// publication (the done purge, the stale tombstone) re-posts the full
|
|
432
|
+
// stored body — on the merge-on-write gateway (PMR-WBC2) after a DELETE
|
|
433
|
+
// of the group — so the title must ride that re-post to survive: dropping
|
|
434
|
+
// it here would delete run-title history (the stored group is rebuilt
|
|
435
|
+
// from exactly what we send). Keeping it cannot resurrect a stale title
|
|
436
|
+
// IN THE RENDER — the fresh running-phase push renders the CURRENT title
|
|
437
|
+
// — but AIDEV-NOTE (PMR-3W5K): on this merge-on-write gateway only an
|
|
438
|
+
// UNCHANGED title is overwritten in place. A renamed ticket's fresh push
|
|
439
|
+
// stores the new title alongside the old-title series (merge never
|
|
440
|
+
// deletes), so the stored group can hold multiple title variants; the
|
|
441
|
+
// old variant then makes the terminal-purge guard SKIP fail-closed
|
|
442
|
+
// (flow/terminal-purge.ts, PMR-3W5K note), and the terminal re-post
|
|
443
|
+
// carries forward whatever the last fresh push stored. The safe cleanup
|
|
444
|
+
// is manual: DELETE the pushgateway group, then /flow-cost <ref> --push.
|
|
445
|
+
const survivors = tokens.filter(
|
|
446
|
+
(token) => !(token.key === 'instance' && token.value === ''),
|
|
447
|
+
)
|
|
448
|
+
const labels = survivors.map((token) => token.raw).join(',')
|
|
449
|
+
kept.push(`${line.slice(0, open + 1)}${labels}${line.slice(close)}`)
|
|
450
|
+
}
|
|
451
|
+
if (kept.length === 0) return { ok: true, body: '' }
|
|
452
|
+
return { ok: true, body: `${kept.join('\n')}\n` }
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** True when a line an exposition parser rejected could still be one of the
|
|
456
|
+
* lines this group owns, judged on RAW text (parsing is what failed).
|
|
457
|
+
* AIDEV-NOTE (PMR-WBC2): the keep-rule requires a `pi_flow*` metric name, so
|
|
458
|
+
* a line that does not start with one can never be ours — even when it
|
|
459
|
+
* carries our group labels (the gateway's own broken `push_*` lines do
|
|
460
|
+
* exactly that, and failing the read on them would block tombstoning on a
|
|
461
|
+
* line we must drop anyway). Foreign runtime metrics (`go_goroutines 11`)
|
|
462
|
+
* and other jobs' broken lines are therefore NOT fatal to this read —
|
|
463
|
+
* measured on the live gateway, the dump holds dozens of lines this parser
|
|
464
|
+
* cannot read and that provably do not belong to any pi-flow group. */
|
|
465
|
+
function couldBelongToGroup(line: string): boolean {
|
|
466
|
+
return line.trim().startsWith('pi_flow')
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** The one P2-5 failure shape. The line is quoted (truncated: a dump line can
|
|
470
|
+
* carry a long escaped reason value) because the engine surfaces this string
|
|
471
|
+
* in a warning and an operator has to be able to see WHAT the gateway sent. */
|
|
472
|
+
function unparseableLine(line: string): GroupBodyResult {
|
|
473
|
+
const snippet = line.length > 120 ? `${line.slice(0, 120)}…` : line
|
|
474
|
+
return { ok: false, error: `unparseable dump line: ${snippet}` }
|
|
475
|
+
}
|