trackfw 7.2.0 → 7.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -48,17 +48,20 @@ function resolveRoadmapFile(cfg, roadmapArg) {
48
48
  // recognised as a wave heading (neither valid nor malformed).
49
49
  const WAVE_SCAN_RE = /^## Wave (\S+) /
50
50
 
51
- // Grammar: <integer>[-<suffix>] where integer >= 1 and suffix is [a-z0-9]+ (lowercase).
52
- // Valid: 1, 2, 2-bis, 2-hotfix, 10-a2.
53
- // Invalid: X, 2-BIS, -bis, 2-, 2-bis-ter, 0.
51
+ // Grammar: <integer>[-<suffix>] where integer >= 0 and suffix is [a-z0-9]+ (lowercase).
52
+ // Valid: 0, 1, 2, 2-bis, 2-hotfix, 10-a2. 0 is the Wave 0 threat-model convention
53
+ // (docs/cli-parity.md § "Wave label grammar").
54
+ // Invalid: X, 2-BIS, -bis, 2-, 2-bis-ter.
54
55
  const WAVE_LABEL_RE = /^(\d+)(?:-([a-z0-9]+))?$/
55
56
 
56
57
  // isValidWaveLabel returns true iff token matches the grammar above.
57
58
  // Exported so unit tests can assert the full table of valid/invalid examples.
59
+ // Shared by both guard points (the --wave flag validation and the heading
60
+ // pre-pass in findWave) — a single function, unlike Go's two duplicated checks.
58
61
  function isValidWaveLabel(token) {
59
62
  const m = WAVE_LABEL_RE.exec(String(token))
60
63
  if (!m) return false
61
- return parseInt(m[1], 10) >= 1
64
+ return parseInt(m[1], 10) >= 0
62
65
  }
63
66
 
64
67
  // ────────────────────────────────────────────────────────────────────────────
@@ -100,11 +103,201 @@ function findWave(lines, waveLabel, roadmapBasename) {
100
103
  return { startLine: wave.startLine, endLine: wave.endLine }
101
104
  }
102
105
 
106
+ // CRITERIA_HEADER_RE accepts both the canonical English header (ADR
107
+ // 2026-08-29 decision 1) and the Portuguese one, which remains accepted with
108
+ // no removal date (decision 2 — 99/143 roadmaps in the corpus use it,
109
+ // including artifacts in done/). The `^` anchor is load-bearing: an
110
+ // unanchored match would casar dentro de prosa ou de cerca de código, turning
111
+ // a quoted literal into forged acceptance evidence.
112
+ const CRITERIA_HEADER_RE = /^\*\*(?:Acceptance criteria|Crit[ée]rios de aceite):\*\*/
113
+
114
+ // STATUS_VOCABULARY is the closed set of first-token markers recognised as
115
+ // "complete" (ADR decision 3): the checkmark emoji, and the English/Portuguese
116
+ // words, matched after case-folding and diacritics-folding. Deliberately
117
+ // closed and explicit — "feito", "ok", "finalizado" are out (ADR, Alternatives
118
+ // Considered — "accept any non-empty status" is the rejected no-op design).
119
+ const STATUS_VOCABULARY = new Set(['✅', 'done', 'concluido'])
120
+
121
+ // VS16 is the single variation selector this module treats as cosmetic
122
+ // noise: the one emoji keyboards insert after "checkmark" to force
123
+ // text-style presentation (ADR 2026-08-29 decision 9, exception clause). No
124
+ // other variation selector or combining mark gets this treatment.
125
+ const VS16 = '\u{FE0F}'
126
+
127
+ // stripVS16 removes only U+FE0F occurrences from token. Deliberately
128
+ // narrower than "strip every variation selector" or "strip every Mn": VS16
129
+ // is the one documented cosmetic exception (ADR decision 9); anything else
130
+ // of category Mn is now a rejection, not a fold (see
131
+ // hasDisallowedCombiningMark).
132
+ function stripVS16(token) {
133
+ return token.split(VS16).join('')
134
+ }
135
+
136
+ // hasDisallowedCombiningMark reports whether token (with VS16 already
137
+ // removed) contains any Unicode category Mn (Mark, Nonspacing) codepoint.
138
+ // ADR 2026-08-29 decision 9: after the single VS16 exception, any combining
139
+ // mark on the first status token is rejected outright \u2014 the ML is NOT
140
+ // complete \u2014 rather than folded away. A vocabulary this small exists to
141
+ // refuse ambiguity; silently folding combining marks reopens exactly the
142
+ // ambiguity it exists to close ("d<U+1DC0>one" must not read as "done").
143
+ //
144
+ // ORDER IS LOAD-BEARING: this check MUST run on the token BEFORE NFD
145
+ // decomposition, not after. "Conclu\u00eddo" in its authored (NFC) form has
146
+ // no literal Mn codepoint \u2014 the accented "\u00ed" is a single
147
+ // precomposed codepoint. NFD-decomposing it *produces* a trailing Mn
148
+ // (U+0301, COMBINING ACUTE ACCENT) that normalizeStatusToken then strips
149
+ // for vocabulary matching. Running this rejection check on the
150
+ // already-decomposed string would treat that legitimate,
151
+ // vocabulary-sanctioned accent the same as an injected combining mark and
152
+ // reject "Conclu\u00eddo" outright, breaking AC15's own positive case.
153
+ // Checking the raw, pre-decomposition token instead lets it through here
154
+ // (no literal Mn present) while still catching a combining mark authored
155
+ // directly onto the token, which is category Mn in either form, decomposed
156
+ // or not.
157
+ function hasDisallowedCombiningMark(token) {
158
+ return /\p{Mn}/u.test(token)
159
+ }
160
+
161
+ // normalizeStatusToken folds diacritics and lower-cases the token for
162
+ // vocabulary comparison. Uses the \p{Mn} Unicode property escape (General
163
+ // Category "Mark, Nonspacing") instead of a hand-enumerated code point range,
164
+ // to match Go's runes.In(unicode.Mn) and Python's unicodedata.category(ch) \u2014
165
+ // all three fold every combining mark that survives to this point, which,
166
+ // after hasDisallowedCombiningMark has already run, only happens as a
167
+ // byproduct of NFD-decomposing an accented Latin letter (e.g. "Conclu\u00eddo"
168
+ // -> "Concluido"). Callers MUST have already rejected via
169
+ // hasDisallowedCombiningMark before calling this \u2014 see that function's
170
+ // doc comment for why.
171
+ function normalizeStatusToken(token) {
172
+ return token.normalize('NFD').replace(/\p{Mn}/gu, '').toLowerCase()
173
+ }
174
+
175
+ // statusIsComplete implements rule 3 by FIRST TOKEN, not substring (ADR
176
+ // decision 3, AC8/AC9/AC14). marker is the already-trimmed remainder of the
177
+ // "**Status:**" line. Splitting on /\s+/ treats U+00A0 (NBSP) as a separator \u2014
178
+ // matching the accepted "NBSP separator" case \u2014 while a zero-width character
179
+ // (U+200B, not matched by \s) stays glued to the token and safely causes
180
+ // rejection (a usability false-negative, not a security concern).
181
+ //
182
+ // This is the fix for vault/notes/adr-status-substring-livre-falso-positivo-2026-08-01.md:
183
+ // `marker.includes('checkmark')` would classify "**Status:** [pending] checkmark" as
184
+ // complete (reproduced live against 7.3.0 \u2014 ADR decision 8). First-token
185
+ // comparison rejects it because the first token is the pending glyph, not the marker.
186
+ //
187
+ // ADR decision 9: VS16 is stripped first (the one cosmetic exception), then
188
+ // any remaining combining mark on the raw token rejects outright \u2014 see
189
+ // hasDisallowedCombiningMark for why this must happen before NFD.
190
+ function statusIsComplete(marker) {
191
+ const trimmed = marker.trim()
192
+ if (trimmed.length === 0) return false
193
+ const first = stripVS16(trimmed.split(/\s+/)[0])
194
+ if (hasDisallowedCombiningMark(first)) return false
195
+ return STATUS_VOCABULARY.has(normalizeStatusToken(first))
196
+ }
197
+
198
+ // splitRoadmapLines is the single boundary where the raw file content becomes
199
+ // the array every marker regex operates on. It normalizes CRLF line endings
200
+ // by stripping a trailing "\r" from each line produced by splitting on
201
+ // "\n" — every downstream marker (ML heading, "**Status:**", acceptance
202
+ // header, criterion lines, "**Gates da wave:**", the fence delimiter) then
203
+ // sees the same content it would see for an LF-only file. It does NOT handle
204
+ // a lone-CR (old-Mac-style) file: splitting on "\n" alone leaves such a file
205
+ // as one giant line, same as internal/commands/barrier.go's splitRoadmapLines.
206
+ // Python's universal-newlines read does handle lone CR — a known, accepted
207
+ // asymmetry; issue #216 (the defect motivating this fix) is CRLF specifically.
208
+ //
209
+ // Unlike Go and Python, this runtime DOES depend on this normalization: JS
210
+ // regex "." excludes "\r" (it is a LineTerminator per the ECMAScript spec,
211
+ // unlike Go's RE2 "."), so `/^\*\*Status:\*\*(.*)$/.exec("**Status:** done\r")`
212
+ // returns null — a CRLF roadmap with every ML fully completed was reported as
213
+ // "not complete (status: missing)" (mirrors internal/commands/barrier.go
214
+ // splitRoadmapLines and the universal-newline read in
215
+ // pypi/trackfw/commands/barrier.py).
216
+ //
217
+ // Only the trailing "\r" immediately before the split point is stripped —
218
+ // this must never be confused with per-line indentation trimming, which
219
+ // ML-1B deliberately removed: leading whitespace on a marker line still fails
220
+ // to match (markers are anchored at column 0, untouched by this function).
221
+ function splitRoadmapLines(content) {
222
+ return content.split('\n').map((line) => (line.endsWith('\r') ? line.slice(0, -1) : line))
223
+ }
224
+
225
+ // detectFenceMarker inspects a whitespace-trimmed line and reports whether it
226
+ // opens or closes a CommonMark-style fence: a run of 3+ identical backtick
227
+ // (`) or tilde (~) characters at the start of the line. Returns
228
+ // { char, length } or null. ADR decision (ML-1B, achado 1): CommonMark
229
+ // defines a fence as 3+ of the SAME character (backtick or tilde), closed by
230
+ // a run of the same character with length >= the opening run — masking only
231
+ // "```" left both "~~~" fences and 4+-backtick fences (whose interior can
232
+ // nest a 3-backtick block) unmasked, which is the escape route a hostile
233
+ // roadmap would use.
234
+ function detectFenceMarker(trimmed) {
235
+ if (trimmed.length === 0) return null
236
+ const first = trimmed[0]
237
+ if (first !== '`' && first !== '~') return null
238
+ let i = 0
239
+ while (i < trimmed.length && trimmed[i] === first) i++
240
+ if (i < 3) return null
241
+ return { char: first, length: i }
242
+ }
243
+
244
+ // computeFenceMask returns, for each line index, whether that line lies
245
+ // strictly inside a fenced code block (``` ... ``` or ~~~ ... ~~~, per
246
+ // CommonMark: 3+ of the same fence character, closed by a run of the same
247
+ // character with length >= the opening run's length). A line that is itself
248
+ // a fence delimiter is never reported as "inside" — only the lines between an
249
+ // opening and a closing delimiter are masked. ADR decision 7 / AC13: ML
250
+ // detection, status and acceptance-header parsing must ignore documentation/
251
+ // examples inside a cerca — otherwise a roadmap that cites those literals (as
252
+ // this very roadmap, its REQ and its ADR do, repeatedly) is read as real ML
253
+ // content. parseGates already has its own, independent fence-matching for the
254
+ // "```bash ... ```" gates block and is untouched by this mask.
255
+ function computeFenceMask(lines) {
256
+ const mask = new Array(lines.length).fill(false)
257
+ let fenced = false
258
+ let fenceChar = null
259
+ let fenceLen = 0
260
+ for (let i = 0; i < lines.length; i++) {
261
+ const trimmed = lines[i].trim()
262
+ const marker = detectFenceMarker(trimmed)
263
+ if (!fenced) {
264
+ if (marker) {
265
+ fenced = true
266
+ fenceChar = marker.char
267
+ fenceLen = marker.length
268
+ continue
269
+ }
270
+ continue
271
+ }
272
+ // Currently inside a fence: only a marker of the SAME character with
273
+ // length >= the opening run closes it (a nested shorter/different
274
+ // marker stays masked as interior content) — AND, per CommonMark, a
275
+ // closing fence line contains NOTHING besides the fence run and
276
+ // (already-trimmed) surrounding whitespace: marker.length === trimmed.length.
277
+ // Fix for hades-tf security review (2026-08-29, achado #1 /
278
+ // vault/notes/barrier-fence-closing-trailing-content-bypass-2026-08-29.md):
279
+ // a line like "```trailing-junk" found INSIDE an open fence does not
280
+ // close it in real CommonMark — it stays interior content — but the
281
+ // prior check treated any run of length >= fenceLen as a valid close
282
+ // regardless of trailing text. The opening branch above is unchanged:
283
+ // CommonMark allows an info string after the opening run (` ```bash `).
284
+ if (marker && marker.char === fenceChar && marker.length >= fenceLen && marker.length === trimmed.length) {
285
+ fenced = false
286
+ continue
287
+ }
288
+ mask[i] = true
289
+ }
290
+ return mask
291
+ }
292
+
103
293
  // findMLs locates every `### ML-` heading inside [startLine, endLine) and returns
104
- // { id, lines } for each, where `lines` is the ML body (heading excluded).
105
- function findMLs(lines, startLine, endLine) {
294
+ // { id, lines, fenced } for each, where `lines` is the ML body (heading excluded)
295
+ // and `fenced` is the fence mask aligned to `lines`. fenceMask defaults to "no
296
+ // fences" so existing call sites that omit it keep working (ML-1A, AC13).
297
+ function findMLs(lines, startLine, endLine, fenceMask = computeFenceMask(lines)) {
106
298
  const headings = []
107
299
  for (let i = startLine; i < endLine; i++) {
300
+ if (fenceMask[i]) continue
108
301
  if (/^### ML-/.test(lines[i])) {
109
302
  const m = /^### (\S+)/.exec(lines[i])
110
303
  headings.push({ id: m[1], headingLine: i })
@@ -113,57 +306,104 @@ function findMLs(lines, startLine, endLine) {
113
306
  return headings.map((h, idx) => {
114
307
  let end = endLine
115
308
  for (let j = h.headingLine + 1; j < endLine; j++) {
309
+ if (fenceMask[j]) continue
116
310
  if (/^### /.test(lines[j]) || /^## /.test(lines[j])) { end = j; break }
117
311
  }
118
- return { id: h.id, lines: lines.slice(h.headingLine + 1, end) }
312
+ return {
313
+ id: h.id,
314
+ lines: lines.slice(h.headingLine + 1, end),
315
+ fenced: fenceMask.slice(h.headingLine + 1, end),
316
+ }
119
317
  })
120
318
  }
121
319
 
122
- // mlCompletionStatus applies rule 3 — completion is a `**Status:**` line whose
123
- // remainder contains ✅. Returns { complete, marker } where marker is "missing"
124
- // when no `**Status:**` line exists at all.
125
- function mlCompletionStatus(mlLines) {
126
- for (const raw of mlLines) {
127
- const line = raw.trim()
128
- const m = /^\*\*Status:\*\*(.*)$/.exec(line)
320
+ // mlCompletionStatus applies rule 3 — completion is by FIRST TOKEN (ADR
321
+ // decision 3), not substring. Returns { complete, marker } where marker is
322
+ // "missing" when no `**Status:**` line exists at all. Lines inside a fenced
323
+ // code block are ignored (ADR decision 7, AC13-a) — `fenced` is aligned to
324
+ // `mlLines`. Matched against the RAW line (no per-line .trim()) — an indented
325
+ // marker does not count (ML-1B, achado 2): Go and Python already require
326
+ // column 0 via `^` against the untrimmed line, and Node's prior .trim() made
327
+ // it the only runtime that released a wave on indented markers.
328
+ //
329
+ // Default omitted on purpose (hades-tf security review, 2026-08-29, achado
330
+ // #3 / hefesto-tf): a `fenced = []` default left every `fenced[i]` as
331
+ // `undefined` when the caller forgot the argument — indistinguishable from
332
+ // "nothing is fenced", silently turning OFF the fence-masking protection this
333
+ // very function exists to enforce. Production call sites always pass
334
+ // `ml.fenced` (never exploitable today), but a completion gate must fail
335
+ // CLOSED on a missing argument, not open. The default below marks every line
336
+ // as fenced (masked) instead, so an accidentally omitted argument yields
337
+ // "missing"/not-complete rather than "everything counts as real content".
338
+ function mlCompletionStatus(mlLines, fenced = mlLines.map(() => true)) {
339
+ for (let i = 0; i < mlLines.length; i++) {
340
+ if (fenced[i]) continue
341
+ const m = /^\*\*Status:\*\*(.*)$/.exec(mlLines[i])
129
342
  if (m) {
130
343
  const marker = m[1].trim()
131
- return { complete: marker.includes('✅'), marker: marker.length > 0 ? marker : 'missing' }
344
+ return { complete: statusIsComplete(marker), marker: marker.length > 0 ? marker : 'missing' }
132
345
  }
133
346
  }
134
347
  return { complete: false, marker: 'missing' }
135
348
  }
136
349
 
137
350
  // mlAcceptanceEvidence applies rule 4. Returns { hasBlock, total, unmet }.
138
- function mlAcceptanceEvidence(mlLines) {
351
+ // Lines inside a fenced code block are ignored throughout — for the header
352
+ // search, for the "**" block-end boundary, and for counting criterion lines —
353
+ // otherwise a cerca citing the acceptance header/`- [x]` as an example would
354
+ // forge acceptance evidence (ADR decision 7, AC13-a). All markers are matched
355
+ // against the RAW line (no per-line .trim()) — an indented marker does not
356
+ // count (ML-1B, achado 2): Go and Python already require column 0 via `^`
357
+ // against the untrimmed line, and Node's prior .trim() made it the only
358
+ // runtime that released a wave on indented markers.
359
+ //
360
+ // Default omitted on purpose — same rationale as mlCompletionStatus above
361
+ // (hades-tf security review, 2026-08-29, achado #3 / hefesto-tf): fail
362
+ // CLOSED (every line treated as fenced/masked, so `hasBlock: false` and no
363
+ // forged criteria are counted) if the caller omits `fenced`, instead of
364
+ // silently disabling the fence mask.
365
+ function mlAcceptanceEvidence(mlLines, fenced = mlLines.map(() => true)) {
139
366
  let blockStart = -1
140
367
  for (let i = 0; i < mlLines.length; i++) {
141
- if (/^\*\*Crit[ée]rios de aceite:\*\*/.test(mlLines[i].trim())) { blockStart = i; break }
368
+ if (fenced[i]) continue
369
+ if (CRITERIA_HEADER_RE.test(mlLines[i])) { blockStart = i; break }
142
370
  }
143
371
  if (blockStart === -1) return { hasBlock: false, total: 0, unmet: 0 }
144
372
 
145
373
  let blockEnd = mlLines.length
146
374
  for (let j = blockStart + 1; j < mlLines.length; j++) {
147
- if (/^\*\*/.test(mlLines[j].trim())) { blockEnd = j; break }
375
+ if (fenced[j]) continue
376
+ if (/^\*\*/.test(mlLines[j])) { blockEnd = j; break }
148
377
  }
149
378
 
150
- const blockLines = mlLines.slice(blockStart + 1, blockEnd)
151
- .map(l => l.trim())
152
- .filter(l => l.length > 0)
153
-
154
- const criteria = blockLines.filter(l => /^- \[/.test(l))
379
+ const criteria = []
380
+ for (let i = blockStart + 1; i < blockEnd; i++) {
381
+ if (fenced[i]) continue
382
+ const l = mlLines[i]
383
+ if (/^- \[.\]/.test(l)) criteria.push(l)
384
+ }
155
385
  if (criteria.length === 0) return { hasBlock: false, total: 0, unmet: 0 }
156
386
 
157
387
  const unmet = criteria.filter(l => /^- \[ \]/.test(l))
158
388
  return { hasBlock: true, total: criteria.length, unmet: unmet.length }
159
389
  }
160
390
 
391
+ // GATES_HEADER_RE mirrors Go's gatesHeaderRe / Python's _GATES_HEADER_RE: a
392
+ // PREFIX match at column 0, not full-line equality — a header followed by
393
+ // trailing prose/whitespace on the same line ("**Gates da wave:** (obrigatórios)")
394
+ // or a CRLF-terminated line ("**Gates da wave:**\r") must still be recognised,
395
+ // exactly as Go/Python already do.
396
+ const GATES_HEADER_RE = /^\*\*Gates da wave:\*\*/
397
+
161
398
  // parseGates applies rule 5. Returns { commands }. Throws UsageError naming the
162
- // offending line number for an unterminated fence.
399
+ // offending line number for an unterminated fence. The header marker is
400
+ // matched against the RAW line (no per-line .trim()) — an indented
401
+ // '**Gates da wave:**' does not count (ML-1B, achado 2): Go and Python
402
+ // already require column 0 for this marker.
163
403
  function parseGates(lines, startLine, endLine) {
164
404
  let markerLine = -1
165
405
  for (let i = startLine; i < endLine; i++) {
166
- if (lines[i].trim() === '**Gates da wave:**') { markerLine = i; break }
406
+ if (GATES_HEADER_RE.test(lines[i])) { markerLine = i; break }
167
407
  }
168
408
  if (markerLine === -1) return { commands: [] }
169
409
 
@@ -197,7 +437,7 @@ function evalMlsComplete(mls, waveLabel) {
197
437
  const evidence = []
198
438
  const failures = []
199
439
  for (const ml of mls) {
200
- const { complete, marker } = mlCompletionStatus(ml.lines)
440
+ const { complete, marker } = mlCompletionStatus(ml.lines, ml.fenced)
201
441
  if (complete) evidence.push(`${ml.id}: ✅`)
202
442
  else failures.push(`${ml.id}: not complete (status: ${marker})`)
203
443
  }
@@ -211,7 +451,7 @@ function evalAcceptanceEvidence(mls) {
211
451
  const evidence = []
212
452
  const failures = []
213
453
  for (const ml of mls) {
214
- const ev = mlAcceptanceEvidence(ml.lines)
454
+ const ev = mlAcceptanceEvidence(ml.lines, ml.fenced)
215
455
  if (!ev.hasBlock) {
216
456
  failures.push(`${ml.id}: no acceptance block`)
217
457
  } else if (ev.unmet > 0) {
@@ -224,16 +464,131 @@ function evalAcceptanceEvidence(mls) {
224
464
  return { name: 'acceptance_evidence', status, evidence, failures }
225
465
  }
226
466
 
227
- function evalGates(commands, cwd) {
467
+ // ────────────────────────────────────────────────────────────────────────────
468
+ // Roadmap trust check (AC11, AC12 — docs/cli-parity.md § Trust and --trust-local-gates)
469
+ // ────────────────────────────────────────────────────────────────────────────
470
+
471
+ // roadmapTrustForGates determines whether the gates declared in a roadmap can
472
+ // be trusted for execution without --trust-local-gates.
473
+ //
474
+ // Decision (AC4, AC11): the discriminant is git — a roadmap whose content
475
+ // differs from origin/main, or that is absent from origin/main, is untrusted.
476
+ //
477
+ // Returns { trusted: true } or { trusted: false, failureMsg: '...' }.
478
+ // Fail-open when not in a git repo, origin/main not resolvable, or any git
479
+ // error other than "path absent from origin/main". See docs/cli-parity.md.
480
+ function roadmapTrustForGates(roadmapPath) {
481
+ const roadmapDir = path.dirname(roadmapPath)
482
+
483
+ // Step 1: check if we are inside a git repository.
484
+ const revParse = spawnSync('git', ['rev-parse', '--git-dir'], {
485
+ cwd: roadmapDir,
486
+ encoding: 'utf8',
487
+ stdio: 'pipe',
488
+ })
489
+ if (revParse.status !== 0) {
490
+ // Not a git repo → fail-open.
491
+ return { trusted: true }
492
+ }
493
+
494
+ // Step 2: get the repository toplevel.
495
+ const topLevel = spawnSync('git', ['rev-parse', '--show-toplevel'], {
496
+ cwd: roadmapDir,
497
+ encoding: 'utf8',
498
+ stdio: 'pipe',
499
+ })
500
+ if (topLevel.status !== 0) {
501
+ return { trusted: true }
502
+ }
503
+ const repoRoot = topLevel.stdout.trim()
504
+
505
+ // Step 3: compute repo-relative path (always forward slashes for git).
506
+ const absRoadmap = path.resolve(roadmapPath)
507
+ const relPath = path.relative(repoRoot, absRoadmap).split(path.sep).join('/')
508
+
509
+ // Step 4: retrieve the file at origin/main.
510
+ const show = spawnSync('git', ['show', `origin/main:${relPath}`], {
511
+ cwd: repoRoot,
512
+ encoding: 'utf8',
513
+ stdio: 'pipe',
514
+ })
515
+ if (show.status !== 0) {
516
+ // If the path specifically does not exist in origin/main → untrusted.
517
+ const stderr = show.stderr || ''
518
+ if (stderr.includes('does not exist in') || stderr.includes('exists on disk, but not in')) {
519
+ return {
520
+ trusted: false,
521
+ failureMsg: 'gates not evaluated: roadmap is not committed in origin/main — pass --trust-local-gates to evaluate local gates',
522
+ }
523
+ }
524
+ // Other failures (no remote, not fetched) → fail-open.
525
+ return { trusted: true }
526
+ }
527
+
528
+ // Step 5: compare content byte-for-byte.
529
+ let localContent
530
+ try {
531
+ localContent = fs.readFileSync(roadmapPath, 'utf8')
532
+ } catch (_) {
533
+ return { trusted: true }
534
+ }
535
+ if (show.stdout !== localContent) {
536
+ return {
537
+ trusted: false,
538
+ failureMsg: 'gates not evaluated: roadmap content differs from origin/main — pass --trust-local-gates to evaluate local gates',
539
+ }
540
+ }
541
+ return { trusted: true }
542
+ }
543
+
544
+ // SH_MISSING_MSG is the pinned failure string for a `gates` check that could not
545
+ // be evaluated because `sh` is not on $PATH (AC3, AC4). All three runtimes (Go,
546
+ // Node, Python) must emit this byte-for-byte — see docs/cli-parity.md
547
+ // "Pinned failure strings for not_evaluated".
548
+ const SH_MISSING_MSG =
549
+ 'gates not evaluated: sh not found in PATH — install a POSIX shell (e.g. Git Bash, WSL) to evaluate gates'
550
+
551
+ function evalGates(commands, cwd, trustResult = { trusted: true }) {
552
+ // trustResult: { trusted: true } | { trusted: false, failureMsg: string }
553
+ if (!trustResult.trusted) {
554
+ // Roadmap is not trusted: do not execute gates (AC3, AC14).
555
+ // Report as not_evaluated — distinct from passed and blocked (AC6).
556
+ return {
557
+ name: 'gates',
558
+ status: 'not_evaluated',
559
+ commands,
560
+ evidence: [],
561
+ failures: [trustResult.failureMsg],
562
+ }
563
+ }
228
564
  const evidence = []
229
565
  const failures = []
230
566
  for (const command of commands) {
231
- const result = spawnSync(command, {
232
- shell: true,
567
+ // `sh` is invoked explicitly, as argv[0], and resolved through $PATH — NOT
568
+ // spawnSync's `shell: true`, which is pinned to a fixed /bin/sh. This is the
569
+ // same $PATH resolution Go has always used via exec.LookPath, and it is
570
+ // required for Windows: the Git Bash `sh.exe` is never at /bin/sh and is
571
+ // only reachable via $PATH.
572
+ const result = spawnSync('sh', ['-c', command], {
233
573
  cwd,
234
574
  encoding: 'utf8',
235
575
  stdio: 'pipe',
236
576
  })
577
+ if (result.error) {
578
+ // The process never started at all (e.g. `sh` missing from $PATH) —
579
+ // distinct from the gate command itself failing inside a running `sh`,
580
+ // which surfaces as a normal exit code (e.g. 127 for "tool not found")
581
+ // and never sets result.error. "Could not measure" is not "measured and
582
+ // failed" (AC3, AC4) — stop immediately: gates after this one were never
583
+ // observed, so they must not appear in evidence or failures.
584
+ return {
585
+ name: 'gates',
586
+ status: 'not_evaluated',
587
+ commands,
588
+ evidence: [],
589
+ failures: [SH_MISSING_MSG],
590
+ }
591
+ }
237
592
  const code = result.status === null || result.status === undefined ? 1 : result.status
238
593
  if (code === 0) evidence.push(`${command}: exit 0`)
239
594
  else failures.push(`${command}: exit ${code}`)
@@ -303,7 +658,7 @@ function printTextReport(doc) {
303
658
  // Command
304
659
  // ────────────────────────────────────────────────────────────────────────────
305
660
 
306
- async function runBarrier(roadmapArg, waveOption, jsonOutput) {
661
+ async function runBarrier(roadmapArg, waveOption, jsonOutput, trustLocalGates) {
307
662
  if (waveOption === undefined || waveOption === null || String(waveOption).trim() === '') {
308
663
  throw new UsageError('--wave is required')
309
664
  }
@@ -315,17 +670,22 @@ async function runBarrier(roadmapArg, waveOption, jsonOutput) {
315
670
  const cfg = config.load()
316
671
  const resolved = resolveRoadmapFile(cfg, roadmapArg)
317
672
  const content = fs.readFileSync(resolved.path, 'utf8')
318
- const lines = content.split('\n')
673
+ const lines = splitRoadmapLines(content)
319
674
 
320
675
  const startedAt = new Date()
321
676
  const wave = findWave(lines, waveLabel, resolved.basename)
322
677
  const mls = findMLs(lines, wave.startLine, wave.endLine)
323
678
  const gates = parseGates(lines, wave.startLine, wave.endLine)
324
679
 
680
+ // Determine trust for gate execution (AC11, AC12).
681
+ const trustResult = trustLocalGates
682
+ ? { trusted: true }
683
+ : roadmapTrustForGates(resolved.path)
684
+
325
685
  const checks = []
326
686
  checks.push(evalMlsComplete(mls, waveLabel))
327
687
  checks.push(evalAcceptanceEvidence(mls))
328
- checks.push(evalGates(gates.commands, process.cwd()))
688
+ checks.push(evalGates(gates.commands, process.cwd(), trustResult))
329
689
  checks.push(await evalValidate())
330
690
  const finishedAt = new Date()
331
691
 
@@ -351,9 +711,10 @@ function createBarrierCommand() {
351
711
  .argument('<roadmap>', 'Roadmap basename, with or without .md')
352
712
  .option('--wave <label>', 'Wave label to evaluate (e.g. 1, 2-bis, 2-hotfix)')
353
713
  .option('--json', 'Emit the result document as JSON instead of a text report')
714
+ .option('--trust-local-gates', 'Trust the local roadmap content for gate execution without comparing to origin/main (used by the /trackfw:barrier slash command for WIP roadmaps)')
354
715
  .action(async (roadmapArg, options) => {
355
716
  try {
356
- const exitCode = await runBarrier(roadmapArg, options.wave, !!options.json)
717
+ const exitCode = await runBarrier(roadmapArg, options.wave, !!options.json, !!options.trustLocalGates)
357
718
  process.exit(exitCode)
358
719
  } catch (err) {
359
720
  if (err instanceof UsageError) {
@@ -378,6 +739,11 @@ module.exports.findMLs = findMLs
378
739
  module.exports.mlCompletionStatus = mlCompletionStatus
379
740
  module.exports.mlAcceptanceEvidence = mlAcceptanceEvidence
380
741
  module.exports.parseGates = parseGates
742
+ module.exports.statusIsComplete = statusIsComplete
743
+ module.exports.computeFenceMask = computeFenceMask
744
+ module.exports.splitRoadmapLines = splitRoadmapLines
745
+ module.exports.CRITERIA_HEADER_RE = CRITERIA_HEADER_RE
746
+ module.exports.roadmapTrustForGates = roadmapTrustForGates
381
747
  module.exports.evalMlsComplete = evalMlsComplete
382
748
  module.exports.evalAcceptanceEvidence = evalAcceptanceEvidence
383
749
  module.exports.evalGates = evalGates