@dzhechkov/harness-core 0.8.46 → 0.8.48

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.
Files changed (153) hide show
  1. package/.dz-manifest.json +200 -168
  2. package/README.md +130 -2
  3. package/dist/agentdb-index.d.ts.map +1 -1
  4. package/dist/agentdb-index.js +32 -2
  5. package/dist/agentdb-index.js.map +1 -1
  6. package/dist/agentdb-snapshot.d.ts +14 -1
  7. package/dist/agentdb-snapshot.d.ts.map +1 -1
  8. package/dist/agentdb-snapshot.js +100 -4
  9. package/dist/agentdb-snapshot.js.map +1 -1
  10. package/dist/apply-leg.d.ts +9 -1
  11. package/dist/apply-leg.d.ts.map +1 -1
  12. package/dist/apply-leg.js +26 -4
  13. package/dist/apply-leg.js.map +1 -1
  14. package/dist/architecture.d.ts +0 -5
  15. package/dist/architecture.d.ts.map +1 -1
  16. package/dist/architecture.js +25 -2
  17. package/dist/architecture.js.map +1 -1
  18. package/dist/codex-rollouts.d.ts +35 -7
  19. package/dist/codex-rollouts.d.ts.map +1 -1
  20. package/dist/codex-rollouts.js +201 -113
  21. package/dist/codex-rollouts.js.map +1 -1
  22. package/dist/cost-ledger.d.ts +42 -3
  23. package/dist/cost-ledger.d.ts.map +1 -1
  24. package/dist/cost-ledger.js +478 -15
  25. package/dist/cost-ledger.js.map +1 -1
  26. package/dist/feature-adr-routing.d.ts +16 -0
  27. package/dist/feature-adr-routing.d.ts.map +1 -1
  28. package/dist/feature-adr-routing.js +21 -0
  29. package/dist/feature-adr-routing.js.map +1 -1
  30. package/dist/guard.d.ts +7 -0
  31. package/dist/guard.d.ts.map +1 -1
  32. package/dist/guard.js +48 -0
  33. package/dist/guard.js.map +1 -1
  34. package/dist/index.d.ts +11 -6
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +10 -3
  37. package/dist/index.js.map +1 -1
  38. package/dist/loop-plan.d.ts +4 -0
  39. package/dist/loop-plan.d.ts.map +1 -1
  40. package/dist/loop-plan.js +4 -0
  41. package/dist/loop-plan.js.map +1 -1
  42. package/dist/mutation-gate.d.ts +36 -1
  43. package/dist/mutation-gate.d.ts.map +1 -1
  44. package/dist/mutation-gate.js +109 -19
  45. package/dist/mutation-gate.js.map +1 -1
  46. package/dist/npm-homepage.d.ts +64 -0
  47. package/dist/npm-homepage.d.ts.map +1 -0
  48. package/dist/npm-homepage.js +109 -0
  49. package/dist/npm-homepage.js.map +1 -0
  50. package/dist/operations.d.ts +6 -0
  51. package/dist/operations.d.ts.map +1 -1
  52. package/dist/operations.js +150 -24
  53. package/dist/operations.js.map +1 -1
  54. package/dist/pack-inventory.d.ts.map +1 -1
  55. package/dist/pack-inventory.js +6 -1
  56. package/dist/pack-inventory.js.map +1 -1
  57. package/dist/parity.d.ts.map +1 -1
  58. package/dist/parity.js +4 -1
  59. package/dist/parity.js.map +1 -1
  60. package/dist/publish-sibling-drift.d.ts +43 -1
  61. package/dist/publish-sibling-drift.d.ts.map +1 -1
  62. package/dist/publish-sibling-drift.js +269 -13
  63. package/dist/publish-sibling-drift.js.map +1 -1
  64. package/dist/publish.d.ts +5 -1
  65. package/dist/publish.d.ts.map +1 -1
  66. package/dist/publish.js +18 -1
  67. package/dist/publish.js.map +1 -1
  68. package/dist/qe-bridge.d.ts +63 -1
  69. package/dist/qe-bridge.d.ts.map +1 -1
  70. package/dist/qe-bridge.js +82 -0
  71. package/dist/qe-bridge.js.map +1 -1
  72. package/dist/release-package-audit.d.ts +86 -0
  73. package/dist/release-package-audit.d.ts.map +1 -0
  74. package/dist/release-package-audit.js +272 -0
  75. package/dist/release-package-audit.js.map +1 -0
  76. package/dist/release.d.ts +8 -1
  77. package/dist/release.d.ts.map +1 -1
  78. package/dist/release.js +58 -32
  79. package/dist/release.js.map +1 -1
  80. package/dist/round.d.ts +10 -1
  81. package/dist/round.d.ts.map +1 -1
  82. package/dist/round.js +5 -1
  83. package/dist/round.js.map +1 -1
  84. package/dist/run-records.d.ts +11 -0
  85. package/dist/run-records.d.ts.map +1 -1
  86. package/dist/run-records.js +124 -20
  87. package/dist/run-records.js.map +1 -1
  88. package/dist/setup-memory-deps.d.ts +14 -0
  89. package/dist/setup-memory-deps.d.ts.map +1 -0
  90. package/dist/setup-memory-deps.js +210 -0
  91. package/dist/setup-memory-deps.js.map +1 -0
  92. package/dist/setup.d.ts +2 -0
  93. package/dist/setup.d.ts.map +1 -1
  94. package/dist/setup.js +379 -378
  95. package/dist/setup.js.map +1 -1
  96. package/dist/stage-usage.d.ts +248 -0
  97. package/dist/stage-usage.d.ts.map +1 -0
  98. package/dist/stage-usage.js +511 -0
  99. package/dist/stage-usage.js.map +1 -0
  100. package/dist/statusline.d.ts +23 -0
  101. package/dist/statusline.d.ts.map +1 -1
  102. package/dist/statusline.js +167 -1
  103. package/dist/statusline.js.map +1 -1
  104. package/dist/workflow-run-dispatch.d.ts +36 -19
  105. package/dist/workflow-run-dispatch.d.ts.map +1 -1
  106. package/dist/workflow-run-dispatch.js +255 -102
  107. package/dist/workflow-run-dispatch.js.map +1 -1
  108. package/dist/workflow-run.d.ts +19 -3
  109. package/dist/workflow-run.d.ts.map +1 -1
  110. package/dist/workflow-run.js +93 -2
  111. package/dist/workflow-run.js.map +1 -1
  112. package/package.json +3 -3
  113. package/sbom.json +303 -223
  114. package/src/agentdb-index.ts +31 -2
  115. package/src/agentdb-snapshot.ts +105 -4
  116. package/src/apply-leg.ts +26 -4
  117. package/src/architecture.ts +15 -2
  118. package/src/codex-rollouts.ts +155 -147
  119. package/src/cost-ledger.ts +308 -19
  120. package/src/feature-adr-routing.ts +22 -0
  121. package/src/guard.ts +52 -0
  122. package/src/index.ts +15 -3
  123. package/src/loop-plan.ts +8 -0
  124. package/src/mutation-gate.ts +153 -19
  125. package/src/npm-homepage.ts +142 -0
  126. package/src/operations.ts +177 -22
  127. package/src/pack-inventory.ts +6 -1
  128. package/src/parity.ts +4 -1
  129. package/src/publish-sibling-drift.ts +214 -11
  130. package/src/publish.ts +20 -1
  131. package/src/qe-bridge.ts +86 -1
  132. package/src/release-package-audit.ts +264 -0
  133. package/src/release.ts +55 -22
  134. package/src/round.ts +8 -0
  135. package/src/run-records.ts +101 -22
  136. package/src/setup-memory-deps.ts +166 -0
  137. package/src/setup.ts +95 -98
  138. package/src/stage-usage.ts +385 -0
  139. package/src/statusline.ts +149 -1
  140. package/src/workflow-run-dispatch.ts +197 -93
  141. package/src/workflow-run.ts +101 -5
  142. package/dist/ledger-cost-fill.d.ts +0 -58
  143. package/dist/ledger-cost-fill.d.ts.map +0 -1
  144. package/dist/ledger-cost-fill.js +0 -78
  145. package/dist/ledger-cost-fill.js.map +0 -1
  146. package/dist/retro.d.ts +0 -131
  147. package/dist/retro.d.ts.map +0 -1
  148. package/dist/retro.js +0 -207
  149. package/dist/retro.js.map +0 -1
  150. package/dist/sbom.d.ts +0 -42
  151. package/dist/sbom.d.ts.map +0 -1
  152. package/dist/sbom.js +0 -120
  153. package/dist/sbom.js.map +0 -1
