@boyingliu01/xp-gate 0.41.10 → 0.41.52

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 (123) hide show
  1. package/adapters/gate-3.sh +28 -1
  2. package/adapters/gate-6-layers.sh +18 -1
  3. package/bin/xp-gate.js +13 -0
  4. package/gate-3.sh +28 -1
  5. package/gate-6-layers.sh +18 -1
  6. package/gates/python-health.ts +74 -26
  7. package/gates/test-layers.ts +94 -9
  8. package/hooks/gate-3.sh +28 -1
  9. package/hooks/gate-6-layers.sh +18 -1
  10. package/hooks/gate-entries/gate-11-entry.sh +21 -0
  11. package/hooks/gate-entries/gate-2-entry.sh +15 -0
  12. package/hooks/install.sh +15 -3
  13. package/hooks/pre-commit +90 -13
  14. package/hooks/pre-push +10 -1
  15. package/hooks/sprint-gate.sh +101 -13
  16. package/lib/check-alignment-runner.cjs +97 -0
  17. package/lib/check.js +6 -0
  18. package/lib/crap-cli.js +14 -6
  19. package/lib/delphi-setup.js +13 -0
  20. package/lib/doctor-tui.js +205 -102
  21. package/lib/doctor.js +146 -7
  22. package/lib/gate-runner.js +14 -3
  23. package/lib/init-install.js +299 -0
  24. package/lib/init-languages.js +158 -0
  25. package/lib/init-manifest.js +165 -0
  26. package/lib/init-md-injection.js +58 -0
  27. package/lib/init.js +134 -500
  28. package/lib/install-skill.js +66 -1
  29. package/lib/layer-baseline.cjs +94 -0
  30. package/lib/mattpocock-license-verdict.json +7 -0
  31. package/lib/uninstall-skills.js +140 -0
  32. package/lib/uninstall.js +41 -100
  33. package/lib/update-skill.js +9 -1
  34. package/package.json +3 -1
  35. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  36. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  37. package/plugins/claude-code/skills/delphi-review/INSTALL.md +22 -3
  38. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  39. package/plugins/claude-code/skills/sprint-flow/references/definition-of-done.md +2 -2
  40. package/plugins/claude-code/skills/sprint-flow/references/phase-3-build.md +1 -1
  41. package/plugins/claude-code/skills/sprint-flow/references/phase-4-verify.md +2 -2
  42. package/plugins/claude-code/skills/sprint-flow/references/phase-6-close.md +17 -0
  43. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  44. package/plugins/dsh/lib/delphi-evidence.d.ts +59 -0
  45. package/plugins/dsh/lib/delphi-evidence.d.ts.map +1 -0
  46. package/plugins/dsh/lib/delphi-evidence.js +128 -0
  47. package/plugins/dsh/lib/delphi-finding.d.ts +123 -0
  48. package/plugins/dsh/lib/delphi-finding.d.ts.map +1 -0
  49. package/plugins/dsh/lib/delphi-finding.js +332 -0
  50. package/plugins/dsh/lib/delphi-findings-parse.d.ts +29 -0
  51. package/plugins/dsh/lib/delphi-findings-parse.d.ts.map +1 -0
  52. package/plugins/dsh/lib/delphi-findings-parse.js +138 -0
  53. package/plugins/dsh/lib/delphi-ledger.d.ts +55 -0
  54. package/plugins/dsh/lib/delphi-ledger.d.ts.map +1 -0
  55. package/plugins/dsh/lib/delphi-ledger.js +124 -0
  56. package/plugins/dsh/lib/delphi-run.d.ts +7 -0
  57. package/plugins/dsh/lib/delphi-run.d.ts.map +1 -1
  58. package/plugins/dsh/lib/delphi-run.js +48 -18
  59. package/plugins/dsh/lib/delphi-seats.d.ts +34 -0
  60. package/plugins/dsh/lib/delphi-seats.d.ts.map +1 -0
  61. package/plugins/dsh/lib/delphi-seats.js +40 -0
  62. package/plugins/dsh/lib/evidence.d.ts +21 -0
  63. package/plugins/dsh/lib/evidence.d.ts.map +1 -1
  64. package/plugins/dsh/lib/evidence.js +3 -0
  65. package/plugins/dsh/lib/index.d.ts.map +1 -1
  66. package/plugins/dsh/lib/index.js +12 -0
  67. package/plugins/dsh/package.json +1 -1
  68. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  69. package/plugins/dsh/skills/delphi-review/INSTALL.md +22 -3
  70. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  71. package/plugins/dsh/skills/sprint-flow/references/definition-of-done.md +2 -2
  72. package/plugins/dsh/skills/sprint-flow/references/phase-3-build.md +1 -1
  73. package/plugins/dsh/skills/sprint-flow/references/phase-4-verify.md +2 -2
  74. package/plugins/dsh/skills/sprint-flow/references/phase-6-close.md +17 -0
  75. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  76. package/plugins/dsh/src/delphi-evidence.test.ts +100 -0
  77. package/plugins/dsh/src/delphi-evidence.ts +201 -0
  78. package/plugins/dsh/src/delphi-finding.test.ts +333 -0
  79. package/plugins/dsh/src/delphi-finding.ts +446 -0
  80. package/plugins/dsh/src/delphi-findings-parse.test.ts +100 -0
  81. package/plugins/dsh/src/delphi-findings-parse.ts +158 -0
  82. package/plugins/dsh/src/delphi-findings.test.ts +4 -0
  83. package/plugins/dsh/src/delphi-ledger.test.ts +210 -0
  84. package/plugins/dsh/src/delphi-ledger.ts +158 -0
  85. package/plugins/dsh/src/delphi-run.test.ts +71 -68
  86. package/plugins/dsh/src/delphi-run.ts +80 -24
  87. package/plugins/dsh/src/delphi-seats.test.ts +117 -0
  88. package/plugins/dsh/src/delphi-seats.ts +50 -0
  89. package/plugins/dsh/src/evidence-findings.test.ts +75 -0
  90. package/plugins/dsh/src/evidence.ts +25 -0
  91. package/plugins/dsh/src/index.ts +14 -0
  92. package/plugins/opencode/package.json +1 -1
  93. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  94. package/plugins/opencode/skills/delphi-review/INSTALL.md +22 -3
  95. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  96. package/plugins/opencode/skills/sprint-flow/references/definition-of-done.md +2 -2
  97. package/plugins/opencode/skills/sprint-flow/references/phase-3-build.md +1 -1
  98. package/plugins/opencode/skills/sprint-flow/references/phase-4-verify.md +2 -2
  99. package/plugins/opencode/skills/sprint-flow/references/phase-6-close.md +17 -0
  100. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  101. package/plugins/qoder/plugin.json +1 -1
  102. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  103. package/plugins/qoder/skills/delphi-review/INSTALL.md +22 -3
  104. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  105. package/plugins/qoder/skills/sprint-flow/references/definition-of-done.md +2 -2
  106. package/plugins/qoder/skills/sprint-flow/references/phase-3-build.md +1 -1
  107. package/plugins/qoder/skills/sprint-flow/references/phase-4-verify.md +2 -2
  108. package/plugins/qoder/skills/sprint-flow/references/phase-6-close.md +17 -0
  109. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  110. package/principles/index.ts +50 -1
  111. package/scripts/delphi-config-read.cjs +43 -6
  112. package/scripts/delphi-external-review.cjs +69 -12
  113. package/scripts/delphi-prompts.cjs +47 -1
  114. package/skills/delphi-review/AGENTS.md +1 -1
  115. package/skills/delphi-review/INSTALL.md +22 -3
  116. package/skills/sprint-flow/AGENTS.md +1 -1
  117. package/skills/sprint-flow/references/definition-of-done.md +2 -2
  118. package/skills/sprint-flow/references/phase-3-build.md +1 -1
  119. package/skills/sprint-flow/references/phase-4-verify.md +2 -2
  120. package/skills/sprint-flow/references/phase-6-close.md +17 -0
  121. package/skills/test-specification-alignment/AGENTS.md +1 -1
  122. package/sprint-gate.sh +101 -13
  123. package/mutation/stryker-types.ts +0 -14
