@gobing-ai/spur 0.3.95 → 0.3.96

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 (155) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/config/plugin-scripts.json +0 -54
  3. package/config/rules/boundary/sp-script-placement.yaml +19 -0
  4. package/config/rules/strict/runtime-boundaries.yaml +5 -0
  5. package/config/rules/structure/test-location.yaml +2 -0
  6. package/config/rules/typescript/no-syscall-emulation-in-boundary-mock.yaml +1 -1
  7. package/config/rules/typescript/output-boundaries.yaml +15 -2
  8. package/config/script-placement-baseline.json +51 -0
  9. package/config/workflows/feature-verification.yaml +1 -1
  10. package/config/workflows/history-anatomy.yaml +23 -11
  11. package/config/workflows/idea-pipeline.yaml +80 -85
  12. package/config/workflows/pr-review.yaml +18 -9
  13. package/config/workflows/task-pipeline.yaml +42 -95
  14. package/config/workflows/wrapup-pipeline.yaml +89 -37
  15. package/package.json +1 -1
  16. package/plugins/sp/README.md +8 -10
  17. package/plugins/sp/agents/super-reviewer.md +43 -18
  18. package/plugins/sp/commands/dev-fixgha.md +83 -0
  19. package/plugins/sp/commands/dev-gitmsg.md +8 -6
  20. package/plugins/sp/commands/dev-gtd.md +2 -2
  21. package/plugins/sp/commands/dev-idea.md +22 -12
  22. package/plugins/sp/commands/dev-plan.md +8 -9
  23. package/plugins/sp/commands/dev-review.md +22 -13
  24. package/plugins/sp/commands/dev-verifyall.md +1 -1
  25. package/plugins/sp/commands/spur-init.md +2 -2
  26. package/plugins/sp/lib/history-anatomy.generated.d.mts +112 -0
  27. package/plugins/sp/lib/history-anatomy.generated.mjs +686 -0
  28. package/plugins/sp/lib/idea-handoff.generated.mjs +5 -4
  29. package/plugins/sp/lib/inline-run.generated.d.mts +11 -0
  30. package/plugins/sp/lib/inline-run.generated.mjs +25 -8
  31. package/plugins/sp/lib/quality-gate.generated.d.mts +104 -0
  32. package/plugins/sp/lib/quality-gate.generated.mjs +438 -0
  33. package/plugins/sp/lib/residual-scan.generated.d.mts +62 -0
  34. package/plugins/sp/lib/residual-scan.generated.mjs +210 -0
  35. package/plugins/sp/lib/spur-bin.ts +36 -0
  36. package/plugins/sp/lib/step-profile.generated.d.mts +71 -0
  37. package/plugins/sp/lib/step-profile.generated.mjs +174 -0
  38. package/plugins/sp/plugin.json +1 -1
  39. package/plugins/sp/references/roles.md +1 -1
  40. package/plugins/sp/scripts/history-anatomy-cache.mjs +20 -19
  41. package/plugins/sp/scripts/history-anatomy-cache.ts +23 -928
  42. package/plugins/sp/scripts/inline-run-setup.mjs +85 -320
  43. package/plugins/sp/scripts/inline-run-setup.ts +104 -667
  44. package/plugins/sp/scripts/quality-gate.mjs +34 -19
  45. package/plugins/sp/scripts/quality-gate.ts +12 -658
  46. package/plugins/sp/scripts/residual-scan.mjs +135 -156
  47. package/plugins/sp/scripts/residual-scan.ts +102 -499
  48. package/plugins/sp/scripts/script-root.mjs +5 -1
  49. package/plugins/sp/scripts/script-root.ts +5 -1
  50. package/plugins/sp/scripts/workflow-step-profile.mjs +25 -17
  51. package/plugins/sp/scripts/workflow-step-profile.ts +21 -315
  52. package/plugins/sp/scripts/wrapup-drift-probe.mjs +8 -2
  53. package/plugins/sp/scripts/wrapup-drift-probe.ts +3 -2
  54. package/plugins/sp/scripts/wrapup-steps.mjs +10 -32
  55. package/plugins/sp/scripts/wrapup-steps.ts +8 -36
  56. package/plugins/sp/skills/code-improvement/SKILL.md +5 -4
  57. package/plugins/sp/skills/code-verification/SKILL.md +34 -9
  58. package/plugins/sp/skills/code-verification/references/verdict-schema.md +3 -3
  59. package/plugins/sp/skills/functional-review/SKILL.md +7 -4
  60. package/plugins/sp/skills/functional-review/references/verdict-schema.md +1 -1
  61. package/plugins/sp/skills/history-anatomy/references/modes.md +2 -1
  62. package/plugins/sp/skills/next-feature/references/handoff-routing.md +1 -1
  63. package/plugins/sp/skills/next-router/references/routing-table.md +1 -1
  64. package/plugins/sp/skills/spur-cli/SKILL.md +3 -3
  65. package/plugins/sp/skills/spur-cli/references/agent.md +10 -10
  66. package/plugins/sp/skills/spur-cli/references/features.md +17 -6
  67. package/plugins/sp/skills/spur-cli/references/init.md +17 -16
  68. package/plugins/sp/skills/spur-cli/references/self.md +3 -2
  69. package/plugins/sp/skills/spur-cli/references/serve.md +10 -10
  70. package/plugins/sp/skills/spur-cli/references/tasks/verbs.md +21 -6
  71. package/plugins/sp/skills/spur-cli/references/tasks.md +14 -8
  72. package/plugins/sp/skills/spur-dev/references/ac-style-guide.md +4 -3
  73. package/plugins/sp/skills/spur-dev/references/cross-cutting.md +11 -9
  74. package/plugins/sp/skills/spur-dev/references/decision-brief.md +1 -1
  75. package/plugins/sp/skills/spur-dev/references/dev-operations.md +86 -70
  76. package/plugins/sp/skills/spur-dev/references/done-housekeeping.md +3 -3
  77. package/plugins/sp/skills/spur-dev/references/execution-batch.md +77 -34
  78. package/plugins/sp/skills/spur-dev/references/execution-workflow.md +5 -9
  79. package/plugins/sp/skills/spur-dev/references/feature-link-helper.md +3 -3
  80. package/plugins/sp/skills/spur-dev/references/flag-glossary.md +31 -21
  81. package/plugins/sp/skills/spur-dev/references/gate-checklists.md +19 -19
  82. package/plugins/sp/skills/spur-dev/references/idea-evaluation.md +4 -3
  83. package/plugins/sp/skills/spur-dev/references/inline-pipeline-driver.md +29 -3
  84. package/plugins/sp/skills/spur-doctor/SKILL.md +1 -1
  85. package/plugins/sp/skills/sys-architecture/SKILL.md +3 -2
  86. package/spur.js +1495 -369
  87. package/web/_astro/{BoardApp.Cpxntzad.js → BoardApp.BIjMatT1.js} +1 -1
  88. package/web/_astro/{BoardApp.BxJuwD7I.js → BoardApp.GvjIe9Z6.js} +42 -42
  89. package/web/_astro/{TaskDetail.C5bW4WGV.js → TaskDetail.BZM3EAFx.js} +1 -1
  90. package/web/_astro/{arc.CyjRvNMY.js → arc.HkRiZnoI.js} +1 -1
  91. package/web/_astro/{architectureDiagram-3BPJPVTR.B4lWRzJA.js → architectureDiagram-3BPJPVTR.BDdK-tgZ.js} +1 -1
  92. package/web/_astro/{blockDiagram-GPEHLZMM.Be38USQ2.js → blockDiagram-GPEHLZMM.CZ9kOBxx.js} +1 -1
  93. package/web/_astro/{c4Diagram-AAUBKEIU.DT9Fj5Qx.js → c4Diagram-AAUBKEIU.DXK9qeRD.js} +1 -1
  94. package/web/_astro/channel.DlhX2MEt.js +1 -0
  95. package/web/_astro/{chunk-2J33WTMH.SeSBWLg5.js → chunk-2J33WTMH.BTD2WeX5.js} +1 -1
  96. package/web/_astro/{chunk-4BX2VUAB.DoO4VE14.js → chunk-4BX2VUAB.Ci6Qbcvk.js} +1 -1
  97. package/web/_astro/{chunk-55IACEB6.DrmTFA53.js → chunk-55IACEB6.yl3zsj7p.js} +1 -1
  98. package/web/_astro/{chunk-727SXJPM.Bi-TUb_V.js → chunk-727SXJPM.ClXZsfyR.js} +1 -1
  99. package/web/_astro/{chunk-AQP2D5EJ.B-xp8Uhi.js → chunk-AQP2D5EJ.BmKWZBcP.js} +1 -1
  100. package/web/_astro/{chunk-FMBD7UC4.DGWrDnUU.js → chunk-FMBD7UC4.By30fcb7.js} +1 -1
  101. package/web/_astro/{chunk-ND2GUHAM._BagvPDy.js → chunk-ND2GUHAM.24NmrD-k.js} +1 -1
  102. package/web/_astro/{chunk-QZHKN3VN.VOboYWQ0.js → chunk-QZHKN3VN.BN4sKdcS.js} +1 -1
  103. package/web/_astro/{classDiagram-4FO5ZUOK.D_apfHS7.js → classDiagram-4FO5ZUOK.CJpoMPb5.js} +1 -1
  104. package/web/_astro/{classDiagram-v2-Q7XG4LA2.D_apfHS7.js → classDiagram-v2-Q7XG4LA2.CJpoMPb5.js} +1 -1
  105. package/web/_astro/{cose-bilkent-S5V4N54A.DNLU_L-x.js → cose-bilkent-S5V4N54A.BraxQ2Nt.js} +1 -1
  106. package/web/_astro/{cynefin-OW5HDTMX.D8borhV-.js → cynefin-OW5HDTMX.gzoU73oL.js} +1 -1
  107. package/web/_astro/{dagre-BM42HDAG.Uc0lvjcV.js → dagre-BM42HDAG.wyDfWySU.js} +1 -1
  108. package/web/_astro/{diagram-2AECGRRQ.DDIxtDBo.js → diagram-2AECGRRQ.h2_EbMxV.js} +1 -1
  109. package/web/_astro/{diagram-5GNKFQAL.DVoDnD3H.js → diagram-5GNKFQAL.Db6dcs89.js} +1 -1
  110. package/web/_astro/{diagram-KO2AKTUF.CRubTJ-0.js → diagram-KO2AKTUF.NVwzxu_U.js} +1 -1
  111. package/web/_astro/{diagram-LMA3HP47.m9SeYcXQ.js → diagram-LMA3HP47.B-eNgDQk.js} +1 -1
  112. package/web/_astro/{diagram-OG6HWLK6.C6s2ZjV5.js → diagram-OG6HWLK6.Bsa8ZRbJ.js} +1 -1
  113. package/web/_astro/{erDiagram-TEJ5UH35.nSzr5KTj.js → erDiagram-TEJ5UH35.BospRE5Q.js} +1 -1
  114. package/web/_astro/{flowDiagram-I6XJVG4X.DrZcys16.js → flowDiagram-I6XJVG4X.DMzvHwAA.js} +1 -1
  115. package/web/_astro/{ganttDiagram-6RSMTGT7.Do4M1b-K.js → ganttDiagram-6RSMTGT7.Dmdxgd-M.js} +1 -1
  116. package/web/_astro/{gitGraphDiagram-PVQCEYII.BWc9oJ4l.js → gitGraphDiagram-PVQCEYII.CaqdO0rL.js} +1 -1
  117. package/web/_astro/index.EoZlzLK-.css +1 -0
  118. package/web/_astro/{infoDiagram-5YYISTIA.BIdOctFk.js → infoDiagram-5YYISTIA.DDVD9Wn7.js} +1 -1
  119. package/web/_astro/{ishikawaDiagram-YF4QCWOH.CV5SuG2t.js → ishikawaDiagram-YF4QCWOH.EKyCUFsL.js} +1 -1
  120. package/web/_astro/{journeyDiagram-JHISSGLW.CxE-rEJ-.js → journeyDiagram-JHISSGLW.By2-RkYB.js} +1 -1
  121. package/web/_astro/{kanban-definition-UN3LZRKU.BPRdKWs_.js → kanban-definition-UN3LZRKU.ar-WmlyR.js} +1 -1
  122. package/web/_astro/{linear.zRsuuDTE.js → linear.BnzMBgo_.js} +1 -1
  123. package/web/_astro/{mermaid.core.jAJTcMKc.js → mermaid.core.DSqeFu2Y.js} +4 -4
  124. package/web/_astro/{mindmap-definition-RKZ34NQL.BffJxfCr.js → mindmap-definition-RKZ34NQL.1XcF8Wh2.js} +1 -1
  125. package/web/_astro/{pieDiagram-4H26LBE5.CacwWaE3.js → pieDiagram-4H26LBE5.DnItHOdK.js} +1 -1
  126. package/web/_astro/{quadrantDiagram-W4KKPZXB.hXELD06-.js → quadrantDiagram-W4KKPZXB.BQQyrnBt.js} +1 -1
  127. package/web/_astro/{requirementDiagram-4Y6WPE33.DdEbPcqT.js → requirementDiagram-4Y6WPE33.Dmzxun82.js} +1 -1
  128. package/web/_astro/{sankeyDiagram-5OEKKPKP.DgaDocKv.js → sankeyDiagram-5OEKKPKP.BBIeRKYB.js} +1 -1
  129. package/web/_astro/{sequenceDiagram-3UESZ5HK.B0KScnAu.js → sequenceDiagram-3UESZ5HK.CUNVdBBf.js} +1 -1
  130. package/web/_astro/{stateDiagram-AJRCARHV.CV9M_WNc.js → stateDiagram-AJRCARHV.DlFf2sJm.js} +1 -1
  131. package/web/_astro/{stateDiagram-v2-BHNVJYJU.BOAo74Et.js → stateDiagram-v2-BHNVJYJU.DXR7I1H5.js} +1 -1
  132. package/web/_astro/{timeline-definition-PNZ67QCA.CqqepUMe.js → timeline-definition-PNZ67QCA.BcO-GyX2.js} +1 -1
  133. package/web/_astro/{vennDiagram-CIIHVFJN.DDqe4dOG.js → vennDiagram-CIIHVFJN.ChCECmmW.js} +1 -1
  134. package/web/_astro/{wardleyDiagram-YWT4CUSO.B3R9OPdO.js → wardleyDiagram-YWT4CUSO.CRaT12mD.js} +1 -1
  135. package/web/_astro/{xychartDiagram-2RQKCTM6.B3SvgXpQ.js → xychartDiagram-2RQKCTM6.B3lsHVpj.js} +1 -1
  136. package/web/index.html +2 -2
  137. package/plugins/sp/lib/artifact-digest.generated.d.mts +0 -7
  138. package/plugins/sp/lib/artifact-digest.generated.mjs +0 -48
  139. package/plugins/sp/scripts/feature-sync-bounded.mjs +0 -301
  140. package/plugins/sp/scripts/feature-sync-bounded.ts +0 -481
  141. package/plugins/sp/scripts/idea-coverage-check.ts +0 -168
  142. package/plugins/sp/scripts/inline-pipeline-parity-check.ts +0 -298
  143. package/plugins/sp/scripts/record-feature-sync.mjs +0 -63
  144. package/plugins/sp/scripts/record-feature-sync.ts +0 -84
  145. package/plugins/sp/scripts/script-contract-check.ts +0 -506
  146. package/plugins/sp/scripts/stage-registry-adapter.ts +0 -1533
  147. package/plugins/sp/scripts/surface-drift-inventory.ts +0 -989
  148. package/plugins/sp/scripts/task-evidence-precheck.ts +0 -189
  149. package/plugins/sp/scripts/task-size-precheck.ts +0 -212
  150. package/plugins/sp/scripts/transition-shim-check.ts +0 -238
  151. package/plugins/sp/scripts/validate-commands.ts +0 -689
  152. package/plugins/sp/scripts/validate-flag-contracts.ts +0 -890
  153. package/plugins/sp/scripts/verify-answer-lint.ts +0 -549
  154. package/web/_astro/channel.CI6N_tCg.js +0 -1
  155. package/web/_astro/index.CENnIEqT.css +0 -1