@@ -0,0 +1,385 @@
1
+ /** Derived stage usage only. Source IO and independent witnesses belong to cost-ledger.ts. */
2
+ import { MODEL_PRICES } from './cost-scoring.js';
3
+ import { canonicalStage } from './feature-adr-stage-canon.js';
4
+ import { fnv1a64 } from './feature-adr-checkpoints.js';
5
+ import { parseModelSpec, resolveLedgerModelProvenance } from './run-records.js';
6
+
7
+ type RecordRow = Record<string, unknown>;
8
+ const record = (v: unknown): v is RecordRow => !!v && typeof v === 'object' && !Array.isArray(v);
9
+ const count = (v: unknown): number | null => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : null;
10
+ const text = (v: unknown): string | null => typeof v === 'string' && v.trim() ? v : null;
11
+ const tokenFields = ['tokensTotal', 'tokensIn', 'tokensOut', 'tokensCacheRead', 'tokensCacheWrite', 'tokensReasoning'] as const;
12
+
13
+ function price(row: RecordRow, dimensions: Record<typeof tokenFields[number], number | null>) {
14
+ const model = text(row['model']); const normalized = model?.toLowerCase().replace(/^[a-z0-9-]+\//, '') ?? '';
15
+ let tableKey = Object.keys(MODEL_PRICES).filter((key) => normalized.startsWith(key)).sort((a, b) => b.length - a.length)[0] ?? null;
16
+ if (!tableKey && ['sonnet', 'opus', 'haiku'].includes(normalized)) tableKey = 'claude-' + normalized;
17
+ let matchKind: 'exact' | 'family-estimate' | 'unknown' = tableKey === null ? 'unknown'
18
+ : tableKey === normalized && !tableKey.includes('claude') ? 'exact' : 'family-estimate';
19
+ let rate = tableKey === null ? null : MODEL_PRICES[tableKey]!;
20
+ let source = 'MODEL_PRICES static snapshot';
21
+ const prices = record(row['prices']) ? row['prices'] : null;
22
+ const matches = prices && record(prices['matches']) ? prices['matches'] : null;
23
+ const table = prices && record(prices['table']) ? prices['table'] : null;
24
+ if (prices) {
25
+ // Never silently reprice a historical snapshot using today's table or its alias spelling.
26
+ rate = null; matchKind = 'unknown'; tableKey = null; source = 'persisted snapshot lacking applicable match provenance';
27
+ for (const alias of [model, text(row['coder']), text(row['reviewer'])]) {
28
+ if (!alias || !model || !table || !matches || !record(table[alias]) || !record(matches[alias])) continue;
29
+ const aliasModel = parseModelSpec(alias)?.model ?? alias;
30
+ if (aliasModel !== model) continue;
31
+ const proposed = table[alias]; const match = matches[alias];
32
+ const key = text(match['tableKey']); const kind = match['kind'];
33
+ if (key === null || !['exact', 'family-estimate'].includes(String(kind))) continue;
34
+ if (kind === 'exact' && (key !== model || key.includes('claude'))) continue;
35
+ if (kind === 'family-estimate' && !(normalized.startsWith(key) || ('claude-' + normalized).startsWith(key))) continue;
36
+ if (['prompt', 'completion', 'cachedInput', 'cacheCreation'].every((field) => typeof proposed[field] === 'number' && Number.isFinite(proposed[field]) && (proposed[field] as number) >= 0)) {
37
+ rate = proposed as unknown as NonNullable<typeof rate>; matchKind = kind as 'exact' | 'family-estimate'; tableKey = key; source = 'persisted declared ' + matchKind + ' snapshot'; break;
38
+ }
39
+ }
40
+ }
41
+ const { tokensIn: input, tokensOut: output, tokensCacheRead: read, tokensCacheWrite: write } = dimensions;
42
+ const semantics = row['inputCacheSemantics'];
43
+ let amount: number | null = null;
44
+ if (rate && input !== null && output !== null && read !== null && write !== null) {
45
+ const plainInput = semantics === 'includes-cache-read-write' ? input - read - write
46
+ : semantics === 'excludes-cache-read-write' ? input : null;
47
+ if (plainInput !== null && plainInput >= 0) amount = plainInput * rate.prompt + output * rate.completion + read * rate.cachedInput + write * rate.cacheCreation;
48
+ }
49
+ if (amount !== null && (!Number.isFinite(amount) || (Array.isArray(row['usageDiagnostics']) && row['usageDiagnostics'].some((v) => typeof v === 'string' && /invalid|mismatch|conflict|exceeds|overflow/.test(v))))) amount = null;
50
+ return { estimatedCostUsd: matchKind === 'exact' ? amount : null, familyEstimatedCostUsd: matchKind === 'family-estimate' ? amount : null,
51
+ pricingKnown: matchKind === 'exact' && amount !== null,
52
+ pricingReason: matchKind === 'unknown' ? 'unknown-model-rate' : amount === null ? 'incomplete-priceable-mix' : matchKind === 'family-estimate' ? 'family-rate-is-not-exact-model' : null,
53
+ priceMatch: { tableKey, matchKind, source, version: text(prices?.['version']) ?? (prices ? 'persisted-version-not-recorded' : 'MODEL_PRICES-unversioned'),
54
+ capturedAt: text(prices?.['snapshotAt']), fingerprint: fnv1a64(JSON.stringify(prices ?? MODEL_PRICES)), current: false, billed: false } };
55
+ }
56
+
57
+ type RoutingInput = Parameters<typeof buildStageUsageReport>[0];
58
+ type RoutingAttempt = { ordinal: number; model: string | null; family: 'openai' | 'claude'; wrapperInvoked: boolean;
59
+ outcome: 'answered' | 'failed' | 'rejected'; reason: string; selected: boolean };
60
+ type RoutingStage = { evidenceKey: string; dispatchSeq: number; plannedModel: string | null;
61
+ plannedModelSource: 'plan-declared' | 'plan-omitted' | 'unavailable' | 'not-recorded'; requestedModel: string | null;
62
+ probeId: string | null; linkStatus: string };
63
+ type RoutingProbe = { probeId: string; runId: string; family: 'openai' | 'claude'; source: string;
64
+ selectedModel: string | null; complete: boolean; totalConsidered: number; attempts: RoutingAttempt[] };
65
+ const safeRoutingModel = (value: unknown): value is string => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(value);
66
+ const routingId = (value: unknown): value is string => typeof value === 'string' && /^[0-9a-f]{32}$/.test(value);
67
+ const routingRun = (value: unknown): value is string => typeof value === 'string' && /^[A-Za-z0-9_.-]{1,128}$/.test(value) && value !== '.' && value !== '..';
68
+ const routingFamily = (value: unknown): value is 'openai' | 'claude' => value === 'openai' || value === 'claude';
69
+ const exactRoutingKeys = (value: unknown, keys: readonly string[]): value is RecordRow => record(value)
70
+ && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)
71
+ && Reflect.ownKeys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key));
72
+ const routingAbsenceReasons = ['producer-not-recorded', 'id-factory-missing'];
73
+ const routingErrorReasons = ['id-factory-invalid', 'provenance-invalid', 'candidate-model-invalid', 'wrapper-result-invalid', 'selected-model-invalid'];
74
+
75
+ function validateRoutingAttempts(value: unknown, family: unknown, selectedModel: unknown): { complete: boolean; totalConsidered: number; attempts: RoutingAttempt[] } | null {
76
+ if (!exactRoutingKeys(value, ['schema', 'complete', 'totalConsidered', 'attempts']) || value['schema'] !== 'wf-probe-attempts-1'
77
+ || typeof value['complete'] !== 'boolean' || !routingFamily(family) || (selectedModel !== null && !safeRoutingModel(selectedModel))) return null;
78
+ const total = count(value['totalConsidered']);
79
+ const attempts = value['attempts'];
80
+ if (total === null || total === 0 || !Array.isArray(attempts) || attempts.length !== Math.min(total, 32) || value['complete'] !== (total <= 32)) return null;
81
+ const safe: RoutingAttempt[] = [];
82
+ for (const [index, a] of attempts.entries()) {
83
+ if (!exactRoutingKeys(a, ['ordinal', 'model', 'family', 'wrapperInvoked', 'outcome', 'reason', 'selected']) || a['ordinal'] !== index + 1
84
+ || a['family'] !== family || typeof a['wrapperInvoked'] !== 'boolean' || typeof a['selected'] !== 'boolean') return null;
85
+ const rejected = family === 'claude' && !a['wrapperInvoked'] && !a['selected'] && a['model'] === null && a['outcome'] === 'rejected' && a['reason'] === 'invalid-candidate';
86
+ const answered = a['wrapperInvoked'] && a['selected'] && safeRoutingModel(a['model']) && a['outcome'] === 'answered' && a['reason'] === 'answered';
87
+ const failed = a['wrapperInvoked'] && !a['selected'] && safeRoutingModel(a['model']) && a['outcome'] === 'failed'
88
+ && ['timeout', 'spawn-error', 'no-exit-code', 'exit-nonzero', 'unexpected-response'].includes(a['reason'] as string);
89
+ if (!(rejected || answered || failed)) return null;
90
+ safe.push({ ordinal: index + 1, model: a['model'] as string | null, family, wrapperInvoked: a['wrapperInvoked'],
91
+ outcome: a['outcome'] as RoutingAttempt['outcome'], reason: a['reason'] as string, selected: a['selected'] });
92
+ }
93
+ const selected = safe.filter(a => a.selected);
94
+ if (!value['complete'] ? selected.length !== 0 : selectedModel === null ? selected.length !== 0
95
+ : selected.length !== 1 || selected[0]?.ordinal !== total || selected[0]?.model !== selectedModel) return null;
96
+ return { complete: value['complete'], totalConsidered: total, attempts: safe };
97
+ }
98
+
99
+ function routingStageIdentity(row: RecordRow): { evidenceKey: string; dispatchSeq: number } | null {
100
+ const seq = count(row['dispatchSeq']);
101
+ if (seq === null || seq === 0 || !routingRun(row['runId'])) return null;
102
+ const evidenceKey = JSON.stringify(['wf-dispatch', row['runId'], seq]);
103
+ if (Object.hasOwn(row, 'evidenceKey') && row['evidenceKey'] !== evidenceKey) return null;
104
+ return { evidenceKey, dispatchSeq: seq };
105
+ }
106
+
107
+ /** Routing uses raw bounded evidence, independently of numerical first-wins normalization. */
108
+ function projectRoutingProvenance(input: RoutingInput) {
109
+ const diagnostics = new Set<string>();
110
+ let defect = false;
111
+ let partial = false;
112
+ let scopeInvalid = false;
113
+ let scopeIncomplete = false;
114
+ const mark = (reason: string, severity: 'defect' | 'partial' = 'partial') => {
115
+ diagnostics.add(reason);
116
+ if (severity === 'defect') defect = true; else partial = true;
117
+ };
118
+ const metadataInvalid = (reason = 'metadata-invalid') => mark(reason, 'defect');
119
+ const sourceMap: Record<string, [string, 'defect' | 'partial']> = {
120
+ 'inventory-truncated': ['source-truncated', 'partial'], 'source-input-too-large': ['source-too-large', 'partial'],
121
+ 'missing-or-unreadable-source': ['source-unreadable', 'partial'], 'malformed-record': ['source-malformed', 'defect'],
122
+ 'malformed-budget-schema': ['source-malformed', 'defect'],
123
+ 'inventory-run-state-unavailable-or-foreign': ['source-scope-incomplete', 'partial'],
124
+ 'inventory-trace-binding-unavailable': ['source-scope-incomplete', 'partial'],
125
+ };
126
+ const invalidSources = ['source-outside-root-or-nonregular', 'source-symlink', 'source-changed-during-read',
127
+ 'inventory-trace-binding-mismatch', 'inventory-trace-invalid', 'inventory-workflow-projection-identity-invalid',
128
+ 'inventory-workflow-projection-identity-mismatch', 'foreign-project-root', 'foreign-trace-run', 'unknown-source',
129
+ 'source-selection-ambiguous', 'source-selection-conflicting-run-dir', 'workflow-source-missing-or-ambiguous', 'fa-run-selection-ambiguous-or-unidentified'];
130
+ for (const diagnostic of input.diagnostics ?? []) {
131
+ if (typeof diagnostic !== 'string' || diagnostic.length === 0) continue;
132
+ const name = diagnostic.split(':', 1)[0]!;
133
+ const mapping = invalidSources.includes(name) ? ['source-scope-invalid', 'defect'] as const : sourceMap[name];
134
+ if (mapping) { mark(mapping[0], mapping[1]); scopeInvalid ||= mapping[0] === 'source-scope-invalid'; scopeIncomplete ||= mapping[1] === 'partial'; }
135
+ else { mark('source-diagnostic-unmapped'); scopeIncomplete = true; }
136
+ }
137
+ const maximum = input.maxRecords ?? 100000;
138
+ if (input.rows.length > maximum || (input.expected?.length ?? 0) > maximum) { mark('source-truncated'); scopeIncomplete = true; }
139
+ const rawRows = input.rows.slice(0, maximum);
140
+ const invalidNormalizedKeys = new Set<string>();
141
+ const stageMaps = new Map<string, { raw: RecordRow; tuple: string; conflict: boolean; legacy: boolean; valid: boolean; modelInvalid: boolean }>();
142
+ const probeMaps = new Map<string, { raw: RecordRow; tuple: string; conflict: boolean; valid: boolean; reason: string | null; summary: RoutingProbe | null }>();
143
+ let hasNew = false;
144
+ let hasLegacy = false;
145
+ if (input.sourceKind === 'workflow-budget') {
146
+ if (!routingRun(input.runId)) { mark('source-scope-invalid', 'defect'); scopeInvalid = true; }
147
+ if (input.expected === undefined) { mark('source-scope-incomplete'); scopeIncomplete = true; }
148
+ for (const raw of rawRows) {
149
+ if (raw['kind'] === 'probe') {
150
+ const keys = ['probeId', 'probeProvenance', 'probeSource', 'probeObservationReason'];
151
+ const present = keys.map(key => Object.hasOwn(raw, key));
152
+ if (present.every(value => !value)) { hasLegacy ||= raw['runId'] === input.runId; continue; }
153
+ hasNew ||= raw['runId'] === input.runId;
154
+ const reason = raw['probeObservationReason'];
155
+ const modelValid = raw['model'] === null || safeRoutingModel(raw['model']);
156
+ const reasonValid = reason === null || (typeof reason === 'string' && [...routingAbsenceReasons, ...routingErrorReasons].includes(reason));
157
+ const idValid = raw['probeId'] === null || routingId(raw['probeId']);
158
+ const sourceValid = raw['probeSource'] === 'dispatcher-child-seam' || raw['probeSource'] === 'scripted-dispatcher';
159
+ const provenance = reason === null ? validateRoutingAttempts(raw['probeProvenance'], raw['family'], raw['model']) : null;
160
+ const valid = present.every(Boolean) && routingRun(raw['runId']) && routingFamily(raw['family']) && idValid && sourceValid && modelValid && reasonValid
161
+ && (reason === null ? routingId(raw['probeId']) && provenance !== null : raw['probeProvenance'] === null);
162
+ const supplied = raw['probeProvenance'];
163
+ const unsafeAttemptModel = record(supplied) && Array.isArray(supplied['attempts']) && supplied['attempts'].slice(0, 32).some(a => record(a)
164
+ && Object.hasOwn(a, 'model') && a['model'] !== null && !safeRoutingModel(a['model']));
165
+ if (!valid) metadataInvalid(modelValid && !unsafeAttemptModel ? 'metadata-invalid' : 'model-invalid');
166
+ else if (typeof reason === 'string') mark(reason, routingErrorReasons.includes(reason) ? 'defect' : 'partial');
167
+ else if (provenance && !provenance.complete) mark('attempts-truncated');
168
+ if (!routingId(raw['probeId'])) continue;
169
+ const summary: RoutingProbe | null = valid && reason === null && provenance !== null ? {
170
+ probeId: raw['probeId'], runId: raw['runId'] as string, family: raw['family'] as RoutingProbe['family'], source: raw['probeSource'] as string,
171
+ selectedModel: raw['model'] as string | null, complete: provenance.complete, totalConsidered: provenance.totalConsidered, attempts: provenance.attempts,
172
+ } : null;
173
+ // Rejected metadata is one closed marker: never traverse, copy or stringify its raw payload.
174
+ const tuple = JSON.stringify(valid
175
+ ? ['valid', raw['runId'], raw['family'], raw['model'], raw['probeSource'], reason, provenance]
176
+ : ['invalid']);
177
+ const old = probeMaps.get(raw['probeId']);
178
+ if (old && old.tuple !== tuple) { old.conflict = true; metadataInvalid('identity-conflict'); }
179
+ else if (!old) probeMaps.set(raw['probeId'], { raw, tuple, conflict: false, valid, reason: typeof reason === 'string' ? reason : null, summary });
180
+ } else if (raw['kind'] === 'stage') {
181
+ const identity = routingStageIdentity(raw);
182
+ if (!identity || raw['runId'] !== input.runId) {
183
+ metadataInvalid();
184
+ const key = text(raw['evidenceKey']) ?? (count(raw['dispatchSeq']) !== null ? JSON.stringify(['wf-dispatch', raw['runId'], raw['dispatchSeq']]) : null);
185
+ if (key !== null) invalidNormalizedKeys.add(key);
186
+ continue;
187
+ }
188
+ const keys = ['plannedModel', 'plannedModelSource', 'probeId'];
189
+ const present = keys.map(key => Object.hasOwn(raw, key));
190
+ const legacy = present.every(value => !value);
191
+ hasLegacy ||= legacy; hasNew ||= !legacy;
192
+ const plan = raw['plannedModel'];
193
+ const source = raw['plannedModelSource'];
194
+ const requestValid = raw['requestedModel'] === null || safeRoutingModel(raw['requestedModel']);
195
+ const planValid = source === 'plan-declared' ? safeRoutingModel(plan) : (source === 'plan-omitted' || source === 'unavailable') && plan === null;
196
+ const valid = legacy || present.every(Boolean) && requestValid && planValid && routingFamily(raw['family']) && (raw['probeId'] === null || routingId(raw['probeId']));
197
+ const modelInvalid = !legacy && (!requestValid || (source === 'plan-declared' && !safeRoutingModel(plan)) || source === 'unavailable');
198
+ if (!valid || modelInvalid) metadataInvalid(modelInvalid ? 'model-invalid' : 'metadata-invalid');
199
+ const tuple = JSON.stringify(legacy
200
+ ? ['legacy', routingFamily(raw['family']) ? raw['family'] : null, safeRoutingModel(raw['requestedModel']) ? raw['requestedModel'] : null]
201
+ : valid ? ['valid', raw['family'], raw['requestedModel'], plan, source, raw['probeId']] : ['invalid']);
202
+ const old = stageMaps.get(identity.evidenceKey);
203
+ if (old && old.tuple !== tuple) { old.conflict = true; metadataInvalid('identity-conflict'); }
204
+ else if (!old) stageMaps.set(identity.evidenceKey, { raw, tuple, conflict: false, legacy, valid, modelInvalid });
205
+ } else metadataInvalid();
206
+ }
207
+ for (const expected of (input.expected ?? []).slice(0, maximum)) {
208
+ const identity = routingStageIdentity(expected);
209
+ if (!identity || expected['runId'] !== input.runId) { metadataInvalid(); continue; }
210
+ if (!stageMaps.has(identity.evidenceKey)) { mark('expected-dispatch-missing'); scopeIncomplete = true; }
211
+ }
212
+ }
213
+ if (hasNew && hasLegacy) mark('not-recorded');
214
+ const stages: RoutingStage[] = [];
215
+ for (const [evidenceKey, stage] of [...stageMaps].sort(([a], [b]) => a.localeCompare(b))) {
216
+ const raw = stage.raw;
217
+ const referenced = routingId(raw['probeId']) ? probeMaps.get(raw['probeId']) : undefined;
218
+ let linkStatus = 'linked';
219
+ if (stage.conflict || referenced?.conflict) linkStatus = 'identity-conflict';
220
+ else if (scopeInvalid || !stage.valid || stage.modelInvalid || referenced && (!referenced.valid || referenced.reason !== null && routingErrorReasons.includes(referenced.reason))) linkStatus = 'invalid';
221
+ else if (stage.legacy) linkStatus = 'not-recorded';
222
+ else if (referenced && referenced.raw['runId'] !== input.runId) linkStatus = 'foreign-probe';
223
+ else if (referenced && referenced.raw['family'] !== raw['family']) linkStatus = 'family-mismatch';
224
+ else if (referenced?.summary && (referenced.summary.selectedModel === null || referenced.summary.selectedModel !== raw['requestedModel'])) linkStatus = 'selection-mismatch';
225
+ else if (raw['probeId'] !== null && !referenced) linkStatus = 'missing-probe';
226
+ else if (raw['probeId'] === null || referenced?.reason !== null && referenced?.reason !== undefined) linkStatus = 'probe-unavailable';
227
+ else if (scopeIncomplete) linkStatus = 'scope-incomplete';
228
+ const suppress = ['identity-conflict', 'invalid', 'foreign-probe', 'family-mismatch', 'selection-mismatch'].includes(linkStatus);
229
+ if (suppress) metadataInvalid(linkStatus === 'invalid' ? 'metadata-invalid' : linkStatus);
230
+ else if (linkStatus !== 'linked' && linkStatus !== 'not-recorded') mark(linkStatus === 'scope-incomplete' ? 'source-scope-incomplete' : linkStatus);
231
+ const identity = routingStageIdentity(raw)!;
232
+ stages.push({ evidenceKey, dispatchSeq: identity.dispatchSeq, plannedModel: suppress || stage.legacy ? null : raw['plannedModel'] as string | null,
233
+ plannedModelSource: suppress ? 'unavailable' : stage.legacy ? 'not-recorded' : raw['plannedModelSource'] as RoutingStage['plannedModelSource'],
234
+ requestedModel: suppress || stage.legacy ? null : raw['requestedModel'] as string | null,
235
+ probeId: !suppress && (linkStatus === 'linked' || linkStatus === 'scope-incomplete') ? raw['probeId'] as string : null, linkStatus });
236
+ }
237
+ const probes = [...probeMaps.values()].filter(probe => !scopeInvalid && !probe.conflict && probe.summary && probe.raw['runId'] === input.runId)
238
+ .map(probe => probe.summary!).sort((a, b) => a.probeId.localeCompare(b.probeId));
239
+ if (!hasNew) diagnostics.add('not-recorded');
240
+ const status = defect ? 'defect' : partial ? 'partial' : hasNew ? 'observed' : 'not-recorded';
241
+ const exposedStages = hasNew || defect ? stages : [];
242
+ const stageFields = new Map(stages.map(stage => [stage.evidenceKey, {
243
+ plannedModel: stage.plannedModel, plannedModelSource: stage.plannedModelSource, probeId: stage.probeId,
244
+ }]));
245
+ for (const key of invalidNormalizedKeys) stageFields.set(key, { plannedModel: null, plannedModelSource: 'unavailable', probeId: null });
246
+ return { report: { schema: 'routing-provenance-1', status, probes: probes.length ? probes : null,
247
+ stages: exposedStages.length ? exposedStages : null, diagnostics: [...diagnostics].sort() }, stageFields };
248
+ }
249
+
250
+ /** All amounts remain source-specific; inventory never substitutes for a numeric witness. */
251
+ export function buildStageUsageReport(input: {
252
+ sourceKind: string; sourcePath: string; runId: string | null; rows: readonly RecordRow[];
253
+ expected?: readonly RecordRow[]; witnesses?: readonly RecordRow[]; moneyObservations?: readonly RecordRow[];
254
+ diagnostics?: readonly string[]; sourceDiagnostics?: readonly string[]; maxRecords?: number;
255
+ }) {
256
+ const diagnostics = [...(input.diagnostics ?? [])]; const sourceDiagnostics = [...(input.sourceDiagnostics ?? [])];
257
+ const maximum = input.maxRecords ?? 100000;
258
+ if (input.rows.length > maximum) diagnostics.push('inventory-truncated');
259
+ const originalKeys = new Set(input.rows.map((v) => text(v['evidenceKey']) ?? (count(v['dispatchSeq']) !== null ? JSON.stringify(['wf-dispatch', v['runId'], v['dispatchSeq']]) : null)));
260
+ const witnessOnly: RecordRow[] = (input.witnesses ?? []).filter((v) => !originalKeys.has(text(v['evidenceKey']))).map((v) => ({ ...v, runId: input.runId, stage: null, phase: null, stepId: null, unassignedSource: true }));
261
+ const normalized = [...input.rows, ...witnessOnly].slice(0, maximum).map((raw, index) => {
262
+ const identity = resolveLedgerModelProvenance(raw);
263
+ const { model, family } = identity;
264
+ diagnostics.push(...identity.diagnostics);
265
+ const phase = text(raw['phase']);
266
+ const stage = input.sourceKind === 'workflow-budget' ? phase ?? text(raw['stage']) ?? text(raw['stepId']) : text(raw['stage']) ?? phase ?? text(raw['stepId']);
267
+ const dimensions = Object.fromEntries(tokenFields.map((key) => [key, count(raw[key])])) as Record<typeof tokenFields[number], number | null>;
268
+ if (raw['tokensTotal'] === undefined && raw['tokens'] !== undefined) dimensions.tokensTotal = count(raw['tokens']);
269
+ for (const key of tokenFields) if (raw[key] != null && count(raw[key]) === null) diagnostics.push('invalid-count:' + index + ':' + key);
270
+ const dispatchSeq = count(raw['dispatchSeq']);
271
+ const evidenceKey = text(raw['evidenceKey']) ?? (input.sourceKind === 'workflow-budget' && dispatchSeq !== null
272
+ ? JSON.stringify(['wf-dispatch', raw['runId'], dispatchSeq]) : null);
273
+ const metadata = { phase, role: text(raw['role']), attempt: count(raw['attempt']), dispatchSeq, itemKey: text(raw['itemKey']),
274
+ stepId: text(raw['stepId']), tier: text(raw['tier']), mode: text(raw['mode']) };
275
+ const missingReasons = Object.entries({ model, family, stage, evidenceKey, ...metadata }).filter(([, value]) => value === null).map(([key]) => key + ':not-recorded');
276
+ const basis = text(raw['reportedTotalBasis']) ?? (raw['tokensOutSource'] === 'budget.spent' ? 'output-only' : 'unknown');
277
+ const priced = price({ ...raw, model, usageDiagnostics: [...(Array.isArray(raw['usageDiagnostics']) ? raw['usageDiagnostics'] : []), ...identity.diagnostics] }, dimensions);
278
+ const reportedCostUsd = typeof raw['reportedCostUsd'] === 'number' && Number.isFinite(raw['reportedCostUsd']) && raw['reportedCostUsd'] >= 0 ? raw['reportedCostUsd'] : null;
279
+ const usageDiagnostics = Array.isArray(raw['usageDiagnostics']) ? raw['usageDiagnostics'].filter((v): v is string => typeof v === 'string') : [];
280
+ diagnostics.push(...usageDiagnostics.map((v) => 'usage:' + v));
281
+ const rawSource = record(raw['usageSource']) ? raw['usageSource'] : null;
282
+ const usageSource = rawSource ? Object.fromEntries(['schema', 'scope', 'threadId', 'turnId', 'receiptId'].map((key) => [key, text(rawSource[key])])) : null;
283
+ const estimate = record(raw['estimate']) ? { tokens: count(raw['estimate']['tokens']),
284
+ costUsd: typeof raw['estimate']['costUsd'] === 'number' && Number.isFinite(raw['estimate']['costUsd']) ? raw['estimate']['costUsd'] : null,
285
+ method: text(raw['estimate']['method']), source: text(raw['estimate']['source']), capturedAt: text(raw['estimate']['capturedAt']) } : null;
286
+ return { sourceKind: input.sourceKind, evidenceKey, runId: text(raw['runId']), stage, stageCanonical: canonicalStage(stage ?? '').stage,
287
+ model, family, modelProvenance: identity.modelProvenance, requestedModel: text(raw['requestedModel']), totalDerivation: text(raw['totalDerivation']) ?? 'not-recorded', ...metadata, ...dimensions, reportedTotalBasis: basis, inputCacheSemantics: text(raw['inputCacheSemantics']) ?? 'unknown',
288
+ usageSource, reportedCostUsd, billedCostUsd: null, billedCostReason: 'not-observed',
289
+ estimate, estimateReason: estimate === null ? 'not-recorded' : null,
290
+ ...priced, missingReasons, outcome: text(raw['outcome']), usageDiagnostics, unassignedSource: raw['unassignedSource'] === true };
291
+ });
292
+ type Normalized = typeof normalized[number];
293
+ const unique = new Map<string, Normalized>(); const owners = new Map<string, Set<string>>(); const conflicts = new Set<string>();
294
+ const unkeyed: Normalized[] = [];
295
+ const payload = (row: Normalized) => JSON.stringify([row.model, row.family, ...tokenFields.map((k) => row[k]), row.reportedTotalBasis, row.inputCacheSemantics, row.reportedCostUsd]);
296
+ for (const row of normalized) {
297
+ if (input.runId !== null && row.runId !== input.runId) { diagnostics.push('foreign-run'); continue; }
298
+ if (row.evidenceKey === null) { diagnostics.push('missing-evidence-identity'); unkeyed.push(row); continue; }
299
+ const prior = unique.get(row.evidenceKey);
300
+ if (prior && payload(prior) !== payload(row)) { conflicts.add(row.evidenceKey); diagnostics.push('conflicting-duplicate:' + row.evidenceKey); }
301
+ else unique.set(row.evidenceKey, prior ?? row);
302
+ const claim = JSON.stringify([row.stage, row.attempt, row.stepId, row.itemKey, row.role]);
303
+ const set = owners.get(row.evidenceKey) ?? new Set<string>(); set.add(claim); owners.set(row.evidenceKey, set);
304
+ }
305
+ const expected = input.expected === undefined ? null : new Map(input.expected.map((v) => [text(v['evidenceKey']) ?? JSON.stringify(['wf-dispatch', v['runId'], v['dispatchSeq']]), v]));
306
+ const rows = [...unique.values()].filter((row) => {
307
+ if (expected && !expected.has(row.evidenceKey!)) { diagnostics.push('foreign-evidence:' + row.evidenceKey); return false; }
308
+ const trace = expected?.get(row.evidenceKey!);
309
+ if (trace) for (const key of ['runId', 'stepId', 'itemKey', 'attempt', 'model', 'phase'] as const) {
310
+ if (trace[key] != null && trace[key] !== (key === 'model' ? (row.requestedModel ?? row.model) : row[key])) diagnostics.push('inventory-identity-mismatch:' + key);
311
+ }
312
+ return !conflicts.has(row.evidenceKey!);
313
+ }).concat(unkeyed);
314
+ const sum = (values: readonly number[]): number | null => {
315
+ const total = values.reduce((n, v) => n + v, 0); if (!Number.isSafeInteger(total)) { diagnostics.push('aggregate-overflow'); return null; } return total;
316
+ };
317
+ const bases = [...new Set(rows.filter((row) => row.tokensTotal !== null).map((row) => row.reportedTotalBasis))];
318
+ const compatible = bases.length <= 1;
319
+ if (!compatible) diagnostics.push('incompatible-total-bases');
320
+ const metric = bases[0] === 'raw-inclusive' ? 'raw-tokens' : bases[0] === 'uncached-display' ? 'uncached-display-tokens' : bases[0] === 'weighted-input-equivalent' ? 'weighted-input-equivalent' : 'source-reported-total';
321
+ const known = compatible ? sum(rows.map((row) => row.tokensTotal).filter((v): v is number => v !== null)) : null;
322
+ const expectedMissing = expected ? [...expected.keys()].filter((key) => !originalKeys.has(key) || conflicts.has(key)) : [];
323
+ const missingTotals = rows.filter((row) => row.tokensTotal === null).length + expectedMissing.length;
324
+ const inventoryComplete = expected !== null && expectedMissing.length === 0 && unkeyed.length === 0
325
+ && !diagnostics.some((d) => /inventory|foreign|malformed|truncated|unreadable|missing-source/.test(d));
326
+ const witnesses = new Map((input.witnesses ?? []).map((v) => [text(v['evidenceKey']), v]));
327
+ let witnessComplete = rows.length > 0 && rows.every((row) => row.evidenceKey !== null && witnesses.has(row.evidenceKey));
328
+ for (const row of rows) {
329
+ const witness = witnesses.get(row.evidenceKey); if (!witness) continue;
330
+ if (count(witness['tokensTotal']) !== row.tokensTotal || witness['reportedTotalBasis'] !== row.reportedTotalBasis) sourceDiagnostics.push('source-amount-mismatch:' + row.evidenceKey);
331
+ }
332
+ if (sourceDiagnostics.length) witnessComplete = false;
333
+ const sourceVerification = { status: sourceDiagnostics.length ? 'defect' : witnessComplete ? 'verified' : 'unavailable', diagnostics: sourceDiagnostics,
334
+ reason: witnessComplete ? null : sourceDiagnostics.length ? 'source-conflict' : 'no-independent-same-scope-amount-witness' };
335
+ const accounted = compatible ? sum(rows.filter((row) => row.stage !== null).map((row) => row.tokensTotal).filter((v): v is number => v !== null)) : null;
336
+ const unaccounted = compatible && known !== null && accounted !== null ? known - accounted : null;
337
+ const doubled = compatible ? sum(rows.map((row) => (owners.get(row.evidenceKey ?? '')?.size ?? 1) > 1 ? (row.tokensTotal ?? 0) : 0)) : null;
338
+ if (doubled !== null && doubled > 0) diagnostics.push('double-attribution');
339
+ // Monetary scope is independent of token expansion: never allocate a parent amount to responses.
340
+ const moneyInputs = input.moneyObservations ?? rows.map((row) => ({ id: row.evidenceKey,
341
+ runId: row.runId, scope: JSON.stringify([input.sourceKind, row.runId, row.evidenceKey]), basis: 'provider-reported', amount: row.reportedCostUsd }));
342
+ const money = new Map<string, { id: string; runId: string | null; scope: string; basis: string; amount: number | null }>();
343
+ const moneyConflicts = new Set<string>(); let moneyUnknown = moneyInputs.length === 0;
344
+ for (const raw of moneyInputs.slice(0, maximum)) {
345
+ const id = text(raw['id']); const scope = text(raw['scope']); const basis = text(raw['basis']); const runId = text(raw['runId']);
346
+ if (input.runId !== null && runId !== input.runId) { diagnostics.push('money-foreign-run'); moneyUnknown = true; continue; }
347
+ const amount = typeof raw['amount'] === 'number' && Number.isFinite(raw['amount']) && raw['amount'] >= 0 ? raw['amount'] : null;
348
+ if (raw['amount'] != null && amount === null) diagnostics.push('money-invalid-amount');
349
+ if (!id || !scope || !basis) { diagnostics.push('money-identity-unavailable'); moneyUnknown = true; continue; }
350
+ const observation = { id, runId, scope, basis, amount }; const prior = money.get(id);
351
+ if (prior && JSON.stringify(prior) !== JSON.stringify(observation)) { diagnostics.push('money-conflict:' + id); moneyConflicts.add(id); }
352
+ else money.set(id, prior ?? observation);
353
+ }
354
+ if (moneyInputs.length > maximum) { diagnostics.push('money-inventory-truncated'); moneyUnknown = true; }
355
+ const moneyObservations = [...money.values()].filter((v) => !moneyConflicts.has(v.id));
356
+ moneyUnknown ||= moneyObservations.some((v) => v.amount === null);
357
+ const knownReported = moneyObservations.reduce((n, v) => n + (v.amount ?? 0), 0);
358
+ if (!Number.isFinite(knownReported)) { diagnostics.push('money-overflow'); moneyUnknown = true; }
359
+ const moneyDefect = diagnostics.some((d) => /^money-(conflict|foreign|invalid|overflow)/.test(d));
360
+ const reportedCostCoverage = { status: moneyDefect ? 'defect' : moneyUnknown ? 'unavailable' : 'complete',
361
+ reason: moneyDefect ? 'conflicting-or-invalid-money-observation' : moneyUnknown ? 'reported-money-or-scope-not-recorded' : null };
362
+ const quantitativeDefect = diagnostics.some((d) => /conflict|foreign|mismatch|invalid|overflow|double-attribution|malformed|exceeds|cumulative-reset/.test(d)) || sourceDiagnostics.length > 0;
363
+ const totalComplete = compatible && missingTotals === 0 && inventoryComplete && rows.length > 0 && !quantitativeDefect;
364
+ const moneySum = (values: readonly number[]): number | null => { const total = values.reduce((n,v) => n + v, 0); return Number.isFinite(total) ? total : null; };
365
+ const knownEstimated = moneySum(rows.map((r) => r.estimatedCostUsd).filter((n): n is number => n !== null));
366
+ const pricingComplete = rows.length > 0 && rows.every((r) => r.pricingKnown) && totalComplete;
367
+ const conservation = { status: quantitativeDefect ? 'DEFECT' : totalComplete ? 'BALANCED' : 'INSUFFICIENT_DATA', scope: 'reported receipt attribution; not independent source verification', metric };
368
+ const dimensionCoverage = Object.fromEntries(tokenFields.map((key) => [key, { known: rows.filter((r) => r[key] !== null).length, unknown: rows.filter((r) => r[key] === null).length + expectedMissing.length }]));
369
+ const routing = projectRoutingProvenance(input);
370
+ return { routingProvenance: routing.report, schema: 'stage-usage-1', sourceKind: input.sourceKind, sourcePath: input.sourcePath, runId: input.runId, metric: compatible ? metric : 'incompatible-metrics',
371
+ rows: rows.map(row => ({ ...row, ...(routing.stageFields.get(row.evidenceKey ?? '') ?? { plannedModel: null, plannedModelSource: 'not-recorded', probeId: null }) })), verdict: conservation.status, complete: totalComplete && witnessComplete && pricingComplete,
372
+ knownRunTotalTokens: known, knownAccountedTokens: accounted, knownUnaccountedTokens: unaccounted,
373
+ stageTokensSum: accounted !== null && doubled !== null ? accounted + doubled : null, doubleAttributedTokens: doubled,
374
+ runTotalTokens: totalComplete ? known : null, sourceVerifiedTotalTokens: witnessComplete && totalComplete ? known : null,
375
+ conservation, reconciliation: conservation, inventory: { status: inventoryComplete ? 'complete' : expected === null ? 'unavailable' : 'incomplete', expected: expected?.size ?? null, missing: expectedMissing, observed: rows.length },
376
+ sourceVerification, dimensionCoverage, pricingCoverage: { complete: pricingComplete, unknown: rows.filter((r) => !r.pricingKnown).length },
377
+ estimatedCostUsd: pricingComplete ? knownEstimated : null, knownEstimatedCostUsd: knownEstimated,
378
+ familyEstimatedCostUsd: rows.length > 0 && rows.every((r) => r.familyEstimatedCostUsd !== null) ? moneySum(rows.map((r) => r.familyEstimatedCostUsd!)) : null,
379
+ knownFamilyEstimatedCostUsd: moneySum(rows.map((r) => r.familyEstimatedCostUsd).filter((v): v is number => v !== null)),
380
+ moneyObservations, reportedCostCoverage, knownReportedCostUsd: Number.isFinite(knownReported) ? knownReported : null,
381
+ reportedCostUsd: reportedCostCoverage.status === 'complete' ? knownReported : null,
382
+ billedCostUsd: null, billedCostReason: 'not-observed', diagnostics: [...new Set(diagnostics)],
383
+ metrics: Object.fromEntries(bases.map((basis) => [basis, { knownSubtotal: sum(rows.filter((r) => r.reportedTotalBasis === basis).map((r) => r.tokensTotal).filter((v): v is number => v !== null)) }])),
384
+ scope: 'observed local receipts; static estimates are not current prices or billed amounts' };
385
+ }
package/src/statusline.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  * @packageDocumentation
15
15
  */