@@ -0,0 +1,446 @@
1
+ /**
2
+ * The finding ledger: how a review's problems stop being written in prose.
3
+ *
4
+ * A Delphi review's cost is in its ROUNDS, and a round is wasted when a seat that
5
+ * already reported a real problem keeps voting REQUEST_CHANGES after the problem
6
+ * was fixed -- the binary verdict cannot say "still the same five issues, all
7
+ * resolved". `parseVerdict` only knows two words, so the itemization lives here:
8
+ * each problem is a finding with a stable identity, and identity is what lets a
9
+ * later round say "this one is closed" instead of "I still disapprove".
10
+ *
11
+ * Why identity is not a hash of the title: the title is natural language, and
12
+ * Chinese wording, punctuation and code snippets change between rounds. A hash
13
+ * that moves takes the freeze with it -- silently, because nothing errors; the
14
+ * review merely grows a round. So identity is a DETERMINISTIC MATCHER, pinned by
15
+ * tests, not a hope that the model says it the same way twice.
16
+ *
17
+ * @test REQ-DSH-016
18
+ * @intent 让"问题已修好"变成可判定的状态(条目已关闭),而不是靠席位改变措辞;
19
+ * 并把字面稳定性从"模型措辞稳定"转移到"确定性匹配器"。
20
+ * @covers AC-DSH-016-03
21
+ */
22
+
23
+ import type { FindingEvidence } from "./delphi-evidence.js"
24
+
25
+ export type { FindingEvidence } from "./delphi-evidence.js"
26
+ export { validateEvidence } from "./delphi-evidence.js"
27
+ export type { EvidenceVerdict } from "./delphi-evidence.js"
28
+
29
+ /** How bad a finding is. Only critical and major block; minor never does. */
30
+ export type Severity = "critical" | "major" | "minor"
31
+
32
+ /**
33
+ * Where a finding is in its life.
34
+ *
35
+ * `disproved` has no way back to `open` on purpose: disproving rests on a
36
+ * measured command or a system-verified code fact, reopening rests on an
37
+ * assertion, and an assertion must not overwrite a measurement. `resolved` CAN
38
+ * reopen, because a fix can be reverted.
39
+ */
40
+ export type FindingStatus = "open" | "resolved" | "disproved"
41
+
42
+ interface Scored {
43
+ readonly finding: Finding
44
+ readonly score: number
45
+ }
46
+
47
+ /** One problem reported by a seat, tracked across rounds. */
48
+ export interface Finding {
49
+ /** Assigned by the matcher, never by the model. */
50
+ readonly id: string
51
+ /** The seat that raised it, or `"multi"` once two seats reported the same one. */
52
+ readonly seat: string
53
+ readonly severity: Severity
54
+ readonly title: string
55
+ /** Normalized file path, WITHOUT a line number: line numbers drift. */
56
+ readonly location: string
57
+ /** Lower-cased ASCII identifiers and backticked fragments; the secondary key. */
58
+ readonly keywords: readonly string[]
59
+ readonly fix: string
60
+ readonly status: FindingStatus
61
+ readonly evidence?: FindingEvidence
62
+ readonly statusChangedAtRound: number
63
+ /**
64
+ * Every seat that raised this finding, in the order they did.
65
+ *
66
+ * `seat` alone collapses to "multi" once a second seat agrees, and "multi"
67
+ * equals no role -- so a shared finding became impossible to settle and blocked
68
+ * consensus forever. The owner SET is what the ledger closes against.
69
+ */
70
+ readonly raisedBy?: readonly string[]
71
+ /**
72
+ * Set when a candidate fell in the uncertain band next to a settled entry: it
73
+ * got a NEW id (never merged on a guess) but names what it may belong to, so a
74
+ * human can join them deliberately.
75
+ */
76
+ readonly candidateOf?: string
77
+ }
78
+
79
+ /** A finding the matcher is asked to identify, before an id has been decided. */
80
+ export interface CandidateFinding {
81
+ readonly seat: string
82
+ readonly severity: Severity
83
+ readonly title: string
84
+ readonly location: string
85
+ readonly fix: string
86
+ }
87
+
88
+ /**
89
+ * Outcome of matching one candidate against the ledger.
90
+ *
91
+ * `matchingDisproved` names the settled entry a candidate resembles closely
92
+ * enough that minting a new id for it would be re-filing a disproved defect
93
+ * under another path -- the caller must see it before treating the new id as
94
+ * legitimate (design §2.2).
95
+ */
96
+ export interface MatchOutcome {
97
+ readonly finding: Finding
98
+ readonly reused: boolean
99
+ readonly matchingDisproved?: Finding
100
+ }
101
+
102
+ /** Identifiers shorter than this are noise (`if`, `for`, common locals). */
103
+ const MIN_KEYWORD_LEN = 4
104
+
105
+ /** Jaccard overlap at or above this on the SAME path means "the same finding". */
106
+ const SAME_ITEM_JACCARD = 0.5
107
+
108
+ /** Dice overlap that marks a no-keyword-overlap restatement of one defect. */
109
+ const REPHRASE_DICE = 0.75
110
+
111
+ /** Below two keywords, overlap carries no information. */
112
+ const MIN_KEYWORDS_FOR_MATCHING = 2
113
+
114
+ /** Near-identical wording across a MOVED path names the same defect. */
115
+ const CROSS_PATH_DICE = 0.9
116
+
117
+ /** Lower edge of the "uncertain" band: below the same-item bar, above noise. */
118
+ const UNCERTAIN_JACCARD = 0.4
119
+
120
+ /** Lower edge of the uncertain Dice band. */
121
+ const UNCERTAIN_DICE = 0.65
122
+
123
+ /** Width of the zero-padded numeric suffix in an id, e.g. `TC-01`. */
124
+ const ID_PAD = 2
125
+
126
+ /** Severity rank; higher blocks harder. */
127
+ const SEVERITY_RANK: Readonly<Record<Severity, number>> = { minor: 0, major: 1, critical: 2 }
128
+
129
+ /** Words that appear in every review and therefore identify nothing. */
130
+ const STOPWORDS = new Set([
131
+ "the", "and", "that", "this", "with", "from", "when", "then", "than", "into",
132
+ "does", "doesn", "should", "would", "could", "must", "cannot", "fail", "fails",
133
+ "will", "have", "been", "also", "only", "case", "code", "file", "test", "tests",
134
+ ])
135
+
136
+ /** Two upper-case letters naming the seat; unknown seats get `XX`. */
137
+ const SEAT_PREFIXES: Readonly<Record<string, string>> = {
138
+ architecture: "AR",
139
+ technical: "TC",
140
+ feasibility: "FC",
141
+ }
142
+
143
+ /** What a brand-new entry starts as. */
144
+ const FRESH: Pick<Finding, "status" | "statusChangedAtRound"> = {
145
+ status: "open",
146
+ statusChangedAtRound: 0,
147
+ }
148
+
149
+ /**
150
+ * Every fragment a title offers as a keyword candidate, lower-cased.
151
+ *
152
+ * Backticks are read first, then bare identifiers, so `restorePyproject(path)`
153
+ * contributes both the whole fragment and its identifier.
154
+ */
155
+ function keywordCandidates(title: string): string[] {
156
+ const fragments = [...title.matchAll(/`([^`]+)`/g)].map((m) => m[1].toLowerCase())
157
+ const identifiers = [...title.matchAll(/[A-Za-z_][A-Za-z0-9_]*/g)].map((m) => m[0].toLowerCase())
158
+ return [...fragments, ...identifiers]
159
+ }
160
+
161
+ /** Whether a lower-cased fragment is specific enough to identify anything. */
162
+ function isDistinctive(word: string): boolean {
163
+ return word.length >= MIN_KEYWORD_LEN && !STOPWORDS.has(word)
164
+ }
165
+
166
+ /**
167
+ * The identifiers and backticked fragments in a title, lower-cased and deduped.
168
+ *
169
+ * ASCII only, deliberately: Chinese word segmentation is itself unstable, and an
170
+ * unstable key on the secondary index reproduces the drift a hash would have.
171
+ */
172
+ export function extractKeywords(title: string): string[] {
173
+ return [...new Set(keywordCandidates(title).filter(isDistinctive))].sort()
174
+ }
175
+
176
+ /** Collapse the path forms that name one file into a single comparable string. */
177
+ function collapsePathForms(location: string): string {
178
+ return location.replace(/^\.\//, "").replace(/\/{2,}/g, "/").replace(/\/+$/, "")
179
+ }
180
+
181
+ /**
182
+ * A location without its line number.
183
+ *
184
+ * Line numbers move when an unrelated line is inserted above, which would make
185
+ * one finding look like two and defeat the freeze. The path is the stable part.
186
+ */
187
+ export function normalizeLocation(location: string): string {
188
+ return collapsePathForms(location.replace(/:\d+(?::\d+)?$/, ""))
189
+ }
190
+
191
+ /** Whether two keyword sets are both large enough for a ratio to mean anything. */
192
+ function comparable(a: readonly string[], b: readonly string[]): boolean {
193
+ return a.length >= MIN_KEYWORDS_FOR_MATCHING && b.length >= MIN_KEYWORDS_FOR_MATCHING
194
+ }
195
+
196
+ /** How many of `b`'s words also appear in `a`. */
197
+ function sharedCount(a: readonly string[], b: readonly string[]): number {
198
+ const left = new Set(a)
199
+ return b.filter((word) => left.has(word)).length
200
+ }
201
+
202
+ /**
203
+ * Jaccard overlap of two keyword sets (|intersection| / |union|).
204
+ *
205
+ * Returns 0 below the keyword minimum. The guard lives HERE, not only in the
206
+ * caller: a one-keyword set has Jaccard 0 or 1 and nothing between, so a public
207
+ * score reporting 1.0 for two identical single words invites exactly the caller
208
+ * that merges on it.
209
+ */
210
+ export function keywordOverlap(a: readonly string[], b: readonly string[]): number {
211
+ if (!comparable(a, b)) return 0
212
+ return sharedCount(a, b) / new Set([...a, ...b]).size
213
+ }
214
+
215
+ /** Dice coefficient of two keyword sets; the rephrase detector. */
216
+ /**
217
+ * Dice overlap of two keyword sets; the rephrase detector.
218
+ *
219
+ * Refuses below the keyword minimum for the same reason `keywordOverlap` does:
220
+ * one shared keyword gives Dice 2*1/(1+1) = 1.0, which clears every bar this
221
+ * module has. Measured -- without this guard, EVERY single-keyword finding looked
222
+ * like a re-filing of every disproved one, and the freeze could not be trusted.
223
+ */
224
+ function keywordDice(a: readonly string[], b: readonly string[]): number {
225
+ if (!comparable(a, b)) return 0
226
+ const total = new Set(a).size + new Set(b).size
227
+ return total === 0 ? 0 : (2 * sharedCount(a, b)) / total
228
+ }
229
+
230
+ /** Whether a candidate and an entry name the same file. */
231
+ function samePath(candidate: CandidateFinding, existing: Finding): boolean {
232
+ return normalizeLocation(candidate.location) === existing.location
233
+ }
234
+
235
+ /** Keywords for a candidate; a pure function of the title. */
236
+ function keywordsOf(candidate: CandidateFinding): string[] {
237
+ return extractKeywords(candidate.title)
238
+ }
239
+
240
+ /** Same path and overlapping keywords at or above the same-item bar. */
241
+ function isSameItem(candidate: CandidateFinding, existing: Finding): boolean {
242
+ const keys = keywordsOf(candidate)
243
+ if (!comparable(keys, existing.keywords)) return false
244
+ return samePath(candidate, existing) && keywordOverlap(keys, existing.keywords) >= SAME_ITEM_JACCARD
245
+ }
246
+
247
+ /** Same path, worded as a restatement of the same identifiers. */
248
+ function isRephrase(candidate: CandidateFinding, existing: Finding): boolean {
249
+ const keys = keywordsOf(candidate)
250
+ if (!comparable(keys, existing.keywords)) return false
251
+ return samePath(candidate, existing) && keywordDice(keys, existing.keywords) >= REPHRASE_DICE
252
+ }
253
+
254
+ /** A settled-by-disproof entry this candidate may be re-filing elsewhere. */
255
+ function resemblesDisproved(candidate: CandidateFinding, ledger: readonly Finding[]): Finding | undefined {
256
+ const keys = keywordsOf(candidate)
257
+ return ledger.find(
258
+ (e) => e.status === "disproved" && keywordDice(keys, e.keywords) >= CROSS_PATH_DICE,
259
+ )
260
+ }
261
+
262
+ /**
263
+ * The settled entry a candidate sits NEXT TO without clearing either bar.
264
+ *
265
+ * Returning it (instead of merging) is the "uncertain" outcome: a guess must not
266
+ * join two findings, but a human should be told they may be the same.
267
+ */
268
+ /** One entry's similarity to a candidate, or null when it clears neither bar. */
269
+ function uncertainScore(keys: readonly string[], entry: Finding): number | null {
270
+ const jaccard = keywordOverlap(keys, entry.keywords)
271
+ const dice = keywordDice(keys, entry.keywords)
272
+ if (jaccard < UNCERTAIN_JACCARD && dice < UNCERTAIN_DICE) return null
273
+ return Math.max(jaccard, dice)
274
+ }
275
+
276
+ /** Higher score wins; equal scores break on id so the choice is ledger-order independent. */
277
+ function isBetterMatch(score: number, finding: Finding, best: Scored | undefined): boolean {
278
+ if (best === undefined) return true
279
+ if (score !== best.score) return score > best.score
280
+ return finding.id < best.finding.id
281
+ }
282
+
283
+ /**
284
+ * The settled entry a candidate sits NEXT TO without clearing either merge bar.
285
+ *
286
+ * The BEST match wins, not the first one found: `candidateOf` is a hint a human
287
+ * acts on, and pointing it at an arbitrary earlier entry makes the hint depend on
288
+ * ledger order rather than on the code.
289
+ */
290
+ function nearestUncertain(candidate: CandidateFinding, ledger: readonly Finding[]): Finding | undefined {
291
+ const keys = keywordsOf(candidate)
292
+ return ledger
293
+ .filter((entry) => samePath(candidate, entry))
294
+ .map((entry) => ({ finding: entry, score: uncertainScore(keys, entry) }))
295
+ .reduce<Scored | undefined>(
296
+ (best, row) => (row.score !== null && isBetterMatch(row.score, row.finding, best) ? { finding: row.finding, score: row.score } : best),
297
+ undefined,
298
+ )?.finding
299
+ }
300
+
301
+ /** Whether an id already belongs to this seat's prefix. */
302
+ function ownsPrefix(finding: Finding, prefix: string): boolean {
303
+ return finding.id.startsWith(`${prefix}-`)
304
+ }
305
+
306
+ /** The numeric suffix of an id, or 0 when it has none. */
307
+ function idSuffix(finding: Finding): number {
308
+ const parsed = Number(finding.id.split("-")[1])
309
+ return Number.isFinite(parsed) ? parsed : 0
310
+ }
311
+
312
+ /** The next free id for a seat, e.g. `TC-01`. */
313
+ /**
314
+ * The next free id for a seat, e.g. `TC-01`.
315
+ *
316
+ * Reduced rather than spread: `Math.max(0, ...ids)` passes one argument per
317
+ * entry, and a long review (or a reused ledger) hits the engine's argument limit
318
+ * as a RangeError at the one moment ids must still be assigned.
319
+ */
320
+ function nextId(seat: string, ledger: readonly Finding[]): string {
321
+ const prefix = SEAT_PREFIXES[seat] ?? "XX"
322
+ const highest = ledger
323
+ .filter((f) => ownsPrefix(f, prefix))
324
+ .reduce((max, f) => Math.max(max, idSuffix(f)), 0)
325
+ return `${prefix}-${String(highest + 1).padStart(ID_PAD, "0")}`
326
+ }
327
+
328
+ /** Only escalate: lowering a severity needs evidence, raising it does not. */
329
+ function highestSeverity(left: Severity | undefined, right: Severity): Severity {
330
+ if (left === undefined) return right
331
+ return SEVERITY_RANK[left] >= SEVERITY_RANK[right] ? left : right
332
+ }
333
+
334
+ /** Widest keyword set, so a later restatement still overlaps. */
335
+ function unionKeywords(candidate: CandidateFinding, reuse: Finding | undefined): string[] {
336
+ if (reuse === undefined) return keywordsOf(candidate)
337
+ return [...new Set([...reuse.keywords, ...keywordsOf(candidate)])].sort()
338
+ }
339
+
340
+ /**
341
+ * The owner set after `seat` joins it: existing contributors, plus this one.
342
+ *
343
+ * A legacy entry without `raisedBy` falls back to its single `seat`, so a ledger
344
+ * recorded before this field existed still closes correctly.
345
+ */
346
+ function unionSeats(reuse: Finding, seat: string): string[] {
347
+ const existing = reuse.raisedBy ?? (reuse.seat === "multi" ? [] : [reuse.seat])
348
+ return [...new Set([...existing, seat])]
349
+ }
350
+
351
+ /** Whether a second, different seat has now reported the same finding. */
352
+ function reportedByOther(candidate: CandidateFinding, reuse: Finding | undefined): boolean {
353
+ if (reuse === undefined || reuse.seat === "multi") return false
354
+ return reuse.seat !== candidate.seat
355
+ }
356
+
357
+ /** `multi` once two seats agree on one id; otherwise the seat that owns it. */
358
+ function seatFor(candidate: CandidateFinding, reuse: Finding | undefined): string {
359
+ if (reuse === undefined) return candidate.seat
360
+ return reportedByOther(candidate, reuse) ? "multi" : reuse.seat
361
+ }
362
+
363
+ /** Status and history, deliberately carrying NO severity (see `buildFinding`). */
364
+ function historyOf(reuse: Finding | undefined): Pick<Finding, "status" | "statusChangedAtRound"> {
365
+ if (reuse === undefined) return FRESH
366
+ const { status, statusChangedAtRound } = reuse
367
+ return { status, statusChangedAtRound }
368
+ }
369
+
370
+ /** The fields that describe the finding itself, in both cases. */
371
+ function identityOf(candidate: CandidateFinding, reuse: Finding | undefined): Pick<Finding, "seat" | "title" | "location" | "keywords" | "fix"> {
372
+ return {
373
+ seat: seatFor(candidate, reuse),
374
+ title: candidate.title,
375
+ location: normalizeLocation(candidate.location),
376
+ keywords: unionKeywords(candidate, reuse),
377
+ fix: candidate.fix,
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Build the entry for a candidate that reused `reuse`.
383
+ *
384
+ * `severity` is set from `highestSeverity` and NOT carried through `historyOf`:
385
+ * a stored severity riding along with the status once made a "minor -> critical"
386
+ * upgrade silently stay major.
387
+ */
388
+ function restate(candidate: CandidateFinding, reuse: Finding): Finding {
389
+ return {
390
+ id: reuse.id,
391
+ raisedBy: unionSeats(reuse, candidate.seat),
392
+ ...identityOf(candidate, reuse),
393
+ ...historyOf(reuse),
394
+ severity: highestSeverity(reuse.severity, candidate.severity),
395
+ }
396
+ }
397
+
398
+ /** The report half of a brand-new entry. */
399
+ function freshReport(candidate: CandidateFinding): Pick<Finding, "seat" | "title" | "location" | "keywords" | "fix"> {
400
+ return {
401
+ seat: candidate.seat,
402
+ title: candidate.title,
403
+ location: normalizeLocation(candidate.location),
404
+ keywords: keywordsOf(candidate),
405
+ fix: candidate.fix,
406
+ }
407
+ }
408
+
409
+ /** Build the entry for a brand-new candidate. */
410
+ function fresh(candidate: CandidateFinding, ledger: readonly Finding[]): Finding {
411
+ return {
412
+ id: nextId(candidate.seat, ledger),
413
+ ...freshReport(candidate),
414
+ raisedBy: [candidate.seat],
415
+ severity: candidate.severity,
416
+ status: FRESH.status,
417
+ statusChangedAtRound: FRESH.statusChangedAtRound,
418
+ }
419
+ }
420
+
421
+ /** The new entry, annotated with the settled entry it may belong to. */
422
+ function withCandidateOf(finding: Finding, uncertain: Finding | undefined): Finding {
423
+ if (uncertain === undefined) return finding
424
+ return { ...finding, candidateOf: uncertain.id }
425
+ }
426
+
427
+ /**
428
+ * Give a candidate its identity, reusing an existing id when it is the same
429
+ * finding.
430
+ *
431
+ * The model's own `id` is never consulted: it is a hint for humans, and letting
432
+ * it be authoritative would let a drifting model reset a frozen id by renaming
433
+ * it.
434
+ */
435
+ export function matchFinding(candidate: CandidateFinding, ledger: readonly Finding[]): MatchOutcome {
436
+ const matched = ledger.find((e) => isSameItem(candidate, e) || isRephrase(candidate, e))
437
+ if (matched) return { finding: restate(candidate, matched), reused: true }
438
+
439
+ const settled = resemblesDisproved(candidate, ledger)
440
+ const finding = withCandidateOf(fresh(candidate, ledger), nearestUncertain(candidate, ledger))
441
+ if (settled === undefined) return { finding, reused: false }
442
+ return { finding, reused: false, matchingDisproved: settled }
443
+ }
444
+
445
+ export type { SeatState } from "./delphi-seats.js"
446
+ export { blockingFindings, releaseSeats } from "./delphi-seats.js"
@@ -0,0 +1,100 @@
1
+ import { describe, it, expect } from "vitest"
2
+
3
+ import { parseFindings } from "./delphi-findings-parse.js"
4
+
5
+ /**
6
+ * @test REQ-DSH-016 席位报告的 Findings 表必须能被可靠地解析成条目
7
+ * @intent 台账的数据入口就是这张表。解析器宁可丢一行,也不能猜一行:
8
+ * 解析器发明出来的 finding 比席位没提过的更糟——它会作为"仍然阻断"
9
+ * 的理由进入后续轮次,而没有任何席位真正主张过它。
10
+ * @covers AC-DSH-016-03
11
+ */
12
+
13
+ /** The prompt's column order; every fixture below varies only its data rows. */
14
+ const HEADER = "| ID | Severity | Description | Location | Fix |\n|---|---|---|---|---|"
15
+
16
+ /** A report with the given data rows under a `### Findings` heading. */
17
+ function report(...rows: string[]): string {
18
+ return [`### Findings`, HEADER, ...rows, "", "### VERDICT", "REQUEST_CHANGES", "### CONFIDENCE", "9"].join("\n")
19
+ }
20
+
21
+ const TWO_ROWS = report(
22
+ "| F1 | critical | exit code discarded | src/run.ts:42 | propagate it |",
23
+ "| F2 | major | scope regex rewrites the wrong table | src/toml.ts:88 | anchor the match |",
24
+ )
25
+
26
+ describe("parseFindings:把报告里的表变成条目", () => {
27
+ it("读出每一行,位置与描述都是席位写的原文", () => {
28
+ const found = parseFindings(TWO_ROWS, "technical")
29
+ expect(found).toHaveLength(2)
30
+ expect(found[0]).toMatchObject({
31
+ seat: "technical",
32
+ severity: "critical",
33
+ location: "src/run.ts:42",
34
+ })
35
+ expect(found[0].title).toContain("exit code discarded")
36
+ expect(found[1].severity).toBe("major")
37
+ })
38
+
39
+ it("NONE 行不是条目,也不能当成\"这条已通过\"", () => {
40
+ const clean = "### Findings\nNONE\n\n### VERDICT\nAPPROVED\n### CONFIDENCE\n8"
41
+ expect(parseFindings(clean, "architecture")).toHaveLength(0)
42
+ })
43
+
44
+ it("表格里的单行 NONE 同样被跳过", () => {
45
+ expect(parseFindings(report("| NONE | | | | |"), "architecture")).toHaveLength(0)
46
+ })
47
+
48
+ it("没有位置的行被丢弃,而不是被猜一个位置", () => {
49
+ // A row with no location cannot be matched across rounds, so accepting it
50
+ // would create a finding that the freeze can never close.
51
+ expect(parseFindings(report("| F1 | critical | something is wrong | - | look |"), "technical")).toHaveLength(0)
52
+ })
53
+
54
+ it("没有描述的行被丢弃", () => {
55
+ expect(parseFindings(report("| F1 | critical | | src/a.ts:1 | look |"), "technical")).toHaveLength(0)
56
+ })
57
+
58
+ it("没有 Findings 段时返回空,而不是把整篇正文当条目", () => {
59
+ const prose = "The suffix resets $? so every gate reads as passing.\n\n### VERDICT\nREQUEST_CHANGES"
60
+ expect(parseFindings(prose, "technical")).toHaveLength(0)
61
+ })
62
+
63
+ it("不认识的严重度词按 major 处理(fail-safe),不能靠古怪用词逃过阻断", () => {
64
+ // Defaulting to minor let a report dodge blocking by spelling "critical" in a
65
+ // way this parser does not know -- and a reported problem being quietly
66
+ // downgraded is exactly what the ledger must not allow. Defaulting to
67
+ // critical would be wrong too: one odd word would block consensus outright.
68
+ const found = parseFindings(report("| F1 | catastrophic | mystery | src/a.ts:1 | look |"), "technical")
69
+ expect(found).toHaveLength(1)
70
+ expect(found[0].severity).toBe("major")
71
+ })
72
+
73
+ it("全空的表格行是畸形数据行,不能被当作 NONE 吞掉", () => {
74
+ // A row that says nothing is not a row that says "nothing found".
75
+ const blank = report("| | | | | |")
76
+ expect(parseFindings(blank, "technical")).toHaveLength(0)
77
+ })
78
+
79
+ it("Severity 别名(high/low)映射到 major/minor", () => {
80
+ const found = parseFindings(
81
+ report("| F1 | high | one | src/a.ts:1 | x |", "| F2 | low | two | src/b.ts:2 | y |"),
82
+ "feasibility",
83
+ )
84
+ expect(found.map((f) => f.severity)).toEqual(["major", "minor"])
85
+ })
86
+
87
+ it("Findings 段在下一个标题处结束,不吞掉后面的内容", () => {
88
+ const trailing = [
89
+ "### Findings",
90
+ HEADER,
91
+ "| F1 | major | one | src/a.ts:1 | x |",
92
+ "### Remaining blocking issues",
93
+ HEADER,
94
+ "| X9 | critical | should not be read | src/z.ts:9 | nope |",
95
+ ].join("\n")
96
+ const found = parseFindings(trailing, "technical")
97
+ expect(found).toHaveLength(1)
98
+ expect(found[0].fix).toBe("x")
99
+ })
100
+ })