@descent-vtt/spec-harness 0.6.0 → 0.7.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.
Files changed (84) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +85 -0
  4. package/README.md +273 -24
  5. package/dist/audit.d.ts +71 -1
  6. package/dist/audit.js +140 -17
  7. package/dist/audit.js.map +1 -1
  8. package/dist/branch.d.ts +13 -0
  9. package/dist/branch.js +19 -0
  10. package/dist/branch.js.map +1 -1
  11. package/dist/cli.d.ts +1 -1
  12. package/dist/cli.js +51 -13
  13. package/dist/cli.js.map +1 -1
  14. package/dist/commands.js +11 -4
  15. package/dist/commands.js.map +1 -1
  16. package/dist/config.js +3 -1
  17. package/dist/config.js.map +1 -1
  18. package/dist/configure.d.ts +50 -3
  19. package/dist/configure.js +78 -5
  20. package/dist/configure.js.map +1 -1
  21. package/dist/context.d.ts +10 -5
  22. package/dist/context.js +54 -19
  23. package/dist/context.js.map +1 -1
  24. package/dist/document.d.ts +2 -1
  25. package/dist/document.js.map +1 -1
  26. package/dist/formats.d.ts +31 -0
  27. package/dist/formats.js +127 -0
  28. package/dist/formats.js.map +1 -0
  29. package/dist/git.d.ts +6 -0
  30. package/dist/git.js +8 -0
  31. package/dist/git.js.map +1 -1
  32. package/dist/guard.d.ts +8 -0
  33. package/dist/guard.js +19 -1
  34. package/dist/guard.js.map +1 -1
  35. package/dist/host.d.ts +14 -0
  36. package/dist/host.js +50 -0
  37. package/dist/host.js.map +1 -0
  38. package/dist/index.d.ts +4 -2
  39. package/dist/index.js +2 -1
  40. package/dist/index.js.map +1 -1
  41. package/dist/manifests.d.ts +8 -1
  42. package/dist/manifests.js +16 -6
  43. package/dist/manifests.js.map +1 -1
  44. package/dist/premises.d.ts +3 -0
  45. package/dist/premises.js +43 -13
  46. package/dist/premises.js.map +1 -1
  47. package/dist/reader.js +10 -2
  48. package/dist/reader.js.map +1 -1
  49. package/dist/round.d.ts +8 -0
  50. package/dist/round.js +73 -22
  51. package/dist/round.js.map +1 -1
  52. package/dist/server.js +9 -3
  53. package/dist/server.js.map +1 -1
  54. package/dist/setup.d.ts +10 -0
  55. package/dist/setup.js +68 -32
  56. package/dist/setup.js.map +1 -1
  57. package/dist/signers.d.ts +43 -0
  58. package/dist/signers.js +105 -0
  59. package/dist/signers.js.map +1 -0
  60. package/dist/types.d.ts +7 -0
  61. package/dist/types.js.map +1 -1
  62. package/dist/vendor/spec-core/markdown/frontmatter.d.ts +11 -1
  63. package/dist/vendor/spec-core/markdown/frontmatter.js +20 -3
  64. package/dist/vendor/spec-core/markdown/frontmatter.js.map +1 -1
  65. package/dist/vendor/spec-core/pattern/glob.d.ts +85 -0
  66. package/dist/vendor/spec-core/pattern/glob.js +207 -17
  67. package/dist/vendor/spec-core/pattern/glob.js.map +1 -1
  68. package/dist/vendor/spec-core/pattern/index.d.ts +2 -2
  69. package/dist/vendor/spec-core/pattern/index.js +1 -1
  70. package/dist/vendor/spec-core/pattern/index.js.map +1 -1
  71. package/dist/vendor/spec-core/text/index.d.ts +1 -0
  72. package/dist/vendor/spec-core/text/index.js +1 -0
  73. package/dist/vendor/spec-core/text/index.js.map +1 -1
  74. package/dist/vendor/spec-core/text/width.d.ts +30 -0
  75. package/dist/vendor/spec-core/text/width.js +113 -0
  76. package/dist/vendor/spec-core/text/width.js.map +1 -0
  77. package/dist/versions.d.ts +27 -1
  78. package/dist/versions.js +23 -1
  79. package/dist/versions.js.map +1 -1
  80. package/dist/workspace.d.ts +6 -1
  81. package/dist/workspace.js +17 -6
  82. package/dist/workspace.js.map +1 -1
  83. package/package.json +1 -1
  84. package/skills/close-round/SKILL.md +4 -1
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,C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E,CAAC,CAAC;IACxK,CAAC;IAED,OAAO;QACL,QAAQ,EAAE,GAAG,KAAK,KAAK,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,IAAI;QAC5D,QAAQ;QACR,OAAO;QACP,UAAU;QACV,mBAAmB,EAAE,QAAQ;QAC7B,eAAe;QACf,qBAAqB;QACrB,qBAAqB;KACtB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * What an agent needs to start a round, and nothing it does not.\n *\n * The brief in full - it is the contract, and a summary of a contract is a\n * different contract. Then what the brief implies but does not say: the scope\n * as the guard will read it, the rulings already signed, the briefs it waits\n * on, the rules spec-guard holds the scope's code to, and the documents the\n * brief cites. The cited documents are the one part that can be large, so\n * they fill what the budget leaves, in the order the brief cites them, and\n * the rest are named rather than dropped silently. So is a document whose\n * front matter is never closed, whose status cannot be read, rather than\n * shown as one without a status, and a pattern in the scope, a protection or\n * a ruling's path the guard cannot read, with spec-core's reason and what the\n * guard does without it, rather than listed as one it can.\n */\n\nimport { sameId } from './branch.js';\nimport { whyUnreadable } from './guard.js';\nimport type { BriefRow } from './types.js';\n\nexport interface CitedDocument {\n readonly path: string;\n readonly title: string | null;\n readonly status: string | null;\n /** `null` when the link does not resolve to a readable file. */\n readonly text: string | null;\n /** YAML front matter opened on line 1 and never closed, so no status was read from it. */\n readonly unclosedFrontMatter?: boolean | undefined;\n}\n\nexport interface RuleInForce {\n readonly document: string;\n readonly line: number;\n readonly kind: string;\n readonly description: string;\n readonly reason: string | null;\n}\n\n/**\n * The rules in force for the scope; `none` when spec-guard reads no\n * specification here, so none can be in force; `unavailable` when the rules\n * could not be read.\n */\nexport type Rules = readonly RuleInForce[] | { readonly none: string } | { readonly unavailable: string };\n\ninterface QueryDocument {\n readonly specFiles?: unknown;\n readonly results?: readonly { readonly rules?: readonly (RuleInForce & { readonly reason?: string | null; readonly inForce?: boolean })[] }[];\n}\n\n/**\n * spec-guard's answer to `query --json`, read. It exits 2 both when no spec\n * file matched its patterns - a repository that keeps none, or keeps them\n * where it does not look - and when it could not read the specs it has; only\n * the first prints a document, one with no spec file in it, so that is how\n * the two are told apart. What it said on stderr is the reason for the second.\n */\nexport function readRules(answer: { readonly code: number; readonly document: unknown; readonly stderr: string }): Rules {\n const document = (answer.document ?? {}) as QueryDocument;\n if (answer.code !== 0) {\n if (Array.isArray(document.specFiles) && document.specFiles.length === 0) {\n return { none: 'no spec file matched its patterns (\"specs\" in its configuration, docs/**/*.md by default)' };\n }\n const said = (answer.stderr.trim().split('\\n')[0] ?? '').replace(/^spec-guard:\\s*/, '');\n return { unavailable: said === '' ? `spec-guard exited ${answer.code}` : `spec-guard exited ${answer.code}: ${said}` };\n }\n const seen = new Set<string>();\n const out: RuleInForce[] = [];\n for (const result of document.results ?? []) {\n for (const rule of result.rules ?? []) {\n const key = `${rule.document}:${rule.line}`;\n if (rule.inForce === false || seen.has(key)) continue;\n seen.add(key);\n out.push({ document: rule.document, line: rule.line, kind: rule.kind, description: rule.description, reason: rule.reason ?? null });\n }\n }\n return out;\n}\n\nexport interface RulingInForce {\n readonly id: string;\n readonly paths: readonly string[];\n readonly signer: string;\n}\n\nexport interface ContextInput {\n readonly brief: BriefRow;\n readonly briefText: string;\n readonly dependencies: readonly BriefRow[];\n readonly cited: readonly CitedDocument[];\n /** The rules in force for the scope, none because spec-guard reads no specification, or why they could not be read. */\n readonly rules: Rules;\n readonly rulings: readonly RulingInForce[];\n readonly branch: string | null;\n readonly base: string | null;\n readonly budget: number;\n}\n\n/** A pattern in the brief's scope or protections that the guard cannot read, with spec-core's reason. */\nexport interface UnreadablePattern {\n readonly pattern: string;\n readonly reason: string;\n}\n\n/** A path of a ruling in force that the guard cannot read, with the ruling's id and spec-core's reason. */\nexport interface UnreadableRulingPath extends UnreadablePattern {\n readonly ruling: string;\n}\n\nexport interface ContextPacket {\n readonly markdown: string;\n /** Cited documents included whole. */\n readonly included: readonly string[];\n /** Cited documents named but left out for the budget. */\n readonly omitted: readonly string[];\n /** Links in the brief that resolve to nothing. */\n readonly unresolved: readonly string[];\n /** Cited documents whose front matter opens on line 1 and is never closed, so no status was read from them. */\n readonly unclosedFrontMatter: readonly string[];\n /** Patterns in `affectedFiles` the guard cannot read, in the brief's order: each puts no path in the scope. */\n readonly unreadableScope: readonly UnreadablePattern[];\n /** Patterns in `protectedFiles` the guard cannot read, in the brief's order: while one stands, the guard refuses every write but to the brief. */\n readonly unreadableProtections: readonly UnreadablePattern[];\n /** Paths of the rulings in force the guard cannot read, in the order the rulings are listed: each allows nothing. */\n readonly unreadableRulingPaths: readonly UnreadableRulingPath[];\n}\n\nfunction list(items: readonly string[]): string {\n return items.map((item) => `- \\`${item}\\``).join('\\n');\n}\n\n/**\n * Each pattern a line, as the guard reads it: as written, or with spec-core's\n * reason the guard cannot read it and what the guard does without it. The\n * guard's own compile decides, so the packet and the guard cannot disagree.\n */\nfunction patternLines(patterns: readonly string[], consequence: string): { lines: string[]; unreadable: UnreadablePattern[] } {\n const unreadable: UnreadablePattern[] = [];\n const lines = patterns.map((pattern) => {\n const reason = whyUnreadable(pattern);\n if (reason === null) return `- \\`${pattern}\\``;\n unreadable.push({ pattern, reason });\n return `- \\`${pattern}\\`, which the guard cannot read: ${reason}; ${consequence}`;\n });\n return { lines, unreadable };\n}\n\nfunction rulesSection(rules: Rules, scopeUnread: boolean): string {\n if ('none' in rules) return `spec-guard holds no rule over this scope: ${rules.none}.`;\n if ('unavailable' in rules) {\n return `The rules spec-guard holds this code to could not be read: ${rules.unavailable}. Treat every ADR as binding until they can.`;\n }\n if (rules.length === 0) {\n // With no pattern of the scope readable, spec-guard was asked about no\n // path, so an empty answer is no answer: \"no rule\" would tell the agent\n // the code it writes is unconstrained.\n return scopeUnread\n ? 'The scope could not be read: no pattern in `affectedFiles` can be read, so spec-guard was not asked for the rules over it. Treat every ADR as binding until the scope is fixed.'\n : 'spec-guard holds no rule over this scope.';\n }\n const byDocument = new Map<string, RuleInForce[]>();\n for (const rule of rules) byDocument.set(rule.document, [...(byDocument.get(rule.document) ?? []), rule]);\n const parts: string[] = [];\n for (const [document, found] of byDocument) {\n parts.push(`### ${document}`, '');\n for (const rule of found) parts.push(`- line ${rule.line}: ${rule.description}${rule.reason === null ? '' : ` - ${rule.reason}`}`);\n parts.push('');\n }\n return parts.join('\\n').trimEnd();\n}\n\n/**\n * A brief's title without the id it repeats: `012 - Rotate tokens` read as\n * `Rotate tokens`, and the same with an en or an em dash, which `spec-brief\n * new` writes, or with a colon after the id. Only the brief's own id is taken\n * off: `Fix - the login bug` is a title, not an id and a title.\n */\nexport function titleOf(brief: Pick<BriefRow, 'id' | 'title'>): string | null {\n if (brief.title === null) return null;\n return brief.title.replace(/^\\s*([^\\s:]+)(?:\\s+[-\\u2013\\u2014]|:)\\s+/, (whole, first: string) => (sameId(first, brief.id) ? '' : whole));\n}\n\n/** Renders the packet, filling the budget with cited documents in the order the brief cites them. */\nexport function renderContext(input: ContextInput): ContextPacket {\n const { brief } = input;\n const title = titleOf(brief);\n const header = [\n `# Round ${brief.id}${title === null ? '' : `: ${title}`}`,\n '',\n [\n `Status ${brief.status ?? 'unknown'}`,\n brief.wave === null ? null : `wave ${brief.wave}`,\n input.branch === null ? null : `branch \\`${input.branch}\\``,\n input.base === null ? null : `measured from \\`${input.base}\\``,\n ]\n .filter((part) => part !== null)\n .join(' · '),\n '',\n ].join('\\n');\n\n const contract = ['## The contract', '', `\\`${brief.file}\\`, in full:`, '', '````markdown', input.briefText.trimEnd(), '````', ''].join('\\n');\n\n // The guard passes over a ruling's path it cannot read, so the path allows\n // nothing. The paths share a line, so the note is in parentheses, closed\n // before the next path.\n const unreadableRulingPaths: UnreadableRulingPath[] = [];\n const rulings =\n input.rulings.length === 0\n ? '- none'\n : input.rulings\n .map((ruling) => {\n const paths = ruling.paths.map((pattern) => {\n const reason = whyUnreadable(pattern);\n if (reason === null) return `\\`${pattern}\\``;\n unreadableRulingPaths.push({ ruling: ruling.id, pattern, reason });\n return `\\`${pattern}\\` (which the guard cannot read: ${reason}; it allows nothing)`;\n });\n return `- ${ruling.id}, signed by ${ruling.signer}: ${paths.join(', ')}`;\n })\n .join('\\n');\n const mayWrite = patternLines(brief.affectedFiles, 'it puts no path in the scope');\n const unreadableScope = mayWrite.unreadable;\n // While a protection the guard cannot read stands, the guard refuses every\n // write, and no ruling waives it; a write to the brief is let through,\n // since that is where it is fixed.\n const mustNot = patternLines(brief.protectedFiles, 'until it is fixed, the guard refuses every write but to the brief');\n const unreadableProtections = mustNot.unreadable;\n const scope = [\n '## Scope, as the guard reads it',\n '',\n 'May write:',\n mayWrite.lines.length === 0 ? '- nothing declared: every write is outside the scope' : mayWrite.lines.join('\\n'),\n '',\n 'Must not change without a ruling:',\n mustNot.lines.length === 0 ? '- nothing declared' : mustNot.lines.join('\\n'),\n '',\n 'Rulings in force:',\n rulings,\n '',\n ].join('\\n');\n\n const waiting = input.dependencies.map((dependency) => {\n const state = dependency.phase === 'archived' ? 'archived, done' : `still ${dependency.status ?? 'live'}`;\n const named = titleOf(dependency);\n return `- ${dependency.id}${named === null ? '' : ` ${named}`}: ${state}`;\n });\n const dependencies = ['## Depends on', '', waiting.length === 0 ? '- nothing' : waiting.join('\\n'), ''].join('\\n');\n\n const scopeUnread = mayWrite.lines.length > 0 && unreadableScope.length === mayWrite.lines.length;\n const rules = ['## Rules in force for this scope', '', rulesSection(input.rules, scopeUnread), ''].join('\\n');\n\n const howTo = [\n '## How this round works',\n '',\n '- Before writing a file, ask whether the round may: `spec-harness guard <path>`, or the `check_path` tool.',\n '- A protected file is changed only under a ruling a person signs. If the round cannot be done without one, stop and ask: `spec-harness escalate --path <file> --reason <why>`, or the `request_escalation` tool. Do not work around it.',\n '- Every box in the brief ends ticked, or with a note under it that starts with a disposition (`**Delegated`, `**Accepted debt`, `**Rejected`, or what the repository configures).',\n '- When the work is done, run `spec-harness audit` and fix what it reports. The archive is a person\\'s decision, not the round\\'s.',\n '',\n ].join('\\n');\n\n const fixed = [header, contract, scope, dependencies, rules, howTo].join('\\n');\n const included: string[] = [];\n const omitted: string[] = [];\n const unresolved: string[] = [];\n const unclosed: string[] = [];\n const documents: string[] = [];\n let used = fixed.length;\n for (const cited of input.cited) {\n if (cited.text === null) {\n unresolved.push(cited.path);\n continue;\n }\n // Named whether or not the budget leaves room for it: the status is\n // unread either way, and the fix is the same.\n if (cited.unclosedFrontMatter === true) unclosed.push(cited.path);\n const heading = `### \\`${cited.path}\\`${cited.title === null ? '' : ` - ${cited.title}`}${cited.status === null ? '' : ` (${cited.status})`}`;\n const block = [heading, '', '````markdown', cited.text.trimEnd(), '````', ''].join('\\n');\n if (used + block.length > input.budget) {\n omitted.push(cited.path);\n continue;\n }\n used += block.length;\n included.push(cited.path);\n documents.push(block);\n }\n const citedSection = ['## Documents the brief cites', ''];\n if (documents.length === 0 && omitted.length === 0 && unresolved.length === 0) citedSection.push('None.', '');\n citedSection.push(...documents);\n if (omitted.length > 0) {\n citedSection.push(`Left out to stay within ${input.budget} characters; read them when the work reaches them:`, list(omitted), '');\n }\n if (unresolved.length > 0) citedSection.push('Cited but not found in the repository:', list(unresolved), '');\n if (unclosed.length > 0) {\n citedSection.push('Front matter opened on line 1 and never closed, so the status was not read; close the block with `---` on a line of its own:', list(unclosed), '');\n }\n\n return {\n markdown: `${fixed}\\n${citedSection.join('\\n').trimEnd()}\\n`,\n included,\n omitted,\n unresolved,\n unclosedFrontMatter: unclosed,\n unreadableScope,\n unreadableProtections,\n unreadableRulingPaths,\n };\n}\n"]}
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAiCnD;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,MAAsF;IAC9G,MAAM,QAAQ,GAAG,CAAC,MAAM,CAAC,QAAQ,IAAI,EAAE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,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC1B,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IACD,MAAM,YAAY,GAAG,CAAC,8BAA8B,EAAE,EAAE,CAAC,CAAC;IAC1D,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,YAAY,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IAC9G,YAAY,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC;IAChC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACvB,YAAY,CAAC,IAAI,CAAC,2BAA2B,KAAK,CAAC,MAAM,oDAAoD,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC;IACpI,CAAC;IACD,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC;QAAE,YAAY,CAAC,IAAI,CAAC,wCAAwC,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC;IAC7G,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACxB,YAAY,CAAC,IAAI,CAAC,8HAA8H,EAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC,CAAC;IACxK,CAAC;IAED,OAAO;QACL,QAAQ,EAAE,GAAG,KAAK,KAAK,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,IAAI;QAC5D,QAAQ;QACR,OAAO;QACP,UAAU;QACV,mBAAmB,EAAE,QAAQ;QAC7B,eAAe;QACf,qBAAqB;QACrB,qBAAqB;KACtB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * What an agent needs to start a round, and nothing it does not.\n *\n * The brief in full - it is the contract, and a summary of a contract is a\n * different contract. Then what the brief implies but does not say: the scope\n * as the guard will read it, the rulings already signed, the briefs it waits\n * on, the rules spec-guard holds the scope's code to, and the documents the\n * brief cites. The cited documents are the one part that can be large, so\n * they fill what the budget leaves, in the order the brief cites them, and\n * the rest are named rather than dropped silently. So is a document whose\n * front matter is never closed, whose status cannot be read, rather than\n * shown as one without a status, and a pattern in the scope, a protection or\n * a ruling's path the guard cannot read, with spec-core's reason and what the\n * guard does without it, rather than listed as one it can; and one a leading\n * `/` roots, which names no path the guard decides.\n */\n\nimport { sameId } from './branch.js';\nimport { rooted, whyUnreadable } from './guard.js';\nimport type { BriefRow } from './types.js';\n\nexport interface CitedDocument {\n readonly path: string;\n readonly title: string | null;\n readonly status: string | null;\n /** `null` when the link does not resolve to a readable file. */\n readonly text: string | null;\n /** YAML front matter opened on line 1 and never closed, so no status was read from it. */\n readonly unclosedFrontMatter?: boolean | undefined;\n}\n\nexport interface RuleInForce {\n readonly document: string;\n readonly line: number;\n readonly kind: string;\n readonly description: string;\n readonly reason: string | null;\n}\n\n/**\n * The rules in force for the scope; `none` when spec-guard reads no\n * specification here, so none can be in force; `unavailable` when the rules\n * could not be read.\n */\nexport type Rules = readonly RuleInForce[] | { readonly none: string } | { readonly unavailable: string };\n\ninterface QueryDocument {\n readonly specFiles?: unknown;\n readonly results?: readonly { readonly rules?: readonly (RuleInForce & { readonly reason?: string | null; readonly inForce?: boolean })[] }[];\n}\n\n/**\n * spec-guard's answer to `query --json`, read. It exits 2 both when no spec\n * file matched its patterns - a repository that keeps none, or keeps them\n * where it does not look - and when it could not read the specs it has; only\n * the first prints a document, one with no spec file in it, so that is how\n * the two are told apart. What it said on stderr is the reason for the second.\n */\nexport function readRules(answer: { readonly code: number; readonly document: unknown; readonly stderr: string }): Rules {\n const document = (answer.document ?? {}) as QueryDocument;\n if (answer.code !== 0) {\n if (Array.isArray(document.specFiles) && document.specFiles.length === 0) {\n return { none: 'no spec file matched its patterns (\"specs\" in its configuration, docs/**/*.md by default)' };\n }\n const said = (answer.stderr.trim().split('\\n')[0] ?? '').replace(/^spec-guard:\\s*/, '');\n return { unavailable: said === '' ? `spec-guard exited ${answer.code}` : `spec-guard exited ${answer.code}: ${said}` };\n }\n const seen = new Set<string>();\n const out: RuleInForce[] = [];\n for (const result of document.results ?? []) {\n for (const rule of result.rules ?? []) {\n const key = `${rule.document}:${rule.line}`;\n if (rule.inForce === false || seen.has(key)) continue;\n seen.add(key);\n out.push({ document: rule.document, line: rule.line, kind: rule.kind, description: rule.description, reason: rule.reason ?? null });\n }\n }\n return out;\n}\n\nexport interface RulingInForce {\n readonly id: string;\n readonly paths: readonly string[];\n readonly signer: string;\n}\n\nexport interface ContextInput {\n readonly brief: BriefRow;\n readonly briefText: string;\n readonly dependencies: readonly BriefRow[];\n readonly cited: readonly CitedDocument[];\n /** The rules in force for the scope, none because spec-guard reads no specification, or why they could not be read. */\n readonly rules: Rules;\n readonly rulings: readonly RulingInForce[];\n readonly branch: string | null;\n readonly base: string | null;\n readonly budget: number;\n}\n\n/** A pattern in the brief's scope or protections that the guard cannot read, with spec-core's reason. */\nexport interface UnreadablePattern {\n readonly pattern: string;\n readonly reason: string;\n}\n\n/** A path of a ruling in force that the guard cannot read, with the ruling's id and spec-core's reason. */\nexport interface UnreadableRulingPath extends UnreadablePattern {\n readonly ruling: string;\n}\n\nexport interface ContextPacket {\n readonly markdown: string;\n /** Cited documents included whole. */\n readonly included: readonly string[];\n /** Cited documents named but left out for the budget. */\n readonly omitted: readonly string[];\n /** Links in the brief that resolve to nothing. */\n readonly unresolved: readonly string[];\n /** Cited documents whose front matter opens on line 1 and is never closed, so no status was read from them. */\n readonly unclosedFrontMatter: readonly string[];\n /** Patterns in `affectedFiles` the guard cannot read, in the brief's order: each puts no path in the scope. */\n readonly unreadableScope: readonly UnreadablePattern[];\n /** Patterns in `protectedFiles` the guard cannot read, in the brief's order: while one stands, the guard refuses every write but to the brief. */\n readonly unreadableProtections: readonly UnreadablePattern[];\n /** Paths of the rulings in force the guard cannot read, in the order the rulings are listed: each allows nothing. */\n readonly unreadableRulingPaths: readonly UnreadableRulingPath[];\n}\n\nfunction list(items: readonly string[]): string {\n return items.map((item) => `- \\`${item}\\``).join('\\n');\n}\n\n/**\n * Each pattern a line, as the guard reads it: as written, or with spec-core's\n * reason the guard cannot read it and what the guard does without it. The\n * guard's own compile decides, so the packet and the guard cannot disagree.\n * With `rootedNote`, a pattern a leading `/` roots, or one of whose\n * alternatives it roots, is marked too, and counted when every alternative\n * is rooted.\n */\nfunction patternLines(\n patterns: readonly string[],\n consequence: string,\n rootedNote?: { readonly whole: string; readonly part: string },\n): { lines: string[]; unreadable: UnreadablePattern[]; rootedWhole: number } {\n const unreadable: UnreadablePattern[] = [];\n let rootedWhole = 0;\n const lines = patterns.map((pattern) => {\n const reason = whyUnreadable(pattern);\n if (reason === null) {\n const root = rootedNote === undefined ? null : rooted(pattern);\n if (root === null) return `- \\`${pattern}\\``;\n if (root === 'whole') rootedWhole += 1;\n return `- \\`${pattern}\\`, ${(rootedNote as { whole: string; part: string })[root]}`;\n }\n unreadable.push({ pattern, reason });\n return `- \\`${pattern}\\`, which the guard cannot read: ${reason}; ${consequence}`;\n });\n return { lines, unreadable, rootedWhole };\n}\n\nfunction rulesSection(rules: Rules, scopeUnread: boolean, scopeRooted: boolean): string {\n if ('none' in rules) return `spec-guard holds no rule over this scope: ${rules.none}.`;\n if ('unavailable' in rules) {\n return `The rules spec-guard holds this code to could not be read: ${rules.unavailable}. Treat every ADR as binding until they can.`;\n }\n if (rules.length === 0) {\n // With no pattern of the scope readable, spec-guard was asked about no\n // path, so an empty answer is no answer: \"no rule\" would tell the agent\n // the code it writes is unconstrained.\n if (scopeUnread) {\n return 'The scope could not be read: no pattern in `affectedFiles` can be read, so spec-guard was not asked for the rules over it. Treat every ADR as binding until the scope is fixed.';\n }\n return scopeRooted\n ? \"No pattern in `affectedFiles` puts a path in the scope: each is rooted at the filesystem's root or cannot be read, so spec-guard was not asked for the rules over it. Treat every ADR as binding until the scope is fixed.\"\n : 'spec-guard holds no rule over this scope.';\n }\n const byDocument = new Map<string, RuleInForce[]>();\n for (const rule of rules) byDocument.set(rule.document, [...(byDocument.get(rule.document) ?? []), rule]);\n const parts: string[] = [];\n for (const [document, found] of byDocument) {\n parts.push(`### ${document}`, '');\n for (const rule of found) parts.push(`- line ${rule.line}: ${rule.description}${rule.reason === null ? '' : ` - ${rule.reason}`}`);\n parts.push('');\n }\n return parts.join('\\n').trimEnd();\n}\n\n/**\n * A brief's title without the id it repeats, by the rules spec-brief reads\n * it with: the brief's own id, then an em dash, which `spec-brief new`\n * writes, an en dash, a full-width colon or a colon, spaced or not, or a\n * hyphen with a space on each side; `012 - Rotate tokens`, `012\\u2014Rotate\n * tokens` and `012\\uFF1ARotate tokens` read as `Rotate tokens`. A bare hyphen\n * is part of a word or a number, as in `001-2 migration`, and only the\n * brief's own id is taken off: `Fix - the login bug` is a title, and so is\n * `0010 \\u2014 x` on brief 001.\n */\nexport function titleOf(brief: Pick<BriefRow, 'id' | 'title'>): string | null {\n if (brief.title === null) return null;\n return brief.title.replace(/^\\s*([^\\s:\\uFF1A\\u2013\\u2014]+)(?:\\s*[:\\uFF1A\\u2013\\u2014]\\s*|\\s+-\\s+)(?=\\S)/, (whole, first: string) =>\n sameId(first, brief.id) ? '' : whole,\n );\n}\n\n/** Renders the packet, filling the budget with cited documents in the order the brief cites them. */\nexport function renderContext(input: ContextInput): ContextPacket {\n const { brief } = input;\n const title = titleOf(brief);\n const header = [\n `# Round ${brief.id}${title === null ? '' : `: ${title}`}`,\n '',\n [\n `Status ${brief.status ?? 'unknown'}`,\n brief.wave === null ? null : `wave ${brief.wave}`,\n input.branch === null ? null : `branch \\`${input.branch}\\``,\n input.base === null ? null : `measured from \\`${input.base}\\``,\n ]\n .filter((part) => part !== null)\n .join(' · '),\n '',\n ].join('\\n');\n\n const contract = ['## The contract', '', `\\`${brief.file}\\`, in full:`, '', '````markdown', input.briefText.trimEnd(), '````', ''].join('\\n');\n\n // The guard passes over a ruling's path it cannot read, so the path allows\n // nothing. The paths share a line, so the note is in parentheses, closed\n // before the next path.\n const unreadableRulingPaths: UnreadableRulingPath[] = [];\n const rulings =\n input.rulings.length === 0\n ? '- none'\n : input.rulings\n .map((ruling) => {\n const paths = ruling.paths.map((pattern) => {\n const reason = whyUnreadable(pattern);\n if (reason === null) {\n // A rooted path can be read, and names no path the guard decides.\n const root = rooted(pattern);\n if (root === 'whole') return `\\`${pattern}\\` (which a leading \\`/\\` roots at the filesystem's root; it allows nothing)`;\n if (root === 'part') return `\\`${pattern}\\` (an alternative of which a leading \\`/\\` roots at the filesystem's root; that alternative allows nothing)`;\n return `\\`${pattern}\\``;\n }\n unreadableRulingPaths.push({ ruling: ruling.id, pattern, reason });\n return `\\`${pattern}\\` (which the guard cannot read: ${reason}; it allows nothing)`;\n });\n return `- ${ruling.id}, signed by ${ruling.signer}: ${paths.join(', ')}`;\n })\n .join('\\n');\n // A rooted pattern can be read and puts no path in the scope: every path\n // the guard decides is repository-relative. spec-guard is not asked about it.\n const mayWrite = patternLines(brief.affectedFiles, 'it puts no path in the scope', {\n whole: \"which a leading `/` roots at the filesystem's root: it puts no path in the scope, and spec-guard is not asked about it\",\n part: \"an alternative of which a leading `/` roots at the filesystem's root: that alternative puts no path in the scope, and spec-guard is not asked about it\",\n });\n const unreadableScope = mayWrite.unreadable;\n // While a protection the guard cannot read stands, the guard refuses every\n // write, and no ruling waives it; a write to the brief is let through,\n // since that is where it is fixed. A rooted protection can be read, and\n // protects nothing: the file it was meant to protect is the round's to write.\n const mustNot = patternLines(brief.protectedFiles, 'until it is fixed, the guard refuses every write but to the brief', {\n whole: \"which a leading `/` roots at the filesystem's root: it protects no path\",\n part: \"an alternative of which a leading `/` roots at the filesystem's root: that alternative protects no path\",\n });\n const unreadableProtections = mustNot.unreadable;\n const scope = [\n '## Scope, as the guard reads it',\n '',\n 'May write:',\n mayWrite.lines.length === 0 ? '- nothing declared: every write is outside the scope' : mayWrite.lines.join('\\n'),\n '',\n 'Must not change without a ruling:',\n mustNot.lines.length === 0 ? '- nothing declared' : mustNot.lines.join('\\n'),\n '',\n 'Rulings in force:',\n rulings,\n '',\n ].join('\\n');\n\n const waiting = input.dependencies.map((dependency) => {\n const state = dependency.phase === 'archived' ? 'archived, done' : `still ${dependency.status ?? 'live'}`;\n const named = titleOf(dependency);\n return `- ${dependency.id}${named === null ? '' : ` ${named}`}: ${state}`;\n });\n const dependencies = ['## Depends on', '', waiting.length === 0 ? '- nothing' : waiting.join('\\n'), ''].join('\\n');\n\n const scopeUnread = mayWrite.lines.length > 0 && unreadableScope.length === mayWrite.lines.length;\n const scopeRooted = mayWrite.rootedWhole > 0 && unreadableScope.length + mayWrite.rootedWhole === mayWrite.lines.length;\n const rules = ['## Rules in force for this scope', '', rulesSection(input.rules, scopeUnread, scopeRooted), ''].join('\\n');\n\n const howTo = [\n '## How this round works',\n '',\n '- Before writing a file, ask whether the round may: `spec-harness guard <path>`, or the `check_path` tool.',\n '- A protected file is changed only under a ruling a person signs. If the round cannot be done without one, stop and ask: `spec-harness escalate --path <file> --reason <why>`, or the `request_escalation` tool. Do not work around it.',\n '- Every box in the brief ends ticked, or with a note under it that starts with a disposition (`**Delegated`, `**Accepted debt`, `**Rejected`, or what the repository configures).',\n '- When the work is done, run `spec-harness audit` and fix what it reports. The archive is a person\\'s decision, not the round\\'s.',\n '',\n ].join('\\n');\n\n const fixed = [header, contract, scope, dependencies, rules, howTo].join('\\n');\n const included: string[] = [];\n const omitted: string[] = [];\n const unresolved: string[] = [];\n const unclosed: string[] = [];\n const documents: string[] = [];\n let used = fixed.length;\n for (const cited of input.cited) {\n if (cited.text === null) {\n unresolved.push(cited.path);\n continue;\n }\n // Named whether or not the budget leaves room for it: the status is\n // unread either way, and the fix is the same.\n if (cited.unclosedFrontMatter === true) unclosed.push(cited.path);\n const heading = `### \\`${cited.path}\\`${cited.title === null ? '' : ` - ${cited.title}`}${cited.status === null ? '' : ` (${cited.status})`}`;\n const block = [heading, '', '````markdown', cited.text.trimEnd(), '````', ''].join('\\n');\n if (used + block.length > input.budget) {\n omitted.push(cited.path);\n continue;\n }\n used += block.length;\n included.push(cited.path);\n documents.push(block);\n }\n const citedSection = ['## Documents the brief cites', ''];\n if (documents.length === 0 && omitted.length === 0 && unresolved.length === 0) citedSection.push('None.', '');\n citedSection.push(...documents);\n if (omitted.length > 0) {\n citedSection.push(`Left out to stay within ${input.budget} characters; read them when the work reaches them:`, list(omitted), '');\n }\n if (unresolved.length > 0) citedSection.push('Cited but not found in the repository:', list(unresolved), '');\n if (unclosed.length > 0) {\n citedSection.push('Front matter opened on line 1 and never closed, so the status was not read; close the block with `---` on a line of its own:', list(unclosed), '');\n }\n\n return {\n markdown: `${fixed}\\n${citedSection.join('\\n').trimEnd()}\\n`,\n included,\n omitted,\n unresolved,\n unclosedFrontMatter: unclosed,\n unreadableScope,\n unreadableProtections,\n unreadableRulingPaths,\n };\n}\n"]}
@@ -27,7 +27,8 @@ export interface DocumentReader {
27
27
  sectionTables(text: string, section: string): SectionTables;
28
28
  citations(text: string): Citation[];
29
29
  /**
30
- * The first level-one heading, and the front matter's status. YAML front
30
+ * The first level-one heading, and the front matter's status, under
31
+ * `status`, `狀態` or `状态`, the first the document holds. YAML front
31
32
  * matter opened on line 1 and never closed is `unclosedFrontMatter`: none
32
33
  * of it is read, so a status its author wrote there reads as none.
33
34
  */
@@ -1 +1 @@
1
- {"version":3,"file":"document.js","sourceRoot":"","sources":["../src/document.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG","sourcesContent":["/**\n * What the harness reads out of a brief or a cited document, through\n * spec-core's Markdown scanner so that code and comments are never mistaken\n * for structure: fenced blocks with their info strings, the section a line\n * sits in, a section's tables, the relative links a document cites, and a\n * document's title and status.\n */\n\nimport type { CodeBlock } from './probe.js';\nimport type { TableView } from './rulings.js';\n\nexport interface Citation {\n readonly target: string;\n /** 1-based. */\n readonly line: number;\n}\n\nexport interface SectionTables {\n readonly tables: readonly TableView[];\n /** 1-based line of the section's heading, or `null` when there is no such section. */\n readonly headingLine: number | null;\n /** 0-based index of the line after the section's last table row, or `null` when it has no table. */\n readonly tableEndLine: number | null;\n}\n\nexport interface DocumentReader {\n codeBlocks(text: string): CodeBlock[];\n sectionAt(text: string, line: number): string | null;\n /** Every section a line sits in, outermost first: a `###` under a `##` is in both. */\n sectionsAt(text: string, line: number): string[];\n sectionTables(text: string, section: string): SectionTables;\n citations(text: string): Citation[];\n /**\n * The first level-one heading, and the front matter's status. YAML front\n * matter opened on line 1 and never closed is `unclosedFrontMatter`: none\n * of it is read, so a status its author wrote there reads as none.\n */\n titleAndStatus(text: string): { readonly title: string | null; readonly status: string | null; readonly unclosedFrontMatter: boolean };\n}\n"]}
1
+ {"version":3,"file":"document.js","sourceRoot":"","sources":["../src/document.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG","sourcesContent":["/**\n * What the harness reads out of a brief or a cited document, through\n * spec-core's Markdown scanner so that code and comments are never mistaken\n * for structure: fenced blocks with their info strings, the section a line\n * sits in, a section's tables, the relative links a document cites, and a\n * document's title and status.\n */\n\nimport type { CodeBlock } from './probe.js';\nimport type { TableView } from './rulings.js';\n\nexport interface Citation {\n readonly target: string;\n /** 1-based. */\n readonly line: number;\n}\n\nexport interface SectionTables {\n readonly tables: readonly TableView[];\n /** 1-based line of the section's heading, or `null` when there is no such section. */\n readonly headingLine: number | null;\n /** 0-based index of the line after the section's last table row, or `null` when it has no table. */\n readonly tableEndLine: number | null;\n}\n\nexport interface DocumentReader {\n codeBlocks(text: string): CodeBlock[];\n sectionAt(text: string, line: number): string | null;\n /** Every section a line sits in, outermost first: a `###` under a `##` is in both. */\n sectionsAt(text: string, line: number): string[];\n sectionTables(text: string, section: string): SectionTables;\n citations(text: string): Citation[];\n /**\n * The first level-one heading, and the front matter's status, under\n * `status`, `狀態` or `状态`, the first the document holds. YAML front\n * matter opened on line 1 and never closed is `unclosedFrontMatter`: none\n * of it is read, so a status its author wrote there reads as none.\n */\n titleAndStatus(text: string): { readonly title: string | null; readonly status: string | null; readonly unclosedFrontMatter: boolean };\n}\n"]}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Findings in the formats a forge reads beside a change: GitLab Code Quality,
3
+ * SARIF 2.1.0 and GitHub workflow commands (spec-core ADR-0005).
4
+ *
5
+ * The shapes are the siblings': spec-brief's severities and its hint in the
6
+ * text, spec-guard's fingerprint of a finding's identity. Pure: the command
7
+ * prints what these return.
8
+ */
9
+ import type { Finding } from './types.js';
10
+ /** The formats that place findings, which `audit` and `premises` print. */
11
+ export type FindingFormat = 'gitlab' | 'sarif' | 'github';
12
+ export declare const FINDING_FORMATS: readonly FindingFormat[];
13
+ export interface FormatOptions {
14
+ /** Where a finding with no file of its own is placed: the brief the command is about. */
15
+ readonly file: string;
16
+ /** This tool's version, which SARIF names. */
17
+ readonly version: string;
18
+ /** What the run measured, which SARIF carries as a note beside its results. */
19
+ readonly summary?: string | undefined;
20
+ }
21
+ /** GitLab Code Quality: a JSON array of issues, which a merge request shows beside the lines they are on. */
22
+ export declare function formatGitlab(findings: readonly Finding[], options: FormatOptions): string;
23
+ /**
24
+ * SARIF 2.1.0, for code scanning. What the run measured is a note in the
25
+ * invocation, SARIF's place for what happened in a run that is not a finding,
26
+ * so a page with no result still says what was checked.
27
+ */
28
+ export declare function formatSarif(findings: readonly Finding[], options: FormatOptions): string;
29
+ /** GitHub Actions workflow commands, one line each, which a job's log turns into annotations on the diff. */
30
+ export declare function formatGithub(findings: readonly Finding[], options: FormatOptions): string;
31
+ export declare function formatFindings(format: FindingFormat, findings: readonly Finding[], options: FormatOptions): string;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Findings in the formats a forge reads beside a change: GitLab Code Quality,
3
+ * SARIF 2.1.0 and GitHub workflow commands (spec-core ADR-0005).
4
+ *
5
+ * The shapes are the siblings': spec-brief's severities and its hint in the
6
+ * text, spec-guard's fingerprint of a finding's identity. Pure: the command
7
+ * prints what these return.
8
+ */
9
+ import { createHash } from 'node:crypto';
10
+ import { RULES } from './audit.js';
11
+ export const FINDING_FORMATS = ['gitlab', 'sarif', 'github'];
12
+ /**
13
+ * GitLab's severities. An error fails the run, but it is not the crash or the
14
+ * security hole `critical` and `blocker` say in GitLab's own reports, so the
15
+ * scale tops out at `major`, as spec-brief's does.
16
+ */
17
+ const GITLAB_SEVERITY = { error: 'major', warning: 'minor', note: 'info' };
18
+ const SARIF_LEVEL = { error: 'error', warning: 'warning', note: 'note' };
19
+ const GITHUB_COMMAND = { error: 'error', warning: 'warning', note: 'notice' };
20
+ /**
21
+ * Each finding with its place and its fingerprint. A finding about a whole
22
+ * brief is placed on the brief's first line. The fingerprint is the SHA-256
23
+ * of the finding's identity - its rule, its file and its subject - and never
24
+ * of its message, hint or line: GitLab tells a new finding from one it has
25
+ * seen by it, so a reworded message or a line added above must not read as
26
+ * one problem fixed and another found. Two findings with one identity are
27
+ * told apart by the order they come in.
28
+ */
29
+ function place(findings, fallback) {
30
+ const seen = new Map();
31
+ return findings.map((finding) => {
32
+ const file = finding.file ?? fallback;
33
+ const identity = [finding.rule, file, finding.subject ?? ''].join('\u0000');
34
+ const repeat = seen.get(identity) ?? 0;
35
+ seen.set(identity, repeat + 1);
36
+ const fingerprint = createHash('sha256').update(repeat === 0 ? identity : `${identity}\u0000${repeat}`).digest('hex');
37
+ return { finding, file, line: Math.max(finding.line ?? 1, 1), fingerprint };
38
+ });
39
+ }
40
+ /**
41
+ * The message and the next action, which every format carries (spec-core
42
+ * ADR-0005). A message a sibling ended with a full stop keeps one.
43
+ */
44
+ function text(finding) {
45
+ return `${finding.message.replace(/\.$/, '')}. ${finding.hint}`;
46
+ }
47
+ /** GitLab Code Quality: a JSON array of issues, which a merge request shows beside the lines they are on. */
48
+ export function formatGitlab(findings, options) {
49
+ const issues = place(findings, options.file).map(({ finding, file, line, fingerprint }) => ({
50
+ description: text(finding),
51
+ check_name: finding.rule,
52
+ fingerprint,
53
+ severity: GITLAB_SEVERITY[finding.severity],
54
+ location: { path: file, lines: { begin: line } },
55
+ }));
56
+ return `${JSON.stringify(issues, null, 2)}\n`;
57
+ }
58
+ /** How SARIF describes a rule: the audit's own words, or the archive rule spec-brief gave. */
59
+ function describeRule(id) {
60
+ if (id.startsWith('archive/'))
61
+ return `A reason spec-brief's archive gives: ${id.slice('archive/'.length)}.`;
62
+ return RULES[id] ?? id;
63
+ }
64
+ /**
65
+ * SARIF 2.1.0, for code scanning. What the run measured is a note in the
66
+ * invocation, SARIF's place for what happened in a run that is not a finding,
67
+ * so a page with no result still says what was checked.
68
+ */
69
+ export function formatSarif(findings, options) {
70
+ const placed = place(findings, options.file);
71
+ const ids = [...new Set(findings.map((finding) => finding.rule))].sort();
72
+ const document = {
73
+ $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
74
+ version: '2.1.0',
75
+ runs: [
76
+ {
77
+ ...(options.summary === undefined
78
+ ? {}
79
+ : { invocations: [{ executionSuccessful: true, toolExecutionNotifications: [{ level: 'note', message: { text: options.summary } }] }] }),
80
+ tool: {
81
+ driver: {
82
+ name: 'spec-harness',
83
+ version: options.version,
84
+ informationUri: 'https://github.com/DescentVTT/spec-harness',
85
+ rules: ids.map((id) => ({ id, shortDescription: { text: describeRule(id) } })),
86
+ },
87
+ },
88
+ results: placed.map(({ finding, file, line, fingerprint }) => ({
89
+ ruleId: finding.rule,
90
+ level: SARIF_LEVEL[finding.severity],
91
+ message: { text: text(finding) },
92
+ locations: [{ physicalLocation: { artifactLocation: { uri: file, uriBaseId: '%SRCROOT%' }, region: { startLine: line } } }],
93
+ partialFingerprints: { specHarnessFinding: fingerprint },
94
+ })),
95
+ },
96
+ ],
97
+ };
98
+ return `${JSON.stringify(document, null, 2)}\n`;
99
+ }
100
+ /** A workflow command's message: `%`, and the line breaks that would end the command. */
101
+ function escapeData(value) {
102
+ return value.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
103
+ }
104
+ /** A workflow command's property: as a message, and the `:` and `,` that would end the property. */
105
+ function escapeProperty(value) {
106
+ return escapeData(value).replace(/:/g, '%3A').replace(/,/g, '%2C');
107
+ }
108
+ /** GitHub Actions workflow commands, one line each, which a job's log turns into annotations on the diff. */
109
+ export function formatGithub(findings, options) {
110
+ return place(findings, options.file)
111
+ .map(({ finding, file, line }) => {
112
+ const properties = `file=${escapeProperty(file)},line=${line},title=${escapeProperty(`spec-harness ${finding.rule}`)}`;
113
+ return `::${GITHUB_COMMAND[finding.severity]} ${properties}::${escapeData(text(finding))}\n`;
114
+ })
115
+ .join('');
116
+ }
117
+ export function formatFindings(format, findings, options) {
118
+ switch (format) {
119
+ case 'gitlab':
120
+ return formatGitlab(findings, options);
121
+ case 'sarif':
122
+ return formatSarif(findings, options);
123
+ case 'github':
124
+ return formatGithub(findings, options);
125
+ }
126
+ }
127
+ //# sourceMappingURL=formats.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formats.js","sourceRoot":"","sources":["../src/formats.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAMnC,MAAM,CAAC,MAAM,eAAe,GAA6B,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AAWvF;;;;GAIG;AACH,MAAM,eAAe,GAAuC,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC/G,MAAM,WAAW,GAAuC,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC7G,MAAM,cAAc,GAAuC,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;AASlH;;;;;;;;GAQG;AACH,SAAS,KAAK,CAAC,QAA4B,EAAE,QAAgB;IAC3D,MAAM,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;IACvC,OAAO,QAAQ,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AAK,CAAC,CAAC;AAChF,CAAC;AAED,oGAAoG;AACpG,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,UAAU,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;AACrE,CAAC;AAED,6GAA6G;AAC7G,MAAM,UAAU,YAAY,CAAC,QAA4B,EAAE,OAAsB;IAC/E,OAAO,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,IAAI,CAAC;SACjC,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE;QAC/B,MAAM,UAAU,GAAG,QAAQ,cAAc,CAAC,IAAI,CAAC,SAAS,IAAI,UAAU,cAAc,CAAC,gBAAgB,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;QACvH,OAAO,KAAK,cAAc,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,UAAU,KAAK,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC;IAC/F,CAAC,CAAC;SACD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,MAAqB,EAAE,QAA4B,EAAE,OAAsB;IACxG,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,QAAQ;YACX,OAAO,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QACzC,KAAK,OAAO;YACV,OAAO,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QACxC,KAAK,QAAQ;YACX,OAAO,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC3C,CAAC;AACH,CAAC","sourcesContent":["/**\n * Findings in the formats a forge reads beside a change: GitLab Code Quality,\n * SARIF 2.1.0 and GitHub workflow commands (spec-core ADR-0005).\n *\n * The shapes are the siblings': spec-brief's severities and its hint in the\n * text, spec-guard's fingerprint of a finding's identity. Pure: the command\n * prints what these return.\n */\n\nimport { createHash } from 'node:crypto';\n\nimport { RULES } from './audit.js';\nimport type { Finding, Severity } from './types.js';\n\n/** The formats that place findings, which `audit` and `premises` print. */\nexport type FindingFormat = 'gitlab' | 'sarif' | 'github';\n\nexport const FINDING_FORMATS: readonly FindingFormat[] = ['gitlab', 'sarif', 'github'];\n\nexport interface FormatOptions {\n /** Where a finding with no file of its own is placed: the brief the command is about. */\n readonly file: string;\n /** This tool's version, which SARIF names. */\n readonly version: string;\n /** What the run measured, which SARIF carries as a note beside its results. */\n readonly summary?: string | undefined;\n}\n\n/**\n * GitLab's severities. An error fails the run, but it is not the crash or the\n * security hole `critical` and `blocker` say in GitLab's own reports, so the\n * scale tops out at `major`, as spec-brief's does.\n */\nconst GITLAB_SEVERITY: Readonly<Record<Severity, string>> = { error: 'major', warning: 'minor', note: 'info' };\nconst SARIF_LEVEL: Readonly<Record<Severity, string>> = { error: 'error', warning: 'warning', note: 'note' };\nconst GITHUB_COMMAND: Readonly<Record<Severity, string>> = { error: 'error', warning: 'warning', note: 'notice' };\n\ninterface Placed {\n readonly finding: Finding;\n readonly file: string;\n readonly line: number;\n readonly fingerprint: string;\n}\n\n/**\n * Each finding with its place and its fingerprint. A finding about a whole\n * brief is placed on the brief's first line. The fingerprint is the SHA-256\n * of the finding's identity - its rule, its file and its subject - and never\n * of its message, hint or line: GitLab tells a new finding from one it has\n * seen by it, so a reworded message or a line added above must not read as\n * one problem fixed and another found. Two findings with one identity are\n * told apart by the order they come in.\n */\nfunction place(findings: readonly Finding[], fallback: string): Placed[] {\n const seen = new Map<string, number>();\n return findings.map((finding) => {\n const file = finding.file ?? fallback;\n const identity = [finding.rule, file, finding.subject ?? ''].join('\\u0000');\n const repeat = seen.get(identity) ?? 0;\n seen.set(identity, repeat + 1);\n const fingerprint = createHash('sha256').update(repeat === 0 ? identity : `${identity}\\u0000${repeat}`).digest('hex');\n return { finding, file, line: Math.max(finding.line ?? 1, 1), fingerprint };\n });\n}\n\n/**\n * The message and the next action, which every format carries (spec-core\n * ADR-0005). A message a sibling ended with a full stop keeps one.\n */\nfunction text(finding: Finding): string {\n return `${finding.message.replace(/\\.$/, '')}. ${finding.hint}`;\n}\n\n/** GitLab Code Quality: a JSON array of issues, which a merge request shows beside the lines they are on. */\nexport function formatGitlab(findings: readonly Finding[], options: FormatOptions): string {\n const issues = place(findings, options.file).map(({ finding, file, line, fingerprint }) => ({\n description: text(finding),\n check_name: finding.rule,\n fingerprint,\n severity: GITLAB_SEVERITY[finding.severity],\n location: { path: file, lines: { begin: line } },\n }));\n return `${JSON.stringify(issues, null, 2)}\\n`;\n}\n\n/** How SARIF describes a rule: the audit's own words, or the archive rule spec-brief gave. */\nfunction describeRule(id: string): string {\n if (id.startsWith('archive/')) return `A reason spec-brief's archive gives: ${id.slice('archive/'.length)}.`;\n return RULES[id] ?? id;\n}\n\n/**\n * SARIF 2.1.0, for code scanning. What the run measured is a note in the\n * invocation, SARIF's place for what happened in a run that is not a finding,\n * so a page with no result still says what was checked.\n */\nexport function formatSarif(findings: readonly Finding[], options: FormatOptions): string {\n const placed = place(findings, options.file);\n const ids = [...new Set(findings.map((finding) => finding.rule))].sort();\n const document = {\n $schema: 'https://json.schemastore.org/sarif-2.1.0.json',\n version: '2.1.0',\n runs: [\n {\n ...(options.summary === undefined\n ? {}\n : { invocations: [{ executionSuccessful: true, toolExecutionNotifications: [{ level: 'note', message: { text: options.summary } }] }] }),\n tool: {\n driver: {\n name: 'spec-harness',\n version: options.version,\n informationUri: 'https://github.com/DescentVTT/spec-harness',\n rules: ids.map((id) => ({ id, shortDescription: { text: describeRule(id) } })),\n },\n },\n results: placed.map(({ finding, file, line, fingerprint }) => ({\n ruleId: finding.rule,\n level: SARIF_LEVEL[finding.severity],\n message: { text: text(finding) },\n locations: [{ physicalLocation: { artifactLocation: { uri: file, uriBaseId: '%SRCROOT%' }, region: { startLine: line } } }],\n partialFingerprints: { specHarnessFinding: fingerprint },\n })),\n },\n ],\n };\n return `${JSON.stringify(document, null, 2)}\\n`;\n}\n\n/** A workflow command's message: `%`, and the line breaks that would end the command. */\nfunction escapeData(value: string): string {\n return value.replace(/%/g, '%25').replace(/\\r/g, '%0D').replace(/\\n/g, '%0A');\n}\n\n/** A workflow command's property: as a message, and the `:` and `,` that would end the property. */\nfunction escapeProperty(value: string): string {\n return escapeData(value).replace(/:/g, '%3A').replace(/,/g, '%2C');\n}\n\n/** GitHub Actions workflow commands, one line each, which a job's log turns into annotations on the diff. */\nexport function formatGithub(findings: readonly Finding[], options: FormatOptions): string {\n return place(findings, options.file)\n .map(({ finding, file, line }) => {\n const properties = `file=${escapeProperty(file)},line=${line},title=${escapeProperty(`spec-harness ${finding.rule}`)}`;\n return `::${GITHUB_COMMAND[finding.severity]} ${properties}::${escapeData(text(finding))}\\n`;\n })\n .join('');\n}\n\nexport function formatFindings(format: FindingFormat, findings: readonly Finding[], options: FormatOptions): string {\n switch (format) {\n case 'gitlab':\n return formatGitlab(findings, options);\n case 'sarif':\n return formatSarif(findings, options);\n case 'github':\n return formatGithub(findings, options);\n }\n}\n"]}
package/dist/git.d.ts CHANGED
@@ -21,6 +21,12 @@ export declare class GitError extends Error {
21
21
  export declare function workTreeRoot(cwd: string): Promise<string | null>;
22
22
  /** The git directory every worktree of this repository shares. */
23
23
  export declare function commonDirectory(cwd: string): Promise<string | null>;
24
+ /**
25
+ * Where git runs the hook `name` from, absolute: `core.hooksPath` read as git
26
+ * reads it - relative to the work tree, absolute, or under `~` - and a linked
27
+ * worktree's shared hooks. `null` when git cannot say, before 2.31.
28
+ */
29
+ export declare function hookPath(name: string, cwd: string): Promise<string | null>;
24
30
  /** The checked-out branch's short name, or `null` on a detached head. */
25
31
  export declare function currentBranch(cwd: string): Promise<string | null>;
26
32
  /** The remote's default branch as a local ref, such as `origin/main`, or `null`. */
package/dist/git.js CHANGED
@@ -36,6 +36,14 @@ export async function workTreeRoot(cwd) {
36
36
  export async function commonDirectory(cwd) {
37
37
  return value(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);
38
38
  }
39
+ /**
40
+ * Where git runs the hook `name` from, absolute: `core.hooksPath` read as git
41
+ * reads it - relative to the work tree, absolute, or under `~` - and a linked
42
+ * worktree's shared hooks. `null` when git cannot say, before 2.31.
43
+ */
44
+ export async function hookPath(name, cwd) {
45
+ return value(['rev-parse', '--path-format=absolute', '--git-path', `hooks/${name}`], cwd);
46
+ }
39
47
  /** The checked-out branch's short name, or `null` on a detached head. */
40
48
  export async function currentBranch(cwd) {
41
49
  return value(['symbolic-ref', '--quiet', '--short', 'HEAD'], cwd);
package/dist/git.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"git.js","sourceRoot":"","sources":["../src/git.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAU9C,gFAAgF;AAChF,MAAM,UAAU,GAAG,CAAC,IAAuB,EAAE,GAAW,EAAE,KAAc;IACtE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,MAAM,KAAK,GAAG,QAAQ,CACpB,KAAK,EACL,CAAC,GAAG,IAAI,CAAC,EACT,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,GAAG,IAAI,GAAG,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,EAC1E,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE;YACxB,MAAM,IAAI,GAAG,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAQ,KAA4B,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAE,KAA0B,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACnI,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;QACpC,CAAC,CACF,CAAC;QACF,IAAI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,EAAE,8BAA8B,kBAAkB,EAAE,EAAE,IAAI,EAAE,gBAAgB,EAAE,eAAe,EAAE,OAAO,EAAE,GAAG,CAAC,EACjH,GAAG,CACJ,CAAC;IACF,MAAM,IAAI,GAAG,GAAG,GAAG,CAAC,MAAM,KAAK,GAAG,CAAC,MAAM,EAAE,CAAC;IAC5C,MAAM,SAAS,GAAG,gCAAgC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;IAC3E,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,KAAK,CAAC,IAAI,SAAS,KAAK,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;AAC7G,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,IAAY,EAAE,GAAW,EAAE,GAAW;IACtE,MAAM,GAAG,GAAG,MAAM,GAAG,CAAC,CAAC,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;IAClF,IAAI,GAAG,CAAC,IAAI,KAAK,CAAC;QAAE,MAAM,IAAI,QAAQ,CAAC,4BAA4B,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AAC1F,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,IAAY,EAAE,GAAW;IAC5D,MAAM,GAAG,CAAC,CAAC,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * The edge where the harness meets git.\n *\n * Reads, except for two things ADR-0003 allows and bounds: a temporary\n * worktree, added and always removed by the sandbox, and nothing else. Every\n * call is an argument vector, never a shell string, so a path or a ref cannot\n * become a command.\n */\n\nimport { execFile } from 'node:child_process';\n\nimport type { FileChange } from './types.js';\n\nexport interface Run {\n readonly code: number;\n readonly stdout: string;\n readonly stderr: string;\n}\n\n/** Runs git and answers whatever it answered; a missing git is a code of -1. */\nexport function git(args: readonly string[], cwd: string, input?: string): Promise<Run> {\n return new Promise((resolve) => {\n const child = execFile(\n 'git',\n [...args],\n { cwd, maxBuffer: 256 * 1024 * 1024, encoding: 'utf8', windowsHide: true },\n (error, stdout, stderr) => {\n const code = error === null ? 0 : typeof (error as { code?: unknown }).code === 'number' ? ((error as { code: number }).code) : -1;\n resolve({ code, stdout, stderr });\n },\n );\n if (input !== undefined) child.stdin?.end(input);\n });\n}\n\nasync function value(args: readonly string[], cwd: string): Promise<string | null> {\n const run = await git(args, cwd);\n return run.code === 0 ? run.stdout.trim() : null;\n}\n\nexport class GitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GitError';\n }\n}\n\n/** The top of the work tree holding `cwd`, POSIX-separated, or `null` outside one. */\nexport async function workTreeRoot(cwd: string): Promise<string | null> {\n return value(['rev-parse', '--show-toplevel'], cwd);\n}\n\n/** The git directory every worktree of this repository shares. */\nexport async function commonDirectory(cwd: string): Promise<string | null> {\n return value(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n}\n\n/** The checked-out branch's short name, or `null` on a detached head. */\nexport async function currentBranch(cwd: string): Promise<string | null> {\n return value(['symbolic-ref', '--quiet', '--short', 'HEAD'], cwd);\n}\n\n/** The remote's default branch as a local ref, such as `origin/main`, or `null`. */\nexport async function remoteDefault(cwd: string): Promise<string | null> {\n return value(['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], cwd);\n}\n\n/** Every local branch, by its short name. */\nexport async function localBranches(cwd: string): Promise<string[]> {\n const listed = await value(['for-each-ref', '--format=%(refname:short)', 'refs/heads/'], cwd);\n return listed === null || listed === '' ? [] : listed.split('\\n').map((name) => name.trim());\n}\n\nexport async function revision(ref: string, cwd: string): Promise<string | null> {\n return value(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], cwd);\n}\n\nexport async function mergeBase(a: string, b: string, cwd: string): Promise<string | null> {\n return value(['merge-base', a, b], cwd);\n}\n\n/** Parses `git diff --name-status -z` output. */\nexport function parseNameStatus(output: string): FileChange[] {\n const fields = output.split('\\0');\n const out: FileChange[] = [];\n for (let i = 0; i < fields.length; ) {\n const code = fields[i] ?? '';\n if (code === '') {\n i += 1;\n continue;\n }\n const status = code.charAt(0) as FileChange['status'];\n if (status === 'R' || status === 'C') {\n out.push({ status, from: fields[i + 1] ?? '', path: fields[i + 2] ?? '' });\n i += 3;\n } else {\n out.push({ status, path: fields[i + 1] ?? '' });\n i += 2;\n }\n }\n return out;\n}\n\n/** The files changed from one revision to another, renames found. */\nexport async function changes(from: string, to: string, cwd: string): Promise<FileChange[]> {\n const run = await git(['diff', '--name-status', '-z', '--find-renames', '--no-color', from, to, '--'], cwd);\n if (run.code !== 0) throw new GitError(`git diff ${from} ${to} failed: ${run.stderr.trim()}`);\n return parseNameStatus(run.stdout);\n}\n\n/** The files a commit would change: what is staged. */\nexport async function stagedChanges(cwd: string): Promise<FileChange[]> {\n const run = await git(['diff', '--cached', '--name-status', '-z', '--find-renames', '--no-color', '--'], cwd);\n if (run.code !== 0) throw new GitError(`git diff --cached failed: ${run.stderr.trim()}`);\n return parseNameStatus(run.stdout);\n}\n\n/** A file's content at a revision, or `null` when it does not exist there. */\nexport async function show(ref: string, path: string, cwd: string): Promise<string | null> {\n const run = await git(['show', `${ref}:${path}`], cwd);\n return run.code === 0 ? run.stdout : null;\n}\n\n/**\n * The commit that last changed one line of a file, as of a revision, or of\n * the working tree when `ref` is `null` - where a line nobody committed yet\n * belongs to the all-zero commit.\n */\nexport async function blameLine(ref: string | null, path: string, line: number, cwd: string): Promise<string | null> {\n const run = await git(['blame', '--porcelain', '-L', `${line},${line}`, ...(ref === null ? [] : [ref]), '--', path], cwd);\n if (run.code !== 0) return null;\n const sha = /^([0-9a-f]{40,64}) /.exec(run.stdout)?.[1];\n return sha ?? null;\n}\n\nexport interface Signature {\n readonly good: boolean;\n /** The allowed signer's principal, for a good signature. */\n readonly principal: string | null;\n readonly detail: string;\n}\n\n/**\n * Whether a commit carries a good SSH signature by a principal in the given\n * allowed-signers file. The file is passed in, never read from the commit's\n * own tree: a round cannot vouch for itself (ADR-0006).\n */\nexport async function verifyCommit(sha: string, allowedSignersFile: string, cwd: string): Promise<Signature> {\n const run = await git(\n ['-c', `gpg.ssh.allowedSignersFile=${allowedSignersFile}`, '-c', 'gpg.format=ssh', 'verify-commit', '--raw', sha],\n cwd,\n );\n const text = `${run.stderr}\\n${run.stdout}`;\n const principal = /Good \"git\" signature for (\\S+)/.exec(text)?.[1] ?? null;\n return { good: run.code === 0 && principal !== null, principal, detail: text.trim().split('\\n')[0] ?? '' };\n}\n\nexport async function addWorktree(path: string, rev: string, cwd: string): Promise<void> {\n const run = await git(['worktree', 'add', '--detach', '--force', path, rev], cwd);\n if (run.code !== 0) throw new GitError(`git worktree add failed: ${run.stderr.trim()}`);\n}\n\n/**\n * Forgets the worktree at `path`, and no other, once its directory is\n * deleted. Git refuses to remove a worktree whose directory has lost its\n * `.git` file, and removes its record of one whose directory is gone, found by\n * the path it was added at: `git worktree prune` would also forget every other\n * worktree git has lost track of, the person's among them.\n */\nexport async function removeWorktree(path: string, cwd: string): Promise<void> {\n await git(['worktree', 'remove', '--force', path], cwd);\n}\n"]}
1
+ {"version":3,"file":"git.js","sourceRoot":"","sources":["../src/git.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAU9C,gFAAgF;AAChF,MAAM,UAAU,GAAG,CAAC,IAAuB,EAAE,GAAW,EAAE,KAAc;IACtE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,MAAM,KAAK,GAAG,QAAQ,CACpB,KAAK,EACL,CAAC,GAAG,IAAI,CAAC,EAC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,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,IAAY,EAAE,GAAW,EAAE,GAAW;IACtE,MAAM,GAAG,GAAG,MAAM,GAAG,CAAC,CAAC,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;IAClF,IAAI,GAAG,CAAC,IAAI,KAAK,CAAC;QAAE,MAAM,IAAI,QAAQ,CAAC,4BAA4B,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AAC1F,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,IAAY,EAAE,GAAW;IAC5D,MAAM,GAAG,CAAC,CAAC,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * The edge where the harness meets git.\n *\n * Reads, except for two things ADR-0003 allows and bounds: a temporary\n * worktree, added and always removed by the sandbox, and nothing else. Every\n * call is an argument vector, never a shell string, so a path or a ref cannot\n * become a command.\n */\n\nimport { execFile } from 'node:child_process';\n\nimport type { FileChange } from './types.js';\n\nexport interface Run {\n readonly code: number;\n readonly stdout: string;\n readonly stderr: string;\n}\n\n/** Runs git and answers whatever it answered; a missing git is a code of -1. */\nexport function git(args: readonly string[], cwd: string, input?: string): Promise<Run> {\n return new Promise((resolve) => {\n const child = execFile(\n 'git',\n [...args],\n { cwd, maxBuffer: 256 * 1024 * 1024, encoding: 'utf8', windowsHide: true },\n (error, stdout, stderr) => {\n const code = error === null ? 0 : typeof (error as { code?: unknown }).code === 'number' ? ((error as { code: number }).code) : -1;\n resolve({ code, stdout, stderr });\n },\n );\n if (input !== undefined) child.stdin?.end(input);\n });\n}\n\nasync function value(args: readonly string[], cwd: string): Promise<string | null> {\n const run = await git(args, cwd);\n return run.code === 0 ? run.stdout.trim() : null;\n}\n\nexport class GitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GitError';\n }\n}\n\n/** The top of the work tree holding `cwd`, POSIX-separated, or `null` outside one. */\nexport async function workTreeRoot(cwd: string): Promise<string | null> {\n return value(['rev-parse', '--show-toplevel'], cwd);\n}\n\n/** The git directory every worktree of this repository shares. */\nexport async function commonDirectory(cwd: string): Promise<string | null> {\n return value(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n}\n\n/**\n * Where git runs the hook `name` from, absolute: `core.hooksPath` read as git\n * reads it - relative to the work tree, absolute, or under `~` - and a linked\n * worktree's shared hooks. `null` when git cannot say, before 2.31.\n */\nexport async function hookPath(name: string, cwd: string): Promise<string | null> {\n return value(['rev-parse', '--path-format=absolute', '--git-path', `hooks/${name}`], cwd);\n}\n\n/** The checked-out branch's short name, or `null` on a detached head. */\nexport async function currentBranch(cwd: string): Promise<string | null> {\n return value(['symbolic-ref', '--quiet', '--short', 'HEAD'], cwd);\n}\n\n/** The remote's default branch as a local ref, such as `origin/main`, or `null`. */\nexport async function remoteDefault(cwd: string): Promise<string | null> {\n return value(['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], cwd);\n}\n\n/** Every local branch, by its short name. */\nexport async function localBranches(cwd: string): Promise<string[]> {\n const listed = await value(['for-each-ref', '--format=%(refname:short)', 'refs/heads/'], cwd);\n return listed === null || listed === '' ? [] : listed.split('\\n').map((name) => name.trim());\n}\n\nexport async function revision(ref: string, cwd: string): Promise<string | null> {\n return value(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], cwd);\n}\n\nexport async function mergeBase(a: string, b: string, cwd: string): Promise<string | null> {\n return value(['merge-base', a, b], cwd);\n}\n\n/** Parses `git diff --name-status -z` output. */\nexport function parseNameStatus(output: string): FileChange[] {\n const fields = output.split('\\0');\n const out: FileChange[] = [];\n for (let i = 0; i < fields.length; ) {\n const code = fields[i] ?? '';\n if (code === '') {\n i += 1;\n continue;\n }\n const status = code.charAt(0) as FileChange['status'];\n if (status === 'R' || status === 'C') {\n out.push({ status, from: fields[i + 1] ?? '', path: fields[i + 2] ?? '' });\n i += 3;\n } else {\n out.push({ status, path: fields[i + 1] ?? '' });\n i += 2;\n }\n }\n return out;\n}\n\n/** The files changed from one revision to another, renames found. */\nexport async function changes(from: string, to: string, cwd: string): Promise<FileChange[]> {\n const run = await git(['diff', '--name-status', '-z', '--find-renames', '--no-color', from, to, '--'], cwd);\n if (run.code !== 0) throw new GitError(`git diff ${from} ${to} failed: ${run.stderr.trim()}`);\n return parseNameStatus(run.stdout);\n}\n\n/** The files a commit would change: what is staged. */\nexport async function stagedChanges(cwd: string): Promise<FileChange[]> {\n const run = await git(['diff', '--cached', '--name-status', '-z', '--find-renames', '--no-color', '--'], cwd);\n if (run.code !== 0) throw new GitError(`git diff --cached failed: ${run.stderr.trim()}`);\n return parseNameStatus(run.stdout);\n}\n\n/** A file's content at a revision, or `null` when it does not exist there. */\nexport async function show(ref: string, path: string, cwd: string): Promise<string | null> {\n const run = await git(['show', `${ref}:${path}`], cwd);\n return run.code === 0 ? run.stdout : null;\n}\n\n/**\n * The commit that last changed one line of a file, as of a revision, or of\n * the working tree when `ref` is `null` - where a line nobody committed yet\n * belongs to the all-zero commit.\n */\nexport async function blameLine(ref: string | null, path: string, line: number, cwd: string): Promise<string | null> {\n const run = await git(['blame', '--porcelain', '-L', `${line},${line}`, ...(ref === null ? [] : [ref]), '--', path], cwd);\n if (run.code !== 0) return null;\n const sha = /^([0-9a-f]{40,64}) /.exec(run.stdout)?.[1];\n return sha ?? null;\n}\n\nexport interface Signature {\n readonly good: boolean;\n /** The allowed signer's principal, for a good signature. */\n readonly principal: string | null;\n readonly detail: string;\n}\n\n/**\n * Whether a commit carries a good SSH signature by a principal in the given\n * allowed-signers file. The file is passed in, never read from the commit's\n * own tree: a round cannot vouch for itself (ADR-0006).\n */\nexport async function verifyCommit(sha: string, allowedSignersFile: string, cwd: string): Promise<Signature> {\n const run = await git(\n ['-c', `gpg.ssh.allowedSignersFile=${allowedSignersFile}`, '-c', 'gpg.format=ssh', 'verify-commit', '--raw', sha],\n cwd,\n );\n const text = `${run.stderr}\\n${run.stdout}`;\n const principal = /Good \"git\" signature for (\\S+)/.exec(text)?.[1] ?? null;\n return { good: run.code === 0 && principal !== null, principal, detail: text.trim().split('\\n')[0] ?? '' };\n}\n\nexport async function addWorktree(path: string, rev: string, cwd: string): Promise<void> {\n const run = await git(['worktree', 'add', '--detach', '--force', path, rev], cwd);\n if (run.code !== 0) throw new GitError(`git worktree add failed: ${run.stderr.trim()}`);\n}\n\n/**\n * Forgets the worktree at `path`, and no other, once its directory is\n * deleted. Git refuses to remove a worktree whose directory has lost its\n * `.git` file, and removes its record of one whose directory is gone, found by\n * the path it was added at: `git worktree prune` would also forget every other\n * worktree git has lost track of, the person's among them.\n */\nexport async function removeWorktree(path: string, cwd: string): Promise<void> {\n await git(['worktree', 'remove', '--force', path], cwd);\n}\n"]}
package/dist/guard.d.ts CHANGED
@@ -44,6 +44,14 @@ export interface GuardInput {
44
44
  * can. The guard matches no path by a pattern it cannot read.
45
45
  */
46
46
  export declare function whyUnreadable(pattern: string): string | null;
47
+ /**
48
+ * Whether a leading `/` roots a pattern the guard can read at the
49
+ * filesystem's root: `whole` when every alternative is rooted, `part` when
50
+ * some brace alternative is, `null` when none is or the pattern cannot be
51
+ * read. The guard decides repository-relative paths, so a rooted
52
+ * alternative matches none of them.
53
+ */
54
+ export declare function rooted(pattern: string): 'whole' | 'part' | null;
47
55
  /** The first verified ruling whose paths cover `path`, read as the guard reads a scope. */
48
56
  export declare function rulingFor(rulings: readonly VerifiedRuling[], path: string): VerifiedRuling | undefined;
49
57
  /** Decides one path. Pure: the caller resolved the path, the brief and the rulings. */
package/dist/guard.js CHANGED
@@ -8,7 +8,7 @@
8
8
  * through a shell passes it - so the audit and spec-brief's archive are the
9
9
  * gates, and this is what keeps an honest agent from needing them (ADR-0005).
10
10
  */
11
- import { parseGlob } from './vendor/spec-core/pattern/index.js';
11
+ import { globAlternatives, parseGlob } from './vendor/spec-core/pattern/index.js';
12
12
  function compile(pattern) {
13
13
  const parsed = parseGlob(pattern, { dialect: 'path', caseSensitive: true, literal: 'either' });
14
14
  return parsed.ok ? parsed.glob : parsed.error;
@@ -21,6 +21,24 @@ export function whyUnreadable(pattern) {
21
21
  const glob = compile(pattern);
22
22
  return typeof glob === 'string' ? glob : null;
23
23
  }
24
+ /**
25
+ * Whether a leading `/` roots a pattern the guard can read at the
26
+ * filesystem's root: `whole` when every alternative is rooted, `part` when
27
+ * some brace alternative is, `null` when none is or the pattern cannot be
28
+ * read. The guard decides repository-relative paths, so a rooted
29
+ * alternative matches none of them.
30
+ */
31
+ export function rooted(pattern) {
32
+ if (typeof compile(pattern) === 'string')
33
+ return null;
34
+ // spec-core refuses here only what its compile refuses, so a pattern the
35
+ // guard reads always has its alternatives read.
36
+ const { alternatives } = globAlternatives(pattern);
37
+ const roots = alternatives.filter((alternative) => alternative.rooted).length;
38
+ if (roots === 0)
39
+ return null;
40
+ return roots === alternatives.length ? 'whole' : 'part';
41
+ }
24
42
  function matching(patterns, path) {
25
43
  const matched = [];
26
44
  const unreadable = [];
package/dist/guard.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"guard.js","sourceRoot":"","sources":["../src/guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,SAAS,EAAa,MAAM,qCAAqC,CAAC;AA8C3E,SAAS,OAAO,CAAC,OAAe;IAC9B,MAAM,MAAM,GAAG,SAAS,CAAC,OAAO,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC/F,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;AAChD,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,OAAe;IAC3C,MAAM,IAAI,GAAG,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AAM,EAAE,cAAc;QACtB,OAAO,EAAE,YAAY,CAAC,UAAU;QAChC,OAAO,EAAE,GAAG,IAAI,qBAAqB,KAAK,CAAC,EAAE,mBAAmB,KAAK,EAAE;QACvE,IAAI,EACF,OAAO,KAAK,MAAM;YAChB,CAAC,CAAC,8BAA8B,KAAK,CAAC,IAAI,4FAA4F,QAAQ,EAAE;YAChJ,CAAC,CAAC,oCAAoC,KAAK,CAAC,IAAI,gFAAgF;KACrI,CAAC;AACJ,CAAC","sourcesContent":["/**\n * May this round write this file?\n *\n * The answer is read from the brief the round runs under: `protectedFiles`\n * are refused unless a person has ruled otherwise, `affectedFiles` are the\n * round's to write, and anything else is outside the scope the person\n * approved. A guard is a guardrail, not a boundary - an agent that writes\n * through a shell passes it - so the audit and spec-brief's archive are the\n * gates, and this is what keeps an honest agent from needing them (ADR-0005).\n */\n\nimport { parseGlob, type Glob } from './vendor/spec-core/pattern/index.js';\nimport type { OutOfScope } from './config.js';\nimport type { BriefRow } from './types.js';\n\nexport type Verdict = 'allow' | 'warn' | 'ask' | 'deny';\n\nexport type Reason =\n | 'outside-repository'\n | 'no-brief'\n | 'brief-file'\n | 'protected'\n | 'ruled'\n | 'unreadable-protection'\n | 'in-scope'\n | 'out-of-scope';\n\nexport interface Decision {\n /** Repository-relative, or the path as given when it lies outside. */\n readonly path: string;\n readonly verdict: Verdict;\n readonly reason: Reason;\n /** The patterns or ruling that decided it. */\n readonly because: readonly string[];\n readonly message: string;\n readonly hint: string;\n}\n\n/** A ruling whose signature has been verified: a person allowed these paths. */\nexport interface VerifiedRuling {\n readonly id: string;\n readonly paths: readonly string[];\n readonly signer: string;\n}\n\nexport interface GuardInput {\n /** Repository-relative POSIX path, or `null` for a path outside the repository. */\n readonly path: string | null;\n /** The path as the caller gave it, for messages. */\n readonly given: string;\n readonly brief: BriefRow | null;\n /** Why there is no brief, when there is none. */\n readonly noBrief?: string | undefined;\n readonly rulings: readonly VerifiedRuling[];\n readonly outOfScope: OutOfScope;\n}\n\nfunction compile(pattern: string): Glob | string {\n const parsed = parseGlob(pattern, { dialect: 'path', caseSensitive: true, literal: 'either' });\n return parsed.ok ? parsed.glob : parsed.error;\n}\n\n/**\n * Why the guard cannot read a pattern, in spec-core's words; `null` when it\n * can. The guard matches no path by a pattern it cannot read.\n */\nexport function whyUnreadable(pattern: string): string | null {\n const glob = compile(pattern);\n return typeof glob === 'string' ? glob : null;\n}\n\nfunction matching(patterns: readonly string[], path: string): { matched: string[]; unreadable: string[] } {\n const matched: string[] = [];\n const unreadable: string[] = [];\n for (const pattern of patterns) {\n const glob = compile(pattern);\n if (typeof glob === 'string') unreadable.push(`${pattern} (${glob})`);\n else if (glob.match(path)) matched.push(pattern);\n }\n return { matched, unreadable };\n}\n\n/** The first verified ruling whose paths cover `path`, read as the guard reads a scope. */\nexport function rulingFor(rulings: readonly VerifiedRuling[], path: string): VerifiedRuling | undefined {\n return rulings.find((candidate) => matching(candidate.paths, path).matched.length > 0);\n}\n\nconst ESCALATE =\n 'if the round cannot be done without it, stop and ask for a ruling: spec-harness escalate --path <file> --reason <why>, or the request_escalation tool';\n\n/** Decides one path. Pure: the caller resolved the path, the brief and the rulings. */\nexport function decide(input: GuardInput): Decision {\n const { path, given, brief } = input;\n if (path === null) {\n return {\n path: given,\n verdict: 'allow',\n reason: 'outside-repository',\n because: [],\n message: `${given} is outside the repository; no brief governs it`,\n hint: 'nothing to do',\n };\n }\n if (brief === null) {\n return {\n path,\n verdict: 'allow',\n reason: 'no-brief',\n because: [],\n message: `no brief governs ${path}: ${input.noBrief ?? 'no active brief'}`,\n hint: 'name the brief this work belongs to, so its scope can be checked',\n };\n }\n if (path === brief.file) {\n return {\n path,\n verdict: 'allow',\n reason: 'brief-file',\n because: [],\n message: `${path} is brief ${brief.id} itself`,\n hint: 'tick or disposition its boxes as the work lands',\n };\n }\n\n const protectedHits = matching(brief.protectedFiles, path);\n if (protectedHits.unreadable.length > 0) {\n // A protection that cannot be read cannot be honoured, and cannot be\n // assumed not to apply: refuse until the brief is fixed.\n return {\n path,\n verdict: 'deny',\n reason: 'unreadable-protection',\n because: protectedHits.unreadable,\n message: `brief ${brief.id} protects files with a pattern that cannot be read: ${protectedHits.unreadable.join('; ')}`,\n hint: `fix protectedFiles in ${brief.file} (spec-brief lint names the problem)`,\n };\n }\n if (protectedHits.matched.length > 0) {\n const ruling = rulingFor(input.rulings, path);\n if (ruling !== undefined) {\n return {\n path,\n verdict: 'allow',\n reason: 'ruled',\n because: [ruling.id],\n message: `${path} is protected by brief ${brief.id}, and ruling ${ruling.id}, signed by ${ruling.signer}, allows it`,\n hint: 'keep the change to what the ruling allows',\n };\n }\n return {\n path,\n verdict: 'deny',\n reason: 'protected',\n because: protectedHits.matched,\n message: `brief ${brief.id} does not empower this round to change ${path} (protectedFiles: ${protectedHits.matched.join(', ')})`,\n hint: ESCALATE,\n };\n }\n\n const affectedHits = matching(brief.affectedFiles, path);\n if (affectedHits.matched.length > 0) {\n return {\n path,\n verdict: 'allow',\n reason: 'in-scope',\n because: affectedHits.matched,\n message: `${path} is in brief ${brief.id}'s scope (${affectedHits.matched.join(', ')})`,\n hint: 'nothing to do',\n };\n }\n\n const verdict: Verdict = input.outOfScope;\n const scope = brief.affectedFiles.length === 0 ? 'declares no affectedFiles' : `covers ${brief.affectedFiles.join(', ')}`;\n return {\n path,\n verdict,\n reason: 'out-of-scope',\n because: affectedHits.unreadable,\n message: `${path} is outside brief ${brief.id}'s scope, which ${scope}`,\n hint:\n verdict === 'deny'\n ? `add it to affectedFiles in ${brief.file} if the round needs it, which is a change the person who approved the brief must see; or ${ESCALATE}`\n : `if the round needs it, say so in ${brief.file} and add it to affectedFiles; the archive reports every file outside the scope`,\n };\n}\n"]}
1
+ {"version":3,"file":"guard.js","sourceRoot":"","sources":["../src/guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAmC,MAAM,qCAAqC,CAAC;AA8CnH,SAAS,OAAO,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CAAC,OAAO;YAC9B,OAAO,EAAE,SAAS,KAAK,CAAC,EAAE,0CAA0C,IAAI,qBAAqB,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG;YAChI,IAAI,EAAE,QAAQ;SACf,CAAC;IACJ,CAAC;IAED,MAAM,YAAY,GAAG,QAAQ,CAAC,KAAK,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;IACzD,IAAI,YAAY,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpC,OAAO;YACL,IAAI;YACJ,OAAO,EAAE,OAAO;YAChB,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,YAAY,CAAC,OAAO;YAC7B,OAAO,EAAE,GAAG,IAAI,gBAAgB,KAAK,CAAC,EAAE,aAAa,YAAY,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG;YACvF,IAAI,EAAE,eAAe;SACtB,CAAC;IACJ,CAAC;IAED,MAAM,OAAO,GAAY,KAAK,CAAC,UAAU,CAAC;IAC1C,MAAM,KAAK,GAAG,KAAK,CAAC,aAAa,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,2BAA2B,CAAC,CAAC,CAAC,UAAU,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;IAC1H,OAAO;QACL,IAAI;QACJ,OAAO;QACP,MAAM,EAAE,cAAc;QACtB,OAAO,EAAE,YAAY,CAAC,UAAU;QAChC,OAAO,EAAE,GAAG,IAAI,qBAAqB,KAAK,CAAC,EAAE,mBAAmB,KAAK,EAAE;QACvE,IAAI,EACF,OAAO,KAAK,MAAM;YAChB,CAAC,CAAC,8BAA8B,KAAK,CAAC,IAAI,4FAA4F,QAAQ,EAAE;YAChJ,CAAC,CAAC,oCAAoC,KAAK,CAAC,IAAI,gFAAgF;KACrI,CAAC;AACJ,CAAC","sourcesContent":["/**\n * May this round write this file?\n *\n * The answer is read from the brief the round runs under: `protectedFiles`\n * are refused unless a person has ruled otherwise, `affectedFiles` are the\n * round's to write, and anything else is outside the scope the person\n * approved. A guard is a guardrail, not a boundary - an agent that writes\n * through a shell passes it - so the audit and spec-brief's archive are the\n * gates, and this is what keeps an honest agent from needing them (ADR-0005).\n */\n\nimport { globAlternatives, parseGlob, type Glob, type GlobAlternative } from './vendor/spec-core/pattern/index.js';\nimport type { OutOfScope } from './config.js';\nimport type { BriefRow } from './types.js';\n\nexport type Verdict = 'allow' | 'warn' | 'ask' | 'deny';\n\nexport type Reason =\n | 'outside-repository'\n | 'no-brief'\n | 'brief-file'\n | 'protected'\n | 'ruled'\n | 'unreadable-protection'\n | 'in-scope'\n | 'out-of-scope';\n\nexport interface Decision {\n /** Repository-relative, or the path as given when it lies outside. */\n readonly path: string;\n readonly verdict: Verdict;\n readonly reason: Reason;\n /** The patterns or ruling that decided it. */\n readonly because: readonly string[];\n readonly message: string;\n readonly hint: string;\n}\n\n/** A ruling whose signature has been verified: a person allowed these paths. */\nexport interface VerifiedRuling {\n readonly id: string;\n readonly paths: readonly string[];\n readonly signer: string;\n}\n\nexport interface GuardInput {\n /** Repository-relative POSIX path, or `null` for a path outside the repository. */\n readonly path: string | null;\n /** The path as the caller gave it, for messages. */\n readonly given: string;\n readonly brief: BriefRow | null;\n /** Why there is no brief, when there is none. */\n readonly noBrief?: string | undefined;\n readonly rulings: readonly VerifiedRuling[];\n readonly outOfScope: OutOfScope;\n}\n\nfunction compile(pattern: string): Glob | string {\n const parsed = parseGlob(pattern, { dialect: 'path', caseSensitive: true, literal: 'either' });\n return parsed.ok ? parsed.glob : parsed.error;\n}\n\n/**\n * Why the guard cannot read a pattern, in spec-core's words; `null` when it\n * can. The guard matches no path by a pattern it cannot read.\n */\nexport function whyUnreadable(pattern: string): string | null {\n const glob = compile(pattern);\n return typeof glob === 'string' ? glob : null;\n}\n\n/**\n * Whether a leading `/` roots a pattern the guard can read at the\n * filesystem's root: `whole` when every alternative is rooted, `part` when\n * some brace alternative is, `null` when none is or the pattern cannot be\n * read. The guard decides repository-relative paths, so a rooted\n * alternative matches none of them.\n */\nexport function rooted(pattern: string): 'whole' | 'part' | null {\n if (typeof compile(pattern) === 'string') return null;\n // spec-core refuses here only what its compile refuses, so a pattern the\n // guard reads always has its alternatives read.\n const { alternatives } = globAlternatives(pattern) as { readonly alternatives: readonly GlobAlternative[] };\n const roots = alternatives.filter((alternative) => alternative.rooted).length;\n if (roots === 0) return null;\n return roots === alternatives.length ? 'whole' : 'part';\n}\n\nfunction matching(patterns: readonly string[], path: string): { matched: string[]; unreadable: string[] } {\n const matched: string[] = [];\n const unreadable: string[] = [];\n for (const pattern of patterns) {\n const glob = compile(pattern);\n if (typeof glob === 'string') unreadable.push(`${pattern} (${glob})`);\n else if (glob.match(path)) matched.push(pattern);\n }\n return { matched, unreadable };\n}\n\n/** The first verified ruling whose paths cover `path`, read as the guard reads a scope. */\nexport function rulingFor(rulings: readonly VerifiedRuling[], path: string): VerifiedRuling | undefined {\n return rulings.find((candidate) => matching(candidate.paths, path).matched.length > 0);\n}\n\nconst ESCALATE =\n 'if the round cannot be done without it, stop and ask for a ruling: spec-harness escalate --path <file> --reason <why>, or the request_escalation tool';\n\n/** Decides one path. Pure: the caller resolved the path, the brief and the rulings. */\nexport function decide(input: GuardInput): Decision {\n const { path, given, brief } = input;\n if (path === null) {\n return {\n path: given,\n verdict: 'allow',\n reason: 'outside-repository',\n because: [],\n message: `${given} is outside the repository; no brief governs it`,\n hint: 'nothing to do',\n };\n }\n if (brief === null) {\n return {\n path,\n verdict: 'allow',\n reason: 'no-brief',\n because: [],\n message: `no brief governs ${path}: ${input.noBrief ?? 'no active brief'}`,\n hint: 'name the brief this work belongs to, so its scope can be checked',\n };\n }\n if (path === brief.file) {\n return {\n path,\n verdict: 'allow',\n reason: 'brief-file',\n because: [],\n message: `${path} is brief ${brief.id} itself`,\n hint: 'tick or disposition its boxes as the work lands',\n };\n }\n\n const protectedHits = matching(brief.protectedFiles, path);\n if (protectedHits.unreadable.length > 0) {\n // A protection that cannot be read cannot be honoured, and cannot be\n // assumed not to apply: refuse until the brief is fixed.\n return {\n path,\n verdict: 'deny',\n reason: 'unreadable-protection',\n because: protectedHits.unreadable,\n message: `brief ${brief.id} protects files with a pattern that cannot be read: ${protectedHits.unreadable.join('; ')}`,\n hint: `fix protectedFiles in ${brief.file} (spec-brief lint names the problem)`,\n };\n }\n if (protectedHits.matched.length > 0) {\n const ruling = rulingFor(input.rulings, path);\n if (ruling !== undefined) {\n return {\n path,\n verdict: 'allow',\n reason: 'ruled',\n because: [ruling.id],\n message: `${path} is protected by brief ${brief.id}, and ruling ${ruling.id}, signed by ${ruling.signer}, allows it`,\n hint: 'keep the change to what the ruling allows',\n };\n }\n return {\n path,\n verdict: 'deny',\n reason: 'protected',\n because: protectedHits.matched,\n message: `brief ${brief.id} does not empower this round to change ${path} (protectedFiles: ${protectedHits.matched.join(', ')})`,\n hint: ESCALATE,\n };\n }\n\n const affectedHits = matching(brief.affectedFiles, path);\n if (affectedHits.matched.length > 0) {\n return {\n path,\n verdict: 'allow',\n reason: 'in-scope',\n because: affectedHits.matched,\n message: `${path} is in brief ${brief.id}'s scope (${affectedHits.matched.join(', ')})`,\n hint: 'nothing to do',\n };\n }\n\n const verdict: Verdict = input.outOfScope;\n const scope = brief.affectedFiles.length === 0 ? 'declares no affectedFiles' : `covers ${brief.affectedFiles.join(', ')}`;\n return {\n path,\n verdict,\n reason: 'out-of-scope',\n because: affectedHits.unreadable,\n message: `${path} is outside brief ${brief.id}'s scope, which ${scope}`,\n hint:\n verdict === 'deny'\n ? `add it to affectedFiles in ${brief.file} if the round needs it, which is a change the person who approved the brief must see; or ${ESCALATE}`\n : `if the round needs it, say so in ${brief.file} and add it to affectedFiles; the archive reports every file outside the scope`,\n };\n}\n"]}
package/dist/host.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The edge where the harness meets a program that is neither git nor a
3
+ * sibling: Claude Code, asked which release it is.
4
+ *
5
+ * Found on `PATH` and started without a shell, as every program the harness
6
+ * runs is (ADR-0002). On Windows a program is an `.exe` or a `.com`; a
7
+ * `claude.cmd` shim, as npm installs one, can be started only by a shell, so
8
+ * it is named rather than run, and its release cannot be told.
9
+ */
10
+ import type { ClaudeCodeAnswer } from './versions.js';
11
+ /** The file `name` names on `PATH` as the environment gives it, or `null`. */
12
+ export declare function onPath(name: string, env: Readonly<Record<string, string | undefined>>, platform?: NodeJS.Platform): string | null;
13
+ /** `claude --version`, as the Claude Code on `PATH` answers it, or why it cannot. */
14
+ export declare function claudeVersion(env: Readonly<Record<string, string | undefined>>, platform?: NodeJS.Platform): Promise<ClaudeCodeAnswer>;
package/dist/host.js ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The edge where the harness meets a program that is neither git nor a
3
+ * sibling: Claude Code, asked which release it is.
4
+ *
5
+ * Found on `PATH` and started without a shell, as every program the harness
6
+ * runs is (ADR-0002). On Windows a program is an `.exe` or a `.com`; a
7
+ * `claude.cmd` shim, as npm installs one, can be started only by a shell, so
8
+ * it is named rather than run, and its release cannot be told.
9
+ */
10
+ import { execFile } from 'node:child_process';
11
+ import { existsSync, statSync } from 'node:fs';
12
+ import { delimiter, join } from 'node:path';
13
+ /** What Windows runs for a name with no extension, in order; the first two alone without a shell. */
14
+ const WINDOWS_EXTENSIONS = ['.COM', '.EXE', '.BAT', '.CMD'];
15
+ /** The file `name` names on `PATH` as the environment gives it, or `null`. */
16
+ export function onPath(name, env, platform = process.platform) {
17
+ const path = env['PATH'] ?? env['Path'] ?? '';
18
+ const windows = platform === 'win32';
19
+ const extensions = windows
20
+ ? (env['PATHEXT'] ?? WINDOWS_EXTENSIONS.join(';')).split(';').filter((extension) => extension !== '')
21
+ : [''];
22
+ for (const directory of path.split(windows ? ';' : delimiter)) {
23
+ if (directory === '')
24
+ continue;
25
+ for (const extension of extensions) {
26
+ const file = join(directory, `${name}${extension.toLowerCase()}`);
27
+ if (existsSync(file) && statSync(file).isFile())
28
+ return file;
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+ /** `claude --version`, as the Claude Code on `PATH` answers it, or why it cannot. */
34
+ export async function claudeVersion(env, platform = process.platform) {
35
+ const file = onPath('claude', env, platform);
36
+ if (file === null)
37
+ return { missing: 'no claude is on PATH' };
38
+ if (platform === 'win32' && !/\.(?:exe|com)$/i.test(file)) {
39
+ return { missing: `claude on PATH is ${file}, a script that cannot be started without a shell, which spec-harness does not use` };
40
+ }
41
+ return new Promise((resolve) => {
42
+ execFile(file, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 15_000, shell: false }, (error, stdout) => {
43
+ if (error !== null)
44
+ resolve({ missing: `${file} --version failed: ${error.message.split('\n')[0] ?? ''}` });
45
+ else
46
+ resolve({ output: stdout });
47
+ });
48
+ });
49
+ }
50
+ //# sourceMappingURL=host.js.map