16
16
 
17
- import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
17
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync, appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
18
18
  import { basename, join, resolve } from 'node:path';
19
19
  import { createRequire } from 'node:module';
20
20
 
@@ -165,6 +165,154 @@ export function featureAdrStatePath(projectRoot: string, slug?: string): string
165
165
  : join(featureAdrStateDir(projectRoot), `${featureAdrStateSlug(slug)}.json`);
166
166
  }
167
167
 
168
+ /** Exact content selectors; slot filenames alone never establish run identity. */
169
+ export interface FeatureAdrSelector {
170
+ readonly slug?: string;
171
+ readonly runId?: string;
172
+ }
173
+
174
+ /** Diagnostic observation, separate from the legacy active-only statusline DTO. */
175
+ export interface FeatureAdrObservation {
176
+ readonly status: 'missing' | 'fresh' | 'stale' | 'expired' | 'completed' | 'unreadable' | 'limited-search';
177
+ readonly state?: Omit<FeatureAdrState, 'pool' | 'recalled' | 'stored'> & {
178
+ readonly pool?: number;
179
+ readonly recalled?: number;
180
+ readonly stored?: number;
181
+ };
182
+ readonly ageMs?: number;
183
+ readonly reason?: string;
184
+ readonly limitedSearch?: boolean;
185
+ }
186
+
187
+ /**
188
+ * Read bounded, regular local slots without writing or borrowing a different selected run.
189
+ * A deliberate symlink project root is resolved once; state ancestors/slots cannot be symlinks.
190
+ * These checks prevent accidental escapes/blocking files, not hostile concurrent replacement.
191
+ */
192
+ export function readFeatureAdrObservation(
193
+ projectRoot: string,
194
+ selector: FeatureAdrSelector = {},
195
+ now: number = Date.now(),
196
+ ): FeatureAdrObservation {
197
+ const failure = (reason: string): FeatureAdrObservation => ({ status: 'unreadable', reason });
198
+ const missing = (): FeatureAdrObservation => ({ status: 'missing' });
199
+ const absent = (error: unknown): boolean => (error as { code?: string })?.code === 'ENOENT';
200
+ const limit = 256 * 1024;
201
+ let root: string;
202
+ try {
203
+ root = realpathSync(resolve(projectRoot));
204
+ for (const path of [join(root, '.dz'), join(root, '.dz', 'feature-adr'), featureAdrStateDir(root)]) {
205
+ try {
206
+ const stat = lstatSync(path);
207
+ if (stat.isSymbolicLink() || !stat.isDirectory()) return failure('state ancestor is not a regular directory');
208
+ } catch (error) { if (!absent(error)) return failure('state directory unavailable'); }
209
+ }
210
+ } catch (error) { return absent(error) ? missing() : failure('project root unavailable'); }
211
+
212
+ const read = (path: string): FeatureAdrObservation => {
213
+ let fd: number | undefined;
214
+ try {
215
+ const stat = lstatSync(path);
216
+ if (!stat.isFile() || stat.isSymbolicLink()) return failure('slot is not a regular file');
217
+ if (stat.size > limit) return failure('slot exceeds 256 KiB');
218
+ // NONBLOCK also keeps a replacement FIFO from blocking between lstat and open.
219
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
220
+ const opened = fstatSync(fd);
221
+ if (!opened.isFile() || opened.size > limit) return failure('slot is not a bounded regular file');
222
+ const buffer = Buffer.alloc(limit + 1);
223
+ let bytes = 0;
224
+ while (bytes <= limit) {
225
+ const count = readSync(fd, buffer, bytes, buffer.length - bytes, null);
226
+ if (count === 0) break;
227
+ bytes += count;
228
+ if (bytes > limit) return failure('slot exceeds 256 KiB');
229
+ }
230
+ const value: unknown = JSON.parse(buffer.subarray(0, bytes).toString('utf8'));
231
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return failure('invalid slot object');
232
+ const parsed = value as Record<string, unknown>;
233
+ if (typeof parsed['slug'] !== 'string' || parsed['slug'].trim() === ''
234
+ || typeof parsed['step'] !== 'string' || parsed['step'].trim() === ''
235
+ || typeof parsed['ts'] !== 'string') return failure('invalid slot identity or timestamp');
236
+ const tsMs = Date.parse(parsed['ts']);
237
+ if (!Number.isFinite(now) || !Number.isFinite(tsMs) || tsMs > now) return failure('invalid or future report timestamp');
238
+ for (const field of ['pool', 'recalled', 'stored', 'reinforced']) {
239
+ const count = parsed[field];
240
+ if (count !== undefined && (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0)) {
241
+ return failure(`invalid ${field} counter`);
242
+ }
243
+ }
244
+ for (const field of ['runId', 'mode', 'tier', 'phaseStartTs']) {
245
+ if (parsed[field] !== undefined && (typeof parsed[field] !== 'string' || (parsed[field] as string).trim() === '')) {
246
+ return failure(`invalid ${field}`);
247
+ }
248
+ }
249
+ if (parsed['tier'] !== undefined && !FEATURE_ADR_TIERS.has(parsed['tier'] as string)) return failure('invalid tier');
250
+ if (parsed['kind'] !== undefined && parsed['kind'] !== 'feature-adr' && parsed['kind'] !== 'loop') return failure('invalid producer kind');
251
+ if (typeof parsed['phaseStartTs'] === 'string') {
252
+ const start = Date.parse(parsed['phaseStartTs']);
253
+ if (!Number.isFinite(start) || start > tsMs) return failure('invalid phase start timestamp');
254
+ }
255
+ const state: NonNullable<FeatureAdrObservation['state']> = {
256
+ slug: parsed['slug'], step: parsed['step'], ts: parsed['ts'],
257
+ kind: parsed['kind'] === 'loop' ? 'loop' : 'feature-adr',
258
+ ...(parsed['pool'] === undefined ? {} : { pool: parsed['pool'] as number }),
259
+ ...(parsed['recalled'] === undefined ? {} : { recalled: parsed['recalled'] as number }),
260
+ ...(parsed['stored'] === undefined ? {} : { stored: parsed['stored'] as number }),
261
+ ...(parsed['reinforced'] === undefined ? {} : { reinforced: parsed['reinforced'] as number }),
262
+ ...(parsed['runId'] === undefined ? {} : { runId: parsed['runId'] as string }),
263
+ ...(parsed['mode'] === undefined ? {} : { mode: parsed['mode'] as string }),
264
+ ...(parsed['tier'] === undefined ? {} : { tier: parsed['tier'] as string }),
265
+ ...(parsed['phaseStartTs'] === undefined ? {} : { phaseStartTs: parsed['phaseStartTs'] as string }),
266
+ };
267
+ const ageMs = now - tsMs;
268
+ const status = state.step.trim() === 'done' ? 'completed'
269
+ : ageMs >= FEATURE_ADR_FRESH_MS ? 'expired' : ageMs >= FEATURE_ADR_WARN_MS ? 'stale' : 'fresh';
270
+ return { status, state, ageMs };
271
+ } catch (error) { return absent(error) ? missing() : failure('slot unreadable or invalid JSON'); }
272
+ finally { if (fd !== undefined) closeSync(fd); }
273
+ };
274
+ const matches = (observation: FeatureAdrObservation): boolean => observation.state !== undefined
275
+ && (selector.slug === undefined || observation.state.slug === selector.slug)
276
+ && (selector.runId === undefined || observation.state.runId === selector.runId);
277
+ if (selector.slug !== undefined) {
278
+ const direct = read(featureAdrStatePath(root, selector.slug));
279
+ if (direct.status !== 'missing') return direct.status === 'unreadable' ? direct : matches(direct) ? direct : missing();
280
+ const legacy = read(featureAdrStatePath(root));
281
+ return legacy.status === 'unreadable' ? legacy : matches(legacy) ? legacy : missing();
282
+ }
283
+
284
+ const candidates: Array<{ path: string; mtime: number }> = [];
285
+ try {
286
+ const legacy = featureAdrStatePath(root);
287
+ try { candidates.push({ path: legacy, mtime: lstatSync(legacy).mtimeMs }); }
288
+ catch (error) { if (!absent(error)) return failure('legacy slot unavailable'); }
289
+ let names: string[] = [];
290
+ try { names = readdirSync(featureAdrStateDir(root)); }
291
+ catch (error) { if (!absent(error)) return failure('state discovery unavailable'); }
292
+ for (const name of names) {
293
+ if (!name.endsWith('.json')) continue;
294
+ const path = join(featureAdrStateDir(root), name);
295
+ let mtime = -Infinity;
296
+ try { mtime = lstatSync(path).mtimeMs; } catch { /* read reports a racing entry */ }
297
+ candidates.push({ path, mtime });
298
+ }
299
+ } catch { return failure('state discovery unavailable'); }
300
+ candidates.sort((a, b) => b.mtime - a.mtime || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
301
+ const limitedSearch = candidates.length > 64;
302
+ const observations = candidates.slice(0, 64).map(({ path }) => read(path));
303
+ const eligible = observations.filter(matches);
304
+ if (eligible.length > 0) {
305
+ eligible.sort((a, b) => {
306
+ const rank = (o: FeatureAdrObservation): number => (o.status === 'fresh' || o.status === 'stale')
307
+ ? o.state?.kind === 'loop' ? 1 : 2 : 0;
308
+ return rank(b) - rank(a) || (a.ageMs ?? Infinity) - (b.ageMs ?? Infinity);
309
+ });
310
+ return { ...eligible[0]!, ...(limitedSearch ? { limitedSearch: true } : {}) };
311
+ }
312
+ if (limitedSearch) return { status: 'limited-search', reason: 'only 64 candidates searched', limitedSearch: true };
313
+ return observations.find((o) => o.status === 'unreadable') ?? missing();
314
+ }
315
+
168
316
  /**
169
317
  * Freshness window for the `/feature-adr` panel: a run older than this is considered finished, so
170
318
  * its state must NOT keep showing a stale panel in the status bar. 90 minutes (in ms).