@@ -0,0 +1,686 @@
1
+ // packages/app/src/services/history-anatomy.ts
2
+ import { createHash as createHash2 } from "node:crypto";
3
+ import {
4
+ closeSync,
5
+ existsSync,
6
+ fsyncSync,
7
+ openSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ renameSync,
11
+ rmSync,
12
+ statSync,
13
+ writeFileSync
14
+ } from "node:fs";
15
+ import { join } from "node:path";
16
+
17
+ // packages/domain/src/analytics/artifact-digest.ts
18
+ import { createHash } from "node:crypto";
19
+ var ARTIFACT_ARRAY_CLASSIFICATION = {
20
+ byTool: "ranked",
21
+ bySession: "ranked",
22
+ topStepsByTokens: "ranked",
23
+ topStepsByDuration: "ranked",
24
+ topSteps: "ranked",
25
+ bottlenecks: "ranked",
26
+ coverage: "set",
27
+ daily: "set",
28
+ loops: "set",
29
+ warnings: "set",
30
+ pairings: "set",
31
+ ladderSnapshot: "set",
32
+ stepSupport: "set",
33
+ phases: "set",
34
+ tools: "set",
35
+ skills: "set",
36
+ sources: "set",
37
+ models: "set"
38
+ };
39
+ var RANKED_ARTIFACT_KEYS = new Set(Object.entries(ARTIFACT_ARRAY_CLASSIFICATION).filter(([, kind]) => kind === "ranked").map(([key]) => key));
40
+ function canonicalize(value, key) {
41
+ if (key === "generatedAt" || key === "validatedAt" || key === "baselineArtifactDigest")
42
+ return null;
43
+ if (Array.isArray(value)) {
44
+ const raw = value.map((v) => JSON.stringify(canonicalize(v, "")));
45
+ return RANKED_ARTIFACT_KEYS.has(key) ? raw : [...raw].sort();
46
+ }
47
+ if (value !== null && typeof value === "object") {
48
+ const out = {};
49
+ for (const k of Object.keys(value).sort()) {
50
+ out[k] = canonicalize(value[k], k);
51
+ }
52
+ return out;
53
+ }
54
+ return value;
55
+ }
56
+ function semanticArtifactDigest(artifactJson) {
57
+ const material = JSON.stringify(canonicalize(artifactJson, "root"));
58
+ return createHash("sha256").update(material).digest("hex");
59
+ }
60
+
61
+ // packages/app/src/services/history-anatomy.ts
62
+ var REPORT_SECTIONS = [
63
+ "Scope and provenance",
64
+ "Executive summary",
65
+ "Baseline comparison",
66
+ "Findings",
67
+ "Recurrence ledger",
68
+ "Telemetry gaps",
69
+ "Remediation options",
70
+ "Performance analysis",
71
+ "Workflow and process improvements",
72
+ "Report-only advisories",
73
+ "Positive patterns",
74
+ "Evidence ledger"
75
+ ];
76
+ var FINDING_FIELDS = [
77
+ "key",
78
+ "category",
79
+ "impact",
80
+ "trend",
81
+ "observation",
82
+ "inference",
83
+ "confidence",
84
+ "contradictions",
85
+ "evidenceAnchor",
86
+ "severity",
87
+ "reproCommand",
88
+ "ownerSurface"
89
+ ];
90
+ function parseScalar(raw) {
91
+ const t = raw.trim();
92
+ if (t.startsWith('"') && t.endsWith('"'))
93
+ return t.slice(1, -1).replaceAll("\\\"", '"');
94
+ if (t === "null")
95
+ return null;
96
+ return t;
97
+ }
98
+ function parseBlock(text) {
99
+ const obj = {};
100
+ const lines = text.split(`
101
+ `);
102
+ for (let i = 0;i < lines.length; i++) {
103
+ const line = lines[i] ?? "";
104
+ if (/^\s*$/.test(line) || /^\s*#/.test(line) || /^-\s+/.test(line.trim()))
105
+ continue;
106
+ const indent = line.search(/\S/);
107
+ const eq = line.indexOf(":");
108
+ if (eq === -1)
109
+ continue;
110
+ const key = line.slice(0, eq).trim();
111
+ const val = parseScalar(line.slice(eq + 1).trim());
112
+ let consumed = 0;
113
+ const next = lines[i + 1];
114
+ if ((val === "" || val === undefined) && /^\s*-\s+/.test(next ?? "")) {
115
+ const items = [];
116
+ let j = i + 1;
117
+ while (j < lines.length && /^\s*-\s+/.test(lines[j] ?? "")) {
118
+ const entry = {};
119
+ for (const part of (lines[j] ?? "").trim().replace(/^-\s+/, "").split(",")) {
120
+ const e = part.indexOf(":");
121
+ if (e === -1)
122
+ continue;
123
+ entry[part.slice(0, e).trim()] = parseScalar(part.slice(e + 1).trim());
124
+ }
125
+ items.push(entry);
126
+ j++;
127
+ }
128
+ obj[key] = items;
129
+ consumed = j - i - 1;
130
+ } else if (val === "" || val === undefined) {
131
+ const block = [];
132
+ let j = i + 1;
133
+ while (j < lines.length) {
134
+ const nl = lines[j] ?? "";
135
+ if (nl.trim() === "") {
136
+ block.push("");
137
+ j++;
138
+ continue;
139
+ }
140
+ const nind = nl.search(/\S/);
141
+ if (nind <= indent)
142
+ break;
143
+ block.push(nl);
144
+ j++;
145
+ }
146
+ obj[key] = parseBlock(block.join(`
147
+ `));
148
+ consumed = j - i - 1;
149
+ } else {
150
+ obj[key] = val;
151
+ }
152
+ i += consumed;
153
+ }
154
+ return obj;
155
+ }
156
+ function readSourceName(s) {
157
+ if (s !== null && typeof s === "object")
158
+ return String(s.source ?? "");
159
+ return String(s);
160
+ }
161
+ var DISPOSITIONS = ["hit", "miss", "forced-recompute"];
162
+ function optionalString(v) {
163
+ return v == null || v === "" ? undefined : String(v);
164
+ }
165
+ function parseProvenance(reportMarkdown) {
166
+ const match = reportMarkdown.match(/^---\n([\s\S]*?)\n---/);
167
+ if (match === null)
168
+ return null;
169
+ try {
170
+ const obj = parseBlock(match[1] ?? "");
171
+ const identity = obj.identity;
172
+ const coverage = obj.coverage;
173
+ if (identity === undefined || !Array.isArray(coverage))
174
+ return null;
175
+ const bounds = identity.bounds;
176
+ if (bounds === undefined || typeof bounds.since !== "string" || typeof bounds.until !== "string") {
177
+ return null;
178
+ }
179
+ return {
180
+ identity: {
181
+ contractVersion: String(identity.contractVersion ?? ""),
182
+ mode: identity.mode === "ad-hoc" ? "ad-hoc" : "daily",
183
+ date: String(identity.date ?? ""),
184
+ timezone: String(identity.timezone ?? ""),
185
+ bounds: { since: bounds.since, until: bounds.until },
186
+ sources: Array.isArray(identity.sources) ? identity.sources.map(readSourceName) : []
187
+ },
188
+ windowState: obj.windowState === "closed" ? "closed" : "provisional",
189
+ generatedAt: String(obj.generatedAt ?? ""),
190
+ validatedAt: String(obj.validatedAt ?? ""),
191
+ artifactDigest: String(obj.artifactDigest ?? ""),
192
+ baselineArtifactDigest: obj.baselineArtifactDigest == null ? null : String(obj.baselineArtifactDigest),
193
+ contractDigest: String(obj.contractDigest ?? ""),
194
+ skillDigest: String(obj.skillDigest ?? ""),
195
+ workflowDigest: String(obj.workflowDigest ?? ""),
196
+ helperDigest: String(obj.helperDigest ?? ""),
197
+ coverage: coverage.map((c) => ({
198
+ source: String(c.source ?? ""),
199
+ status: String(c.status ?? ""),
200
+ lastImportedAt: c.lastImportedAt == null ? null : String(c.lastImportedAt)
201
+ })),
202
+ runId: optionalString(obj.runId),
203
+ currentArtifactPath: optionalString(obj.currentArtifactPath),
204
+ baselineArtifactPath: obj.baselineArtifactPath == null ? null : String(obj.baselineArtifactPath),
205
+ spurVersion: optionalString(obj.spurVersion),
206
+ schemaVersion: obj.schemaVersion == null ? undefined : Number(obj.schemaVersion),
207
+ executor: optionalString(obj.executor),
208
+ model: optionalString(obj.model),
209
+ cacheDisposition: DISPOSITIONS.includes(obj.cacheDisposition) ? obj.cacheDisposition : undefined
210
+ };
211
+ } catch {
212
+ return null;
213
+ }
214
+ }
215
+ function decideCache(cached, current, opts) {
216
+ if (opts.recompute)
217
+ return { disposition: "forced-recompute", reasons: ["recompute"] };
218
+ if (cached === null)
219
+ return { disposition: "miss", reasons: ["no-cache"] };
220
+ const reasons = [];
221
+ const id = cached.identity;
222
+ const cur = current.identity;
223
+ if (id.contractVersion !== cur.contractVersion)
224
+ reasons.push("identity:contractVersion");
225
+ if (id.mode !== cur.mode)
226
+ reasons.push("identity:mode");
227
+ if (id.date !== cur.date)
228
+ reasons.push("identity:date");
229
+ if (id.timezone !== cur.timezone)
230
+ reasons.push("identity:timezone");
231
+ if (id.bounds.since !== cur.bounds.since || id.bounds.until !== cur.bounds.until)
232
+ reasons.push("identity:bounds");
233
+ if ([...id.sources].sort().join("\x00") !== [...cur.sources].sort().join("\x00"))
234
+ reasons.push("identity:sources");
235
+ if (cached.artifactDigest !== current.artifactDigest)
236
+ reasons.push("data-changed");
237
+ if (cached.contractDigest !== current.contractDigest)
238
+ reasons.push("logic-changed:contract");
239
+ if (cached.skillDigest !== current.skillDigest)
240
+ reasons.push("logic-changed:skill");
241
+ if (cached.workflowDigest !== current.workflowDigest)
242
+ reasons.push("logic-changed:workflow");
243
+ if (cached.helperDigest !== current.helperDigest)
244
+ reasons.push("logic-changed:helper");
245
+ const currentSources = new Set(current.coverage.map((c) => c.source));
246
+ if (cached.coverage.some((c) => !currentSources.has(c.source)))
247
+ reasons.push("coverage-degraded");
248
+ if (cached.windowState === "provisional" && opts.dayClosed)
249
+ reasons.push("window-closed");
250
+ return { disposition: reasons.length === 0 ? "hit" : "miss", reasons };
251
+ }
252
+ function escapeRe(s) {
253
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
254
+ }
255
+ var FINDING_CATEGORIES = [
256
+ "reliability",
257
+ "repetition",
258
+ "workflow",
259
+ "performance",
260
+ "coverage",
261
+ "telemetry",
262
+ "positive"
263
+ ];
264
+ function checkReportStructure(reportMarkdown) {
265
+ const problems = [];
266
+ if (/TODO|PLACEHOLDER|FIXME|^\|\s*\|/im.test(reportMarkdown))
267
+ problems.push("placeholder-or-todo-present");
268
+ let lastIdx = -1;
269
+ for (const section of REPORT_SECTIONS) {
270
+ const re = new RegExp(`^#{2,3}\\s+${escapeRe(section)}\\s*$`, "m");
271
+ const m = reportMarkdown.match(re);
272
+ if (m === null || (m.index ?? -1) <= lastIdx) {
273
+ problems.push(`section-missing-or-out-of-order:${section}`);
274
+ } else if (m.index !== undefined) {
275
+ lastIdx = m.index;
276
+ }
277
+ }
278
+ const findingsIdx = reportMarkdown.search(/^##\s+Findings\s*$/im);
279
+ if (findingsIdx !== -1) {
280
+ const tail = reportMarkdown.slice(findingsIdx);
281
+ const nextSection = tail.slice(1).search(/^##\s+/im);
282
+ const findingsBody = nextSection === -1 ? tail : tail.slice(0, nextSection + 1);
283
+ const catAlt = FINDING_CATEGORIES.join("|");
284
+ const knownRows = findingsBody.match(new RegExp(`^\\|\\s*(?:${catAlt}):[^|]+`, "gm")) ?? [];
285
+ const invalidRows = findingsBody.match(/^\|\s*([^|:\s][^|:]*):[^|]+/gm) ?? [];
286
+ for (const row of [...new Set([...knownRows, ...invalidRows])]) {
287
+ const seg = row.match(/^\|\s*([^:|]+):/)?.[1];
288
+ if (seg !== undefined && !FINDING_CATEGORIES.includes(seg.trim())) {
289
+ problems.push(`finding-invalid-key-category:${seg.trim()}`);
290
+ }
291
+ const rowLower = row.toLowerCase();
292
+ for (const field of FINDING_FIELDS) {
293
+ if (!rowLower.includes(field.toLowerCase()))
294
+ problems.push(`finding-missing-field:${field}`);
295
+ }
296
+ }
297
+ const blocks = findingsBody.split(/^###\s+/m).slice(1);
298
+ for (const block of blocks) {
299
+ if (!block.includes("`key`") && !/\|\s*key\s*:/.test(block))
300
+ continue;
301
+ for (const field of FINDING_FIELDS) {
302
+ if (!block.includes(field))
303
+ problems.push(`finding-missing-field:${field}`);
304
+ }
305
+ if (!/(^|[\s`])P[123]([\s`.]|$)/.test(block) && !block.includes("symbolic-severity")) {
306
+ problems.push("finding-invalid-severity");
307
+ }
308
+ const catValue = block.match(/`category`\s*[:=]\s*`?([^`\n]+?)`?\s*(?:\n|$)/)?.[1];
309
+ if (catValue && !FINDING_CATEGORIES.includes(catValue.trim())) {
310
+ problems.push(`finding-invalid-category:${catValue.trim()}`);
311
+ }
312
+ const keyValue = block.match(/`key`\s*[:=]\s*`?([^`\n]+?)`?\s*(?:\n|$)/)?.[1] ?? "";
313
+ const firstSegment = keyValue.split(":")[0]?.trim() ?? "";
314
+ if (keyValue !== "" && !FINDING_CATEGORIES.includes(firstSegment)) {
315
+ problems.push(`finding-invalid-key-category:${firstSegment}`);
316
+ }
317
+ }
318
+ }
319
+ const ledgerIdx = reportMarkdown.search(/^#{2,3}\s+Evidence\s+ledger/im);
320
+ if (ledgerIdx !== -1) {
321
+ const ledgerSection = reportMarkdown.slice(ledgerIdx);
322
+ const sep = ledgerSection.match(/^\|[\s:|-]+\|[ \t]*$/m);
323
+ const body = sep?.index === undefined ? ledgerSection : ledgerSection.slice(sep.index + sep[0].length);
324
+ const claimRows = body.match(/^[|>]\s+\S.*$/gm) ?? [];
325
+ for (const row of claimRows) {
326
+ const hasAnchor = /`[^`]+:\d+`|`[^`]+\.(md|ts|json)`|[a-z][a-z0-9_-]*\/[a-z][a-z0-9_./-]*:[0-9]+/i.test(row);
327
+ if (!hasAnchor) {
328
+ problems.push("evidence-claim-without-anchor");
329
+ break;
330
+ }
331
+ }
332
+ }
333
+ return { ok: problems.length === 0, problems };
334
+ }
335
+ var NOT_AVAILABLE = "not available";
336
+ function logicDigest(path) {
337
+ if (path === undefined || path === "" || !existsSync(path))
338
+ return NOT_AVAILABLE;
339
+ try {
340
+ const h = createHash2("sha256");
341
+ if (statSync(path).isDirectory()) {
342
+ const walk = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? walk(join(dir, e.name)) : /\.(md|ya?ml)$/.test(e.name) ? [join(dir, e.name)] : []).sort();
343
+ for (const f of walk(path)) {
344
+ h.update(f.slice(path.length));
345
+ h.update(readFileSync(f));
346
+ }
347
+ } else {
348
+ h.update(readFileSync(path));
349
+ }
350
+ return h.digest("hex");
351
+ } catch {
352
+ return NOT_AVAILABLE;
353
+ }
354
+ }
355
+ function importedSnapshotAsOf(coverage) {
356
+ const stamps = coverage.map((c) => c.lastImportedAt).filter((v) => typeof v === "string" && v !== "");
357
+ if (stamps.length === 0 || stamps.length !== coverage.length)
358
+ return NOT_AVAILABLE;
359
+ return [...stamps].sort()[0] ?? NOT_AVAILABLE;
360
+ }
361
+ function localDay(tz, at = new Date) {
362
+ try {
363
+ return new Intl.DateTimeFormat("en-CA", { timeZone: tz, dateStyle: "short" }).format(at);
364
+ } catch {
365
+ return at.toISOString().slice(0, 10);
366
+ }
367
+ }
368
+ function tzOffsetMs(tz, at) {
369
+ const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", {
370
+ timeZone: tz,
371
+ hour12: false,
372
+ year: "numeric",
373
+ month: "2-digit",
374
+ day: "2-digit",
375
+ hour: "2-digit",
376
+ minute: "2-digit",
377
+ second: "2-digit"
378
+ }).formatToParts(at).filter((p) => p.type !== "literal").map((p) => [p.type, p.value]));
379
+ const asUtc = Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), parts.hour === "24" ? 0 : Number(parts.hour), Number(parts.minute), Number(parts.second));
380
+ const atSec = Math.floor(at.getTime() / 1000) * 1000;
381
+ return asUtc - atSec;
382
+ }
383
+ function zonedDayStart(tz, ymd) {
384
+ const [y, m, d] = ymd.split("-").map(Number);
385
+ const utcMidnight = Date.UTC(y ?? 1970, (m ?? 1) - 1, d ?? 1);
386
+ const guess = new Date(utcMidnight - tzOffsetMs(tz, new Date(utcMidnight)));
387
+ return new Date(utcMidnight - tzOffsetMs(tz, guess));
388
+ }
389
+ function formatZonedIso(tz, at) {
390
+ const off = tzOffsetMs(tz, at);
391
+ const abs = Math.abs(off);
392
+ const pad = (n) => String(n).padStart(2, "0");
393
+ const offStr = `${off < 0 ? "-" : "+"}${pad(Math.floor(abs / 3600000))}:${pad(Math.floor(abs % 3600000 / 60000))}`;
394
+ return `${new Date(at.getTime() + off).toISOString().slice(0, 23)}${offStr}`;
395
+ }
396
+ function dayBounds(tz, ymd) {
397
+ const start = zonedDayStart(tz, ymd);
398
+ const nextYmd = localDay(tz, new Date(start.getTime() + 30 * 3600000));
399
+ return {
400
+ since: formatZonedIso(tz, start),
401
+ until: formatZonedIso(tz, new Date(zonedDayStart(tz, nextYmd).getTime() - 1))
402
+ };
403
+ }
404
+ function resolvePaths(opts) {
405
+ const m = opts.helper.match(/\/scripts\/(?:([^/]+)\/)?[^/]+$/);
406
+ const pluginRoot = m ? opts.helper.slice(0, m.index) : opts.helper;
407
+ const skill = `${pluginRoot}/skills/${m?.[1] ? `${m[1]}-history-anatomy` : "history-anatomy"}`;
408
+ const tz = opts.tz ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? "UTC";
409
+ const date = opts.date !== undefined && opts.date !== "" ? opts.date : localDay(tz, opts.now ?? new Date);
410
+ const target = opts.output !== undefined && opts.output !== "" ? opts.output : `${opts.reportDir}/${date}-history-anatomy.md`;
411
+ const adHoc = opts.mode === "ad-hoc" && !!opts.since && !!opts.until;
412
+ let env = `HA_HELPER=${opts.helper}
413
+ HA_SKILL=${skill}
414
+ HA_TARGET=${target}
415
+ HA_DATE=${date}
416
+ `;
417
+ if (adHoc) {
418
+ return `${env}HA_SINCE=${opts.since}
419
+ HA_UNTIL=${opts.until}
420
+ `;
421
+ }
422
+ const current = dayBounds(tz, date);
423
+ const baseline = dayBounds(tz, localDay(tz, new Date(zonedDayStart(tz, date).getTime() - 12 * 3600000)));
424
+ env += `HA_SINCE=${current.since}
425
+ HA_UNTIL=${current.until}
426
+ `;
427
+ env += `HA_BASELINE_SINCE=${baseline.since}
428
+ HA_BASELINE_UNTIL=${baseline.until}
429
+ `;
430
+ return env;
431
+ }
432
+ function isRealDate(ymd) {
433
+ const m = ymd.match(/^(\d{4})-(\d{2})-(\d{2})$/);
434
+ if (!m)
435
+ return false;
436
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
437
+ const dt = new Date(Date.UTC(y, mo - 1, d));
438
+ return dt.getUTCFullYear() === y && dt.getUTCMonth() === mo - 1 && dt.getUTCDate() === d;
439
+ }
440
+ function validateSelector(opts) {
441
+ const errors = [];
442
+ const has = (v) => v !== undefined && v !== "";
443
+ const val = (v) => has(v) ? v : null;
444
+ const mode = has(opts.mode) ? opts.mode : "daily";
445
+ if (mode !== "daily" && mode !== "ad-hoc") {
446
+ return { ok: false, errors: [`--mode must be "daily" or "ad-hoc", got "${opts.mode}"`] };
447
+ }
448
+ const recompute = opts.recompute ?? "";
449
+ if (recompute !== "" && recompute !== "true" && recompute !== "false") {
450
+ errors.push(`--recompute must be "true" or "false", got "${recompute}"`);
451
+ }
452
+ if (mode === "daily") {
453
+ for (const [flag, v] of [
454
+ ["--focus", opts.focus],
455
+ ["--since", opts.since],
456
+ ["--until", opts.until],
457
+ ["--output", opts.output]
458
+ ]) {
459
+ if (has(v))
460
+ errors.push(`daily mode rejects ${flag}`);
461
+ }
462
+ if (has(opts.date) && !isRealDate(opts.date)) {
463
+ errors.push(`--date must be a real YYYY-MM-DD calendar day, got "${opts.date}"`);
464
+ }
465
+ } else {
466
+ if (has(opts.date))
467
+ errors.push("ad-hoc mode rejects --date");
468
+ if (recompute === "true")
469
+ errors.push("ad-hoc mode rejects --recompute");
470
+ if (!has(opts.focus))
471
+ errors.push("ad-hoc mode requires a non-empty --focus");
472
+ const sinceOk = has(opts.since);
473
+ const untilOk = has(opts.until);
474
+ if (!sinceOk)
475
+ errors.push("ad-hoc mode requires --since (inclusive ISO instant)");
476
+ if (!untilOk)
477
+ errors.push("ad-hoc mode requires --until (inclusive ISO instant)");
478
+ if (sinceOk && untilOk) {
479
+ const since = new Date(opts.since ?? "");
480
+ const until = new Date(opts.until ?? "");
481
+ if (Number.isNaN(since.getTime()))
482
+ errors.push(`--since must be a parseable ISO instant, got "${opts.since}"`);
483
+ if (Number.isNaN(until.getTime()))
484
+ errors.push(`--until must be a parseable ISO instant, got "${opts.until}"`);
485
+ if (!Number.isNaN(since.getTime()) && !Number.isNaN(until.getTime()) && since.getTime() > until.getTime()) {
486
+ errors.push(`--since must not be after --until ("${opts.since}" > "${opts.until}")`);
487
+ }
488
+ }
489
+ }
490
+ if (errors.length)
491
+ return { ok: false, errors };
492
+ return {
493
+ ok: true,
494
+ mode,
495
+ date: val(opts.date),
496
+ focus: val(opts.focus),
497
+ since: val(opts.since),
498
+ until: val(opts.until)
499
+ };
500
+ }
501
+ function buildProvenance(opts) {
502
+ let raw;
503
+ try {
504
+ raw = JSON.parse(readFileSync(opts.artifact, "utf8"));
505
+ } catch (err) {
506
+ throw new Error(`could not parse fresh analyze artifact at ${opts.artifact}: ${err.message}`);
507
+ }
508
+ const coverage = (raw.coverage ?? []).map((c) => ({
509
+ source: String(c.source ?? ""),
510
+ status: String(c.status ?? ""),
511
+ lastImportedAt: c.lastImportedAt == null ? null : String(c.lastImportedAt)
512
+ }));
513
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone ?? "UTC";
514
+ const now = opts.now ?? new Date;
515
+ const date = opts.date !== undefined && opts.date !== "" ? opts.date : localDay(tz, now);
516
+ const windowState = opts.mode === "ad-hoc" || date < localDay(tz, now) ? "closed" : "provisional";
517
+ const nowIso = now.toISOString();
518
+ return {
519
+ identity: {
520
+ contractVersion: opts.contractVersion ?? "1",
521
+ mode: opts.mode,
522
+ date,
523
+ timezone: tz,
524
+ bounds: { since: String(raw.selector?.since ?? ""), until: String(raw.selector?.until ?? "") },
525
+ sources: coverage.map((c) => c.source).sort()
526
+ },
527
+ windowState,
528
+ generatedAt: nowIso,
529
+ validatedAt: nowIso,
530
+ artifactDigest: semanticArtifactDigest(raw),
531
+ baselineArtifactDigest: (() => {
532
+ if (!(opts.baseline !== undefined && existsSync(opts.baseline)))
533
+ return null;
534
+ try {
535
+ return semanticArtifactDigest(JSON.parse(readFileSync(opts.baseline, "utf8")));
536
+ } catch (err) {
537
+ throw new Error(`could not parse baseline artifact at ${opts.baseline}: ${err.message}`);
538
+ }
539
+ })(),
540
+ contractDigest: logicDigest(opts.contractFile),
541
+ skillDigest: logicDigest(opts.skillDir),
542
+ workflowDigest: logicDigest(opts.workflowFile),
543
+ helperDigest: logicDigest(opts.helperFile),
544
+ coverage,
545
+ runId: opts.runId,
546
+ currentArtifactPath: opts.artifact,
547
+ baselineArtifactPath: opts.baseline ?? null,
548
+ spurVersion: opts.spurVersion ?? NOT_AVAILABLE,
549
+ schemaVersion: typeof raw.schemaVersion === "number" ? raw.schemaVersion : undefined,
550
+ executor: opts.executor ?? NOT_AVAILABLE,
551
+ model: opts.model ?? NOT_AVAILABLE
552
+ };
553
+ }
554
+ function probe(opts) {
555
+ const current = buildProvenance(opts);
556
+ const cachedText = existsSync(opts.target) ? readFileSync(opts.target, "utf8") : null;
557
+ const cached = cachedText === null ? null : parseProvenance(cachedText);
558
+ const decision = opts.mode === "ad-hoc" ? { disposition: "miss", reasons: ["ad-hoc-never-cached"] } : decideCache(cached, current, {
559
+ recompute: opts.recompute,
560
+ dayClosed: current.windowState === "closed"
561
+ });
562
+ current.cacheDisposition = decision.disposition;
563
+ return { decision, current };
564
+ }
565
+ var YAML_KEYS = [
566
+ "windowState",
567
+ "generatedAt",
568
+ "validatedAt",
569
+ "artifactDigest",
570
+ "baselineArtifactDigest",
571
+ "contractDigest",
572
+ "skillDigest",
573
+ "workflowDigest",
574
+ "helperDigest",
575
+ "runId",
576
+ "currentArtifactPath",
577
+ "baselineArtifactPath",
578
+ "spurVersion",
579
+ "schemaVersion",
580
+ "executor",
581
+ "model",
582
+ "cacheDisposition"
583
+ ];
584
+ function yamlScalar(v) {
585
+ if (v === null || v === undefined)
586
+ return "null";
587
+ if (typeof v === "number" || typeof v === "boolean")
588
+ return String(v);
589
+ return `"${String(v).replaceAll('"', "\\\"")}"`;
590
+ }
591
+ function renderProvenanceFrontmatter(p) {
592
+ const lines = [
593
+ "---",
594
+ "identity:",
595
+ ` contractVersion: ${yamlScalar(p.identity.contractVersion)}`,
596
+ ` mode: ${p.identity.mode}`,
597
+ ` date: ${yamlScalar(p.identity.date)}`,
598
+ ` timezone: ${p.identity.timezone}`,
599
+ " bounds:",
600
+ ` since: ${p.identity.bounds.since}`,
601
+ ` until: ${p.identity.bounds.until}`,
602
+ " sources:"
603
+ ];
604
+ for (const s of p.identity.sources)
605
+ lines.push(` - source: ${s}`);
606
+ for (const k of YAML_KEYS) {
607
+ if (p[k] === undefined)
608
+ continue;
609
+ lines.push(`${k}: ${yamlScalar(p[k])}`);
610
+ }
611
+ lines.push("coverage:");
612
+ for (const c of p.coverage) {
613
+ lines.push(` - source: ${c.source}, status: ${c.status}, lastImportedAt: ${c.lastImportedAt ?? "null"}`);
614
+ }
615
+ lines.push("---");
616
+ return lines.join(`
617
+ `);
618
+ }
619
+ function bannerLine(p) {
620
+ return `> imported snapshot as of ${importedSnapshotAsOf(p.coverage)} · window ${p.windowState} · cache ${p.cacheDisposition ?? NOT_AVAILABLE}`;
621
+ }
622
+ function stripHeader(md) {
623
+ const body = md.replace(/^---\n[\s\S]*?\n---\n?/, "").replace(/^\n+/, "");
624
+ return body.replace(/^> imported snapshot as of [^\n]*\n+/, "");
625
+ }
626
+ function stampReport(candidateMarkdown, p) {
627
+ return `${renderProvenanceFrontmatter(p)}
628
+
629
+ ${bannerLine(p)}
630
+
631
+ ${stripHeader(candidateMarkdown).replace(/^\n+/, "")}`;
632
+ }
633
+ function refreshReport(publishedMarkdown, validatedAt, disposition) {
634
+ const cached = parseProvenance(publishedMarkdown);
635
+ if (cached === null)
636
+ return publishedMarkdown;
637
+ const refreshed = { ...cached, validatedAt, cacheDisposition: disposition };
638
+ return stampReport(publishedMarkdown, refreshed);
639
+ }
640
+ function publishAtomically(candidatePath, targetPath) {
641
+ const tmpPath = `${targetPath}.tmp`;
642
+ try {
643
+ writeFileSync(tmpPath, readFileSync(candidatePath));
644
+ const fd = openSync(tmpPath, "r");
645
+ try {
646
+ fsyncSync(fd);
647
+ } finally {
648
+ closeSync(fd);
649
+ }
650
+ renameSync(tmpPath, targetPath);
651
+ } catch (err) {
652
+ try {
653
+ rmSync(tmpPath, { force: true });
654
+ } catch {}
655
+ throw err;
656
+ }
657
+ }
658
+ function porcelainPaths(text) {
659
+ return new Set(text.split(`
660
+ `).map((line) => line.replace(/^\S+\s+/, "").trim()).filter((line) => line.length > 0));
661
+ }
662
+ function diffPorcelain(before, now, expects) {
663
+ const beforePaths = porcelainPaths(before);
664
+ return [...porcelainPaths(now)].filter((p) => !beforePaths.has(p) && !expects.has(p)).sort();
665
+ }
666
+ export {
667
+ validateSelector,
668
+ stampReport,
669
+ semanticArtifactDigest,
670
+ resolvePaths,
671
+ renderProvenanceFrontmatter,
672
+ refreshReport,
673
+ publishAtomically,
674
+ probe,
675
+ porcelainPaths,
676
+ parseProvenance,
677
+ logicDigest,
678
+ importedSnapshotAsOf,
679
+ diffPorcelain,
680
+ decideCache,
681
+ checkReportStructure,
682
+ buildProvenance,
683
+ bannerLine,
684
+ REPORT_SECTIONS,
685
+ FINDING_FIELDS
686
+ };