@attalabs/vinaya 0.42.2 → 0.43.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 (82) hide show
  1. package/dist/checks/bin/check-evidence-fresh.js +8 -5
  2. package/dist/index.js +20 -17
  3. package/dist/lib/pre-push-cache-test-run.js +3 -1
  4. package/dist/programs/archive.js +3 -1
  5. package/dist/programs/check.js +3 -1
  6. package/dist/programs/commit-msg.js +3 -1
  7. package/dist/programs/dev-review-loop.js +9 -6
  8. package/dist/programs/dispatch.js +3 -1
  9. package/dist/programs/log-emit.js +3 -1
  10. package/dist/programs/log-selftest.js +3 -1
  11. package/dist/programs/log-send.js +3 -1
  12. package/dist/programs/pr-report.js +8 -5
  13. package/dist/programs/pr-snapshot.js +3 -1
  14. package/dist/programs/pr-verify-evidence.js +8 -5
  15. package/dist/programs/pr.js +3 -1
  16. package/dist/programs/review-post.js +3 -1
  17. package/dist/programs/review-status.js +3 -1
  18. package/dist/programs/run-engine.js +110594 -0
  19. package/dist/programs/supervised-command.js +67 -0
  20. package/dist/programs/sync.js +3 -1
  21. package/dist/programs/task-brief.js +5 -3
  22. package/dist/programs/task-sweep.js +3 -1
  23. package/dist/programs/task-tools-serve.js +13 -11
  24. package/dist/programs/tokens.js +3 -1
  25. package/dist/programs/waiver.js +3 -1
  26. package/dist/vinaya-strict/checks/registry.ts +1085 -0
  27. package/dist/vinaya-strict/executing/code-reviewer/README.md +3 -0
  28. package/dist/vinaya-strict/executing/code-reviewer/doctrine.md +185 -0
  29. package/dist/vinaya-strict/executing/code-reviewer/evals/README.md +1 -0
  30. package/dist/vinaya-strict/executing/code-reviewer/evals/code-reviewer-cases.json +280 -0
  31. package/dist/vinaya-strict/executing/code-reviewer/grants.yaml +22 -0
  32. package/dist/vinaya-strict/executing/code-reviewer/output.schema.json +93 -0
  33. package/dist/vinaya-strict/executing/code-reviewer/review-result.ts +347 -0
  34. package/dist/vinaya-strict/executing/dev-review.flow.yaml +103 -0
  35. package/dist/vinaya-strict/executing/developer/README.md +3 -0
  36. package/dist/vinaya-strict/executing/developer/developer-doctrine-shape.test.ts +69 -0
  37. package/dist/vinaya-strict/executing/developer/developer-turn-result.ts +286 -0
  38. package/dist/vinaya-strict/executing/developer/doctrine.md +111 -0
  39. package/dist/vinaya-strict/executing/developer/evals/README.md +1 -0
  40. package/dist/vinaya-strict/executing/developer/evals/developer-capability-cases.json +6275 -0
  41. package/dist/vinaya-strict/executing/developer/evals/developer-capability-held-out.json +11526 -0
  42. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.test.ts +498 -0
  43. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.ts +1407 -0
  44. package/dist/vinaya-strict/executing/developer/grants.yaml +25 -0
  45. package/dist/vinaya-strict/executing/developer/output.schema.json +148 -0
  46. package/dist/vinaya-strict/executing/developer/reference.md +376 -0
  47. package/dist/vinaya-strict/executing/operator/doctrine.md +209 -0
  48. package/dist/vinaya-strict/executing/security-reviewer/README.md +3 -0
  49. package/dist/vinaya-strict/executing/security-reviewer/doctrine.md +171 -0
  50. package/dist/vinaya-strict/executing/security-reviewer/evals/README.md +1 -0
  51. package/dist/vinaya-strict/executing/security-reviewer/evals/security-reviewer-cases.json +141 -0
  52. package/dist/vinaya-strict/executing/security-reviewer/grants.yaml +22 -0
  53. package/dist/vinaya-strict/executing/security-reviewer/output.schema.json +93 -0
  54. package/dist/vinaya-strict/integration/config/vinaya-config-section.ts +1278 -0
  55. package/dist/vinaya-strict/integration/policies/vinaya-policies.ts +52 -0
  56. package/dist/vinaya-strict/integration/process/process-integration.ts +57 -0
  57. package/dist/vinaya-strict/loops/dev-review/v2/dev-review-v2.flow.yaml +136 -0
  58. package/dist/vinaya-strict/process.yaml +43 -0
  59. package/dist/vinaya-strict/retrospecting/archivist/doctrine.md +174 -0
  60. package/dist/vinaya-strict/retrospecting/tranche-archivist/doctrine.md +270 -0
  61. package/dist/vinaya-strict/thinking/architect/doctrine.md +110 -0
  62. package/dist/vinaya-strict/thinking/planner/doctrine.md +105 -0
  63. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.test.ts +128 -0
  64. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.ts +169 -0
  65. package/dist/vinaya-strict/thinking/planner/tools/open-issue.test.ts +701 -0
  66. package/dist/vinaya-strict/thinking/planner/tools/open-issue.ts +1035 -0
  67. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.test.ts +359 -0
  68. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.ts +815 -0
  69. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.test.ts +200 -0
  70. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.ts +458 -0
  71. package/package.json +4 -2
  72. package/studio-standalone/apps/vinaya-studio/.next/BUILD_ID +1 -1
  73. package/studio-standalone/apps/vinaya-studio/.next/build-manifest.json +2 -2
  74. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.html +1 -1
  75. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.rsc +1 -1
  76. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  77. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  78. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  79. package/studio-standalone/apps/vinaya-studio/.next/server/middleware-build-manifest.js +1 -1
  80. package/studio-standalone/apps/vinaya-studio/.next/server/pages/500.html +1 -1
  81. /package/studio-standalone/apps/vinaya-studio/.next/static/{Q_xjhiWztjosXWbMSJ0Yp → x2q88XfwsihlevulRhIvs}/_buildManifest.js +0 -0
  82. /package/studio-standalone/apps/vinaya-studio/.next/static/{Q_xjhiWztjosXWbMSJ0Yp → x2q88XfwsihlevulRhIvs}/_ssgManifest.js +0 -0
@@ -0,0 +1,1278 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { execFileSync } from 'node:child_process'
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
4
+ import { homedir } from 'node:os'
5
+ import { dirname, join } from 'node:path'
6
+ import { z } from 'zod'
7
+ import {
8
+ CODE_REVIEW_SEVERITY_ORDER,
9
+ DEFAULT_READY_PUSH_TIMEOUT_MINUTES,
10
+ DEFAULT_REVIEW_POLICY,
11
+ isKnownSeverity,
12
+ type ReviewPolicy,
13
+ SECURITY_SEVERITY_ORDER
14
+ } from '../../tools/task-contract/review-policy'
15
+ import { DEFAULT_COLLISION_THRESHOLD } from '../../tools/task-contract/issue-validation'
16
+ import { type GateCutovers, NO_GATE_CUTOVERS } from '../../tools/task-contract/gate-cutovers'
17
+ import { DEFAULT_RELEASE_ACTOR } from '../../tools/review-gate'
18
+ import { normalizeSpecPath } from '../../tools/reader-resolvable-prose'
19
+ import { DOCTRINE_TREE } from '../../tools/doctrine/doctrine-map'
20
+ import {
21
+ fetchFailureReason,
22
+ GIT_IDENTITY_TIMEOUT_MS,
23
+ isMissingFileError,
24
+ NO_TRUST_ANCHOR_REPO_MESSAGE,
25
+ readLocalOverrideFile,
26
+ type TrustAnchorFetcher
27
+ } from '../../../../kernel/config/loader/config-loader.js'
28
+ import { isSafeRepoRelPath, type KernelConfig } from '../../../../kernel/config/schema/config-schema.js'
29
+ import type { GlobalOnlyKey, ProcessConfigSection } from '../../../../kernel/config/schema/process-config-section.js'
30
+ import {
31
+ outsideRepositoryReason,
32
+ ProseRulesSchema,
33
+ PublishedProseSchema,
34
+ RepoRelativePathSchema
35
+ } from '../../tools/prose-rules-config.js'
36
+ import { CLAUDE_COMMAND_PATH } from '../claude-command-emitter.js'
37
+ import { GEMINI_COMMAND_PATH } from '../gemini-command-emitter.js'
38
+
39
+ // Vinaya's section of the configuration: the keys that name its review loop,
40
+ // its roles, its briefs and its prose rules — review policy, gate cutovers,
41
+ // prose rules, the collision threshold, the release actor, principals, tokens
42
+ // collection and the command-emitter paths — with their refinements and
43
+ // resolvers. `compose.ts` joins it with the kernel's keys into the one schema.
44
+
45
+ /** Vinaya's machine-wide home folder and the names of its configuration files. */
46
+ export const VINAYA_HOME = join(homedir(), '.vinaya')
47
+ export const VINAYA_GLOBAL_CONFIG_FILENAME = 'config.json'
48
+ export const VINAYA_CONFIG_FILENAME = 'vinaya.config.json'
49
+
50
+ // ── The kernel leaves Vinaya supplies ───────────────────────────────────────
51
+
52
+ // The managed-block path spellings `buildInitOps` ever generates.
53
+ // `startsWith('.git/')` (lib/ops.ts's runtime discriminator) is a
54
+ // case-sensitive prefix test, and `.git` alone (no trailing slash) resolves
55
+ // to a real directory rather than a file — both escape it, one via a
56
+ // case-insensitive filesystem, one on every filesystem. Rejecting any spelling
57
+ // that isn't byte-exactly one of these prefixes at parse time means
58
+ // lib/ops.ts's resolvers never see a bad `blocks[].path`.
59
+ //
60
+ // `.claude/hooks/` is the fourth: the Claude Code Stop-hook script
61
+ // (`claude-stop-hook-emitter.ts`) is a marker-delimited managed block exactly
62
+ // like the three git-hook directories, just never `.git/`-prefixed.
63
+ export const CANONICAL_HOOK_BLOCK_PREFIXES = ['.git/', '.husky/', '.vinaya/hooks/', '.claude/hooks/'] as const
64
+
65
+ // Same no-privileged-field discipline as every check field: an adopter's own
66
+ // custom check whose failure only their own equivalent of the Principal can
67
+ // clear declares this exactly like `test-plan` does in the core registry — see
68
+ // `CheckSpec.principalOwed`'s doc comment for the exclusion semantics this
69
+ // unlocks. Placed after `ownWorkflow` in every check entry.
70
+ export const VINAYA_CHECK_ENTRY_FIELDS = {
71
+ principalOwed: z.literal(true).optional()
72
+ }
73
+
74
+ const AGENTS_SKILLS_PREFIX = '.agents/skills/'
75
+ const CLAUDE_SKILLS_PREFIX = '.claude/skills/vinaya-'
76
+
77
+ /**
78
+ * `true` for the agent-vendor file paths (the two commands and the role
79
+ * skills in both `.agents/skills/` and `.claude/skills/`), but ONLY when the manifest
80
+ * has never recorded any `--agents` choice at all (`agents === undefined`,
81
+ * same condition `resolveAgentVendors` widens to every vendor for).
82
+ * `upgrade`'s `planUpgrade` and `doctor`'s `diagnoseInstall` both gate a
83
+ * `create-file` op on a SEPARATE `manifest.files` ownership list, unrelated
84
+ * to `agents` — without this, `resolveAgentVendors` correctly resolving to
85
+ * every vendor still would not get these files past that second gate,
86
+ * since `manifest.files` never listed them for an install predating the
87
+ * feature. This is the shared other half both callers need.
88
+ */
89
+ export function isDefaultedAgentVendorPath(path: string, manifest: { agents?: readonly string[] }): boolean {
90
+ if (manifest.agents !== undefined) return false
91
+ return (
92
+ path === CLAUDE_COMMAND_PATH ||
93
+ path === GEMINI_COMMAND_PATH ||
94
+ path.startsWith(AGENTS_SKILLS_PREFIX) ||
95
+ path.startsWith(CLAUDE_SKILLS_PREFIX)
96
+ )
97
+ }
98
+
99
+ // ── Vinaya's keys ───────────────────────────────────────────────────────────
100
+
101
+ // `roles`: per-role override and additive-role registration, keyed by
102
+ // config key. `contract` is PATH-ONLY, resolved relative to this config
103
+ // file's own directory — a slash-free value (e.g. `"developer.md"`) is
104
+ // rejected at load, so the field can never be confused for a bare role id
105
+ // or a shell command the way `checks.run` legitimately can be. The
106
+ // resolver (`src/roles/resolver.ts`) does the override-vs-additive
107
+ // classification and structural contract validation; this schema only
108
+ // proves the shape is a path.
109
+ const RoleEntrySchema = z.object({
110
+ contract: z.string().refine((p) => p.includes('/'), {
111
+ message: 'must be a path (contain at least one "/"), not a bare filename'
112
+ })
113
+ })
114
+ export type RoleEntry = z.infer<typeof RoleEntrySchema>
115
+
116
+ // The upper bound the `report` key's own `superRefine` enforces on
117
+ // `report.commandTimeoutMs` — 1 hour. A misconfigured value above this could
118
+ // otherwise leave `pr report`'s evidence runner hanging on a stuck
119
+ // subprocess for arbitrarily long (a round-2 security ruling).
120
+ const MAX_REPORT_COMMAND_TIMEOUT_MS = 3_600_000
121
+
122
+ // briefSchema: the config-defined brief schema
123
+ // the forge-write commands validate a body against. WHICH sections a `pr`/
124
+ // `issue` body must carry is expressed HERE, never hardcoded in the command
125
+ // code — this repo's required-section set is just one instance (one
126
+ // derivation, N consumers). Declarative only: a section is either a named
127
+ // battle-tested built-in (backed by an `@attalabs/process-vinaya` validator) or a
128
+ // generic heading/field/phrase matcher an adopter authors for their own
129
+ // required sections. No conditional grammar (no if/unless/except) —
130
+ // any diff-conditionality (lock-ack, premise coverage) lives inside the
131
+ // built-in validator's code, never in this config.
132
+ export const BRIEF_BUILTINS = [
133
+ 'tier',
134
+ 'testPlan',
135
+ 'testPlanExclusivity',
136
+ 'principalPlaceholder',
137
+ 'surfaceMap',
138
+ 'docUpdateList',
139
+ 'worktreeStep0',
140
+ 'stopConditions',
141
+ 'autonomyClause',
142
+ 'project',
143
+ 'for',
144
+ 'closesN',
145
+ 'premiseCoverage',
146
+ 'issueRationale',
147
+ 'objectives',
148
+ 'briefSections',
149
+ 'milestoneShape'
150
+ ] as const
151
+ export type BriefBuiltin = (typeof BRIEF_BUILTINS)[number]
152
+
153
+ // A single required section. Discriminated by which key is present:
154
+ // { "builtin": "tier" } — run the named process-package validator
155
+ // { "heading": "Rollback Plan" } — require a matching `## …` heading
156
+ // { "field": "Ticket" } — require a `Ticket:` header field
157
+ // { "phrase": "signed-off-by" } — require a literal phrase anywhere
158
+ // `name` is an optional human label for the custom-matcher forms.
159
+ const BriefSectionSchema = z.union([
160
+ z.object({ builtin: z.enum(BRIEF_BUILTINS) }),
161
+ z.object({ heading: z.string().min(1), name: z.string().optional() }),
162
+ z.object({ field: z.string().min(1), name: z.string().optional() }),
163
+ z.object({ phrase: z.string().min(1), name: z.string().optional() })
164
+ ])
165
+ export type BriefSection = z.infer<typeof BriefSectionSchema>
166
+
167
+ const BriefSchemaSchema = z.object({
168
+ pr: z.object({ sections: z.array(BriefSectionSchema) }).optional(),
169
+ issue: z.object({ sections: z.array(BriefSectionSchema) }).optional(),
170
+ // Same shape as pr/issue — an adopter's required sections for `vinaya
171
+ // milestone create` bodies. `checkMilestoneShape`'s own goal/Release:/
172
+ // intents refusal is unconditional (called directly by the command, not
173
+ // config-gated, mirroring the Issue-only A/B/D content gate) — this key
174
+ // only lets an adopter layer their own custom `heading`/`field`/`phrase`
175
+ // sections on top, or opt into the `milestoneShape` builtin explicitly.
176
+ milestone: z.object({ sections: z.array(BriefSectionSchema) }).optional(),
177
+ // Builtins this adopter has DELIBERATELY dropped, by builtin name
178
+ // (`closesN`, `tier`, …). Purely a silencer for `vinaya doctor`'s
179
+ // brief-schema divergence report — it grants nothing and gates nothing, so
180
+ // acking a builtin that is still present in `sections` changes no
181
+ // behaviour anywhere. `briefSchema` is adopter-owned and `upgrade` never
182
+ // rewrites it, which is correct; before this key existed, that ownership
183
+ // also meant a dropped builtin was permanently invisible. The report
184
+ // makes the divergence visible; this makes a considered choice quiet while
185
+ // an accidental one keeps surfacing.
186
+ ack: z.array(z.enum(BRIEF_BUILTINS)).optional()
187
+ })
188
+ export type BriefSchema = z.infer<typeof BriefSchemaSchema>
189
+
190
+ // `projects`: a config-native home for project metadata, alongside (not
191
+ // instead of) `.vinaya/projects.md` (`registry-write.ts`'s `PROJECTS_REGISTRY_PATH`).
192
+ // `init product <name>` appends an entry here at the same time it appends the
193
+ // registry row — see `registry-write.ts`'s `planConfigProjectEntry`/
194
+ // `applyConfigProjectEntry`, the config-side sibling of `planRegistryRow`/
195
+ // `applyRegistryRow`. Minimal metadata only, matching the config grammar's
196
+ // declarative discipline: `name` identifies the entry (dedup key, mirrors the
197
+ // registry row's own `Project` column); `description`/`path` are optional
198
+ // display metadata. Never load-bearing for enforcement — no gate or resolver
199
+ // reads this key, exactly like the registry file it sits beside.
200
+ const ProjectEntrySchema = z.object({
201
+ name: z.string().min(1),
202
+ description: z.string().min(1).optional(),
203
+ path: z.string().min(1).optional()
204
+ })
205
+ export type ProjectEntry = z.infer<typeof ProjectEntrySchema>
206
+
207
+ /** A parsed `tokens.collect` declaration — see `tokens.collect`'s own schema comment. */
208
+ export type TokensCollectDeclaration = { interpreter: string; script: string }
209
+
210
+ /**
211
+ * Parses a `tokens.collect` string into its two required parts, or `null`
212
+ * if the string is not shaped that way. Deliberately RIGID, not a shell
213
+ * tokenizer: exactly one interpreter token, one script-path token, nothing
214
+ * else — no flags, no quoting, no `&&`/`|`/`;`, no extra arguments. This is
215
+ * what makes the round-3 content-pinning fix (`tokens.collect trust cache`,
216
+ * below) rigorous rather than heuristic: there is exactly one file this
217
+ * declaration can ever mean, identified by parsing alone, never by
218
+ * guessing which whitespace-delimited token of an otherwise-arbitrary
219
+ * shell string "looks like a path" (a security-review finding —
220
+ * that guessing was the earlier design this one replaces).
221
+ *
222
+ * The script segment must additionally satisfy `isSafeRepoRelPath` — no
223
+ * absolute path, no `..` segment — since it is later resolved relative to
224
+ * this repo-local config file's own directory, exactly like
225
+ * `RoleEntrySchema.contract`'s resolution.
226
+ */
227
+ export function parseTokensCollectDeclaration(value: string): TokensCollectDeclaration | null {
228
+ const m = value.trim().match(/^(\S+)\s+(\S+)$/)
229
+ if (!m) return null
230
+ const [, interpreter, script] = m as [string, string, string]
231
+ if (!isSafeRepoRelPath(script)) return null
232
+ return { interpreter, script }
233
+ }
234
+
235
+ /** Vinaya's top-level keys, each the schema the composed configuration places under it. */
236
+ export const VINAYA_CONFIG_FRAGMENT = {
237
+ roles: z.record(z.string(), RoleEntrySchema).optional(),
238
+ briefSchema: BriefSchemaSchema.optional(),
239
+ // GitHub logins trusted as this repo's own principals for review-gate
240
+ // verdict-author verification and actor-verified waiver labels
241
+ // (`vinaya/waiver:docs`, `vinaya/waiver:review`). There is no built-in
242
+ // default: without it every Principal-deciding check and command refuses
243
+ // (`resolveTrustedPrincipals`). Repo-local only, same as `checks` — stripped from a global config below, since who
244
+ // counts as a trusted approver must come from the reviewed, committed
245
+ // per-repo file, never a machine-wide personal config.
246
+ principals: z.array(z.string()).min(1).optional(),
247
+ // The GitHub login expected to author this repo's Changesets release PR
248
+ // (`changeset-release/main`) — overrides `DEFAULT_RELEASE_ACTOR`
249
+ // (`github-actions[bot]`, the stock `changesets/action` + ambient
250
+ // `GITHUB_TOKEN` identity) when this repo opens release PRs some other
251
+ // way, e.g. a custom PAT (`RELEASE_TOKEN`) whose owner is a real user
252
+ // login, not a bot. Same trust class as `principals` — repo-local only,
253
+ // resolved via the same server-side trust-anchor read
254
+ // (`resolveReleaseActor` + `loadTrustAnchorConfig`), never from local git
255
+ // or an env var: this value gates the Changesets-release exemption on
256
+ // `body-bare-digits`, a merge-authority decision.
257
+ releaseActor: z.string().min(1).optional(),
258
+ // Adopter-declared token-usage collection for `vinaya tokens`
259
+ // (`harness/processes/vinaya-strict/doctrine/tranche-model.md` §12 layer 2), for a non-Claude-Code host —
260
+ // whose stdout must be a JSON object shaped `{ inputTokens, outputTokens,
261
+ // cacheCreationInputTokens, cacheReadInputTokens, model }` — the
262
+ // `TranscriptSummary` seam flattened to JSON. Absent, `vinaya tokens`
263
+ // falls back to the shipped Claude Code transcript adapter unchanged —
264
+ // this key is a pure ADDITION of a second route, never a replacement of
265
+ // the first, and the shipped adapter is never removed when this key is
266
+ // present.
267
+ //
268
+ // This is an opt-in collection route, not a capability declaration:
269
+ // `resolveMeteringCapability`'s probe stays host-identity-blind exactly as
270
+ // ruled (Principal, 2026-08-28) — there is no `tokens.metering` key, and
271
+ // this key is read only inside `vinaya tokens`'s own command path, never
272
+ // consulted by the probe `vinaya doctor`/`vinaya upgrade` call.
273
+ //
274
+ // Read from the repo-root config only, same trust class as `checks` and
275
+ // `principals`: a value that decides what runs on this turn must come
276
+ // from the reviewed, committed per-repo file, never a machine-wide
277
+ // personal config — stripped from a global config below with a loud
278
+ // warning, never resolved.
279
+ //
280
+ // GRAMMAR: exactly
281
+ // `"<interpreter> <repo-relative-script-path>"` — two whitespace-
282
+ // delimited tokens, nothing else. `parseTokensCollectDeclaration`
283
+ // (above) is the one parser; no flags, no shell syntax (`&&`/`|`/`;`),
284
+ // no quoting are ever part of this grammar, and the script segment must
285
+ // satisfy `isSafeRepoRelPath`. This is deliberately RIGID, replacing an
286
+ // earlier, more permissive "any shell command" shape two rounds of
287
+ // security review found real holes in:
288
+ // - Round 1: an arbitrary shell command ran with no printed trace at
289
+ // all. Fixed: `vinaya tokens` prints the exact command to stderr
290
+ // immediately before every run (`tokens.ts`) — an audit trail, never
291
+ // a gate on its own.
292
+ // - Round 2: a printed trace is not a gate — nothing stopped a
293
+ // malicious or mistaken value from running the first time anyone ran
294
+ // `vinaya tokens`. Fixed: `vinaya tokens` REFUSES to run at all until
295
+ // a human has explicitly approved it, per exact declaration, per
296
+ // repo, per machine, via `vinaya tokens --trust-collect`
297
+ // (`tokens.collect trust cache`, below).
298
+ // - Round 3: trust from round 2 bound to the command STRING alone,
299
+ // never to the CONTENT of the script it invoked — editing only the
300
+ // script, never this config, executed the new content silently on
301
+ // the next run. Closed by narrowing the grammar itself (this
302
+ // comment): the interpreter/script split is exact, never heuristic,
303
+ // so the ONE file a declaration can mean is always identifiable, and
304
+ // trust now pins that file's content (a real `git hash-object` blob
305
+ // hash) alongside the declaration. Spawned via `execFile` — never a
306
+ // shell — closing the earlier "shell interpretation" surface as a
307
+ // side effect of the narrower grammar, not a separate fix.
308
+ tokens: z
309
+ .object({
310
+ collect: z
311
+ .string()
312
+ .min(1)
313
+ .refine((v) => parseTokensCollectDeclaration(v) !== null, {
314
+ message:
315
+ 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
316
+ })
317
+ })
318
+ .optional(),
319
+ // The sanctioned "I need one more blast-radius collision domain" path —
320
+ // the legacy static packages file is retired, zero backward
321
+ // compatibility, so this is now the ONLY way to declare one beyond
322
+ // derivation. `checkBlastRadiusScope`'s domain list
323
+ // (`harness/processes/vinaya-strict/tools/task-contract/forge/forge-write.ts`'s `readSharedPackages`, mirroring
324
+ // `harness/processes/vinaya-strict/thinking/planner/tools/open-issue.ts`'s own) is live-derived from
325
+ // `package.json` workspaces plus a built-in cross-cutting default set
326
+ // (lockfile, monorepo config, CI, git hooks); an adopter who needs a
327
+ // domain beyond those (a `migrations/` folder, a codegen output dir)
328
+ // declares it here.
329
+ blastRadius: z.object({ extraDomains: z.array(z.string()).optional() }).optional(),
330
+ // De-hardcodes `reader-resolvable-prose`/`retired-vocabulary`'s repo-specific
331
+ // inputs — the two prose/vocabulary core checks read
332
+ // this key at check-run time (`check-reader-resolvable-prose.ts`,
333
+ // `check-retired-vocabulary.ts`), never at generation time, so editing it
334
+ // takes effect on the very next `vinaya check` with no `upgrade` needed.
335
+ // Every field is optional and additive: an adopter who sets nothing gets
336
+ // this repo's own defaults (the doctrine map's source paths under `harness/processes/vinaya-strict`, a
337
+ // dormant reader-facing sweep, `legacySlugDir` derived from `doctrineRoot`).
338
+ proseGates: z
339
+ .object({
340
+ // The doctrine directory these checks sweep in full (`ships` class) —
341
+ // the doctrine map's source paths under `harness/processes/vinaya-strict` by default. An adopter
342
+ // who names their installed doctrine tree differently sets this once;
343
+ // both checks read it the same way.
344
+ doctrineRoot: z.string().min(1).optional(),
345
+ // The reader-facing surface's path prefix and filename suffix — e.g.
346
+ // `apps/web/src/app` and `/page.tsx`. BOTH must be set together for the
347
+ // reader-facing sweep to run at all; either absent (the default) is a
348
+ // declared no-op, matching this repo's own `READER_FACING_ROOT: null`
349
+ // (no public site here to sweep), not a silent gap.
350
+ readerFacingPrefix: z.string().min(1).optional(),
351
+ readerFacingSuffix: z.string().min(1).optional(),
352
+ // The archived-tranche directory `checkUnresolvableReferences`'s
353
+ // legacy-slug list is derived from (filenames, not content). Defaults
354
+ // to `<doctrineRoot>/tranches/completed`; absent-on-disk degrades to
355
+ // an explicitly dormant legacy-slug class, never an error.
356
+ legacySlugDir: z.string().min(1).optional(),
357
+ // The source-comment class — scans `.ts` comment lines
358
+ // under these directory roots for a tranche-slug or forge-number
359
+ // citation. Unset entirely (the default) leaves the class dormant, the
360
+ // same "declared no-op, not a silent gap" discipline `readerFacingPrefix`/
361
+ // `readerFacingSuffix` use above. Each entry is a repo-relative
362
+ // directory (or file) path swept recursively for `.ts` files — a
363
+ // prefix, like `PRODUCT_SLUG_SCOPE`, not a shell glob pattern, despite
364
+ // the field's name (chosen to match the brief's own vocabulary for
365
+ // this key).
366
+ sourceComments: z
367
+ .object({
368
+ globs: z.array(z.string().min(1)).optional(),
369
+ // Exact repo-relative file paths to skip entirely — a test fixture
370
+ // that deliberately pins a historical tranche name or forge number
371
+ // in a comment, where rewriting the citation away would break the
372
+ // thing the fixture exists to prove.
373
+ allowlist: z.array(z.string().min(1)).optional(),
374
+ // `'warning'` (the default) reports without failing the run —
375
+ // the rollout precedent every class in this file follows. `'error'`
376
+ // makes a reportable finding fail the check's exit code, same as
377
+ // the `product` class always has.
378
+ severity: z.enum(['warning', 'error']).optional()
379
+ })
380
+ .optional(),
381
+ // Exact repo-relative paths skipped entirely by the spec class below:
382
+ // stock already failing the day this sweep was extended to specs,
383
+ // listed here so the sweep can turn blocking on day one without
384
+ // failing every open PR against the existing backlog. Shrinks as each
385
+ // spec's prose is rewritten to state its facts plainly instead of
386
+ // citing a tranche, an Issue, or a document outside this repository.
387
+ // Exempts a path the defaults below brought in exactly as it exempts
388
+ // one under an app's own `specs/**`.
389
+ //
390
+ // Two forms. An array exempts each listed file entirely. An object maps
391
+ // each listed file to the most spec-class findings it may carry: above
392
+ // its number the file fails, at or below it passes, so a listed file
393
+ // can no longer gain a citation and its number only goes down.
394
+ specGrandfather: z
395
+ .union([z.array(z.string().min(1)), z.record(z.string().min(1), z.number().int().min(0))])
396
+ .optional(),
397
+ // Repo-relative files or folders ADDED to the spec class, on top of
398
+ // the defaults every repository gets with no configuration at all: a
399
+ // root `SPEC.md`, a root `CONTEXT.md`, every `.md` under `docs/adr/`,
400
+ // and every `apps/<app>/specs/**/*.md`. A folder entry is swept
401
+ // recursively for `.md` files; a file entry names that one file.
402
+ // `README.md` is never a default and should not be added lightly — the
403
+ // tranche-slug pattern the class runs matches an ordinary stack badge.
404
+ //
405
+ // An entry names a path inside THIS repository, so one that reaches
406
+ // outside it — absolute, or climbing through `..` — is refused here
407
+ // rather than resolved: the class would otherwise read a file this
408
+ // repository does not own and quote its text in a finding. A trailing
409
+ // slash or a leading `./` is accepted and normalized, since both spell
410
+ // a path this repository does own.
411
+ specPaths: z.array(RepoRelativePathSchema).optional(),
412
+ // The product class's file set — repository-relative files or folders
413
+ // under which a tranche-slug citation in product code blocks. Replaces
414
+ // `PRODUCT_SLUG_SCOPE` (this repository's CLI source, workflows,
415
+ // `.vinaya` and the two package READMEs) when set; never added to it.
416
+ productPaths: z.array(RepoRelativePathSchema).optional(),
417
+ // The published pass (the documentation gate's C7) — see
418
+ // `PublishedProseSchema`.
419
+ published: PublishedProseSchema.optional(),
420
+ // The writing rules both prose checks run: `exempt` (paths no rule
421
+ // reads), `defaults` (per default rule id, `"off"` or a partial
422
+ // override of scopes, severity or exempt) and `custom` (rules a
423
+ // repository writes itself). Validated in full at load, every refusal
424
+ // naming its key — see `prose-rules-config.ts`. Read at check-run time
425
+ // like every key here, so an edit takes effect on the next run.
426
+ rules: ProseRulesSchema.optional()
427
+ })
428
+ .optional(),
429
+ // Config-native project metadata — see the `ProjectEntrySchema` comment
430
+ // above. Additive-only; absent entirely for a single-project repo.
431
+ projects: z.array(ProjectEntrySchema).optional(),
432
+ // `vinaya dispatch <role> --agent <vendor>` (`harness/processes/vinaya-strict/loops/dev-review/dispatch/dispatch.ts`).
433
+ // `timeoutMs` is the Developer wall-time ceiling before `dispatchRole`
434
+ // sends `SIGTERM` (then `SIGKILL`) to the child; absent defaults to four
435
+ // hours (`DEFAULT_TIMEOUT_MS` in `dispatch.ts`). `reviewerTimeoutMs` is the
436
+ // corresponding ceiling for code-reviewer and security dispatches; absent
437
+ // defaults to twenty minutes (`DEFAULT_REVIEWER_TIMEOUT_MS`).
438
+ // `agent` is a default vendor the CLI's own `--agent` flag overrides, for a
439
+ // repo that always dispatches the same vendor.
440
+ //
441
+ // The three vendor names are duplicated here as a literal enum rather than
442
+ // imported from `./dispatch.js`'s `AGENT_VENDOR_NAMES`: `dispatch.ts`
443
+ // itself calls `loadConfig()` (this file) to resolve `dispatch.timeoutMs`,
444
+ // so importing the other direction would make the two files circular. The
445
+ // list is fixed at three and reviewed alongside any change to
446
+ // `dispatch.ts`'s own `AgentVendor` union, which stays the source of truth
447
+ // for the type.
448
+ // `killGraceMs`: the window between the SIGTERM sent
449
+ // at `timeoutMs` and the SIGKILL escalation that follows it — absent
450
+ // defaults to five seconds (`SIGKILL_GRACE_MS` in `dispatch.ts`). Exists
451
+ // so a test proving the SIGTERM-then-SIGKILL escalation itself happens
452
+ // does not have to pay the real production grace window to observe it: a
453
+ // test config can set this to a few milliseconds and assert the same
454
+ // behavior in a fraction of the wall time, without faking the process
455
+ // signalling it exercises.
456
+ dispatch: z
457
+ .object({
458
+ timeoutMs: z.number().int().positive().optional(),
459
+ reviewerTimeoutMs: z.number().int().positive().optional(),
460
+ killGraceMs: z.number().int().positive().optional(),
461
+ agent: z.enum(['claude', 'codex']).optional()
462
+ })
463
+ .optional(),
464
+ // Which severities block is repository policy — two separate thresholds,
465
+ // one per review role's own ordered
466
+ // severity scale (`@attalabs/process-vinaya`'s `CODE_REVIEW_SEVERITY_ORDER`/
467
+ // `SECURITY_SEVERITY_ORDER`). Typed as a bare string here, deliberately NOT
468
+ // `z.enum(...)`: a `z.enum` failure fails the WHOLE config's schema parse,
469
+ // which both `loadConfig`/`loadTrustAnchorConfig` turn into a `null`
470
+ // (each with a one-line warning, but every other field falls back too) —
471
+ // the opposite of this field's own contract. `resolveReviewPolicy`
472
+ // (below) is where an unknown value actually refuses, so a typo here is a
473
+ // review-policy-specific refusal, never a whole-config fallback to
474
+ // defaults. Same trust class as `principals` —
475
+ // read only via `loadTrustAnchorConfig` (the default branch), never the PR
476
+ // checkout, so a change cannot lower its own threshold.
477
+ reviewPolicy: z
478
+ .object({
479
+ codeReviewThreshold: z.string().min(1).optional(),
480
+ securityThreshold: z.string().min(1).optional(),
481
+ // Same deliberately-loose typing as the two thresholds
482
+ // above, for the same reason: a `z.number().int().positive()` failure
483
+ // here would fail the WHOLE config's schema parse (a one-line warning,
484
+ // then every field falls back to defaults) rather than this field's
485
+ // own loud refusal in `resolveReviewPolicy`, below.
486
+ maxRounds: z.number().optional(),
487
+ // Same deliberately-loose typing, same reason as the fields above: a
488
+ // schema-level refusal here would fail the WHOLE config's parse rather
489
+ // than this field's own loud refusal in `resolveReviewPolicy`.
490
+ maxTaskMinutes: z.number().optional(),
491
+ // Same deliberately-loose typing, same reason: the positive-integer
492
+ // refusal lives in `resolveReviewPolicy`.
493
+ readyPushTimeoutMinutes: z.number().optional()
494
+ })
495
+ .optional(),
496
+ // The agent-configuration security scanner the review loop runs before the
497
+ // security pass. `command` is the scanner as an argv
498
+ // list — its first element the executable, the rest its arguments, a pinned
499
+ // version included in the args (`["npx", "--yes", "ecc-agentshield@1.6.0",
500
+ // "scan"]`). The loop appends the directory to scan (the head-verified
501
+ // candidate copy) as a final argument and runs it once per round, ONLY when
502
+ // the pull request touches agent configuration (`.claude/**`, `.mcp.json`,
503
+ // `.agents/**` — fixed in code, never configurable), with a constructed
504
+ // environment carrying no forge credential, a time limit and an output cap.
505
+ // Absent, the security pass is told no scanner is configured and the round
506
+ // proceeds unchanged — never a pause. Read, like `reviewPolicy`/`principals`,
507
+ // only from the default-branch trust anchor (`resolveSecurityScanCommand` +
508
+ // `loadTrustAnchorConfig`), never the pull request's own checkout: the key
509
+ // names a subprocess that runs in the driver's environment, so a pull request
510
+ // must not be able to choose it in its own diff.
511
+ securityScan: z
512
+ .object({
513
+ command: z.array(z.string().min(1)).min(1)
514
+ })
515
+ .optional(),
516
+ // The five Issue/PR gate cutovers — one Issue/PR number per gate below
517
+ // which that gate is grandfathered (an older Issue/PR passes
518
+ // unconditionally). These were hardcoded constants in `@attalabs/process-vinaya`
519
+ // (`OBJECTIVES_SINCE_ISSUE` etc.); they are now this optional key so a
520
+ // repository can set its own, and — crucially — an ABSENT key means NO
521
+ // cutover: `resolveGateCutovers` resolves every field to `null`, and each
522
+ // pure gate then applies to every Issue/PR from number 1 (a new repository's
523
+ // Issue 1 is refused without `## Objectives` exactly as a high-numbered
524
+ // Issue is, O1). Only a repository whose Issues/PRs predate a gate sets these
525
+ // — this monorepo does, restating its own historical numbers so its older
526
+ // Issues and pull requests are judged exactly as before (O2). Every field is
527
+ // an optional non-negative integer; an omitted field within the block is
528
+ // itself "no cutover" for that one gate. Read from the working-tree config
529
+ // (`loadConfig`/`loadConfigChecked`), not the trust anchor: the value must be
530
+ // present on THIS branch for the transition to work (the default branch does
531
+ // not carry the key until this merges), and it is the same reviewed-committed
532
+ // trust class the source constants it replaces already had, never a
533
+ // merge-authority decision like `principals`/`reviewPolicy`.
534
+ gateCutovers: z
535
+ .object({
536
+ objectivesSinceIssue: z.number().int().nonnegative().optional(),
537
+ briefSectionsSinceIssue: z.number().int().nonnegative().optional(),
538
+ documentationSinceIssue: z.number().int().nonnegative().optional(),
539
+ briefRulesSincePr: z.number().int().nonnegative().optional(),
540
+ agentBoxesRefusedSincePr: z.number().int().nonnegative().optional()
541
+ })
542
+ .optional(),
543
+ // Plan-time policy. `collisionThreshold` is how many files two open tasks
544
+ // may share before the one being written must declare a `Conflicts-with`
545
+ // edge on the other: at or above it the write is refused, under it the
546
+ // overlap is printed as a warning and both tasks run in parallel. The
547
+ // asymmetry is the whole point — a merge conflict over one or two files
548
+ // costs minutes, serializing a task costs a whole dispatch — so the default
549
+ // (`DEFAULT_COLLISION_THRESHOLD`, three files) is deliberately permissive,
550
+ // and `0` turns the refusal off entirely, leaving only the warning. Read
551
+ // from the working-tree config like `gateCutovers`, and for the same
552
+ // reason: it is adopter policy of the reviewed-committed trust class, never
553
+ // a merge-authority decision like `principals`/`reviewPolicy`.
554
+ planning: z
555
+ .object({
556
+ collisionThreshold: z.number().int().nonnegative().optional()
557
+ })
558
+ .optional(),
559
+ // The pre-push hook's test-file selector (`lib/test-selector.ts`) chooses
560
+ // what to run by import-graph reachability from the diff — a rule whose
561
+ // own INPUT is the repository itself (scans `.github/workflows`, walks
562
+ // `package.json` exec bits, re-derives the changeset/CI-shard manifests)
563
+ // is never reached by that graph; nothing imports it, so it never ran at
564
+ // push time at all. `alwaysRun` names test files (glob, matched
565
+ // against the repo-root-relative path) that run on every push regardless
566
+ // of reachability — additive only, on top of whatever the import graph
567
+ // already selects, never a narrowing of it.
568
+ //
569
+ // `readyTests` opts a self-hosting repository's version-2 ready push, and
570
+ // the driver-owned repair pushes on its own open pull request, into
571
+ // required-CI testing: those pushes keep every cheap local gate and defer
572
+ // the selected test suite to the named required check on the approved
573
+ // head. Read from the default branch only (`pre-push-ready-policy.ts`);
574
+ // absent means local tests. The one supported pair is this repository's
575
+ // own CI workflow and its aggregate check — any other value is refused
576
+ // rather than read as an adopter CI protocol.
577
+ //
578
+ // `requiredCi` names the required current-head check a version-2 run's
579
+ // publication owes whether its selected tests ran locally or were deferred:
580
+ // test execution policy (`readyTests`) never removes it. Read from the
581
+ // default branch only, like `readyTests`; the same one supported pair. An
582
+ // existing `readyTests` opt-in supplies it when this field is absent, and a
583
+ // differing pair in both is refused. Absent with no opt-in, nothing extra is
584
+ // owed.
585
+ prePush: z
586
+ .object({
587
+ alwaysRun: z.array(z.string()).optional(),
588
+ readyTests: z
589
+ .object({
590
+ mode: z.literal('ci'),
591
+ workflow: z.literal('.github/workflows/ci.yml'),
592
+ check: z.literal('Vinaya CI')
593
+ })
594
+ .strict()
595
+ .optional(),
596
+ requiredCi: z
597
+ .object({
598
+ workflow: z.literal('.github/workflows/ci.yml'),
599
+ check: z.literal('Vinaya CI')
600
+ })
601
+ .strict()
602
+ .optional()
603
+ })
604
+ .optional(),
605
+ // The evidence runner's (`vinaya pr report`'s Group C) per-`[agent]`-command
606
+ // subprocess budget — replaces the runner's own prior hardcoded
607
+ // `AGENT_COMMAND_TIMEOUT_MS` constant (30 seconds, far too small for a real
608
+ // Test Plan command — a production build, a booted app, an end-to-end
609
+ // check) with adopter policy. Absent defaults to `900000` (15 minutes,
610
+ // `DEFAULT_COMMAND_TIMEOUT_MS` in `commands/pr-report.ts`). Capped by the
611
+ // `superRefine` below at `3600000` (1 hour) so a misconfigured value cannot
612
+ // leave `pr report` hanging on a stuck subprocess for arbitrarily long
613
+ // (a round-2 security ruling) — checked there, not inline on the
614
+ // field itself, so this field's own type stays exactly what it always was.
615
+ report: z
616
+ .object({
617
+ commandTimeoutMs: z.number().int().positive().optional()
618
+ })
619
+ .superRefine((report, ctx) => {
620
+ const commandTimeoutMs = report.commandTimeoutMs
621
+ if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
622
+ ctx.addIssue({
623
+ code: z.ZodIssueCode.custom,
624
+ path: ['commandTimeoutMs'],
625
+ message: 'must be at most 3600000 (1 hour)'
626
+ })
627
+ }
628
+ })
629
+ .optional(),
630
+ // Opt-in decision records. `path` is the folder, relative to the
631
+ // repository root, that holds them: `vinaya new adr <title>` writes the
632
+ // next numbered record there and indexes it, the folder joins the writing
633
+ // rules' `spec` scope, and the `decision-record-citation` rule — which runs
634
+ // only while this key is set — bans citing a record by number anywhere
635
+ // outside the folder. Absent, none of that happens. A path outside the
636
+ // repository, or inside the doctrine tree, is refused by the
637
+ // `superRefine` below, naming this key.
638
+ decisionRecords: z
639
+ .object({
640
+ path: RepoRelativePathSchema
641
+ })
642
+ .strict()
643
+ .optional()
644
+ }
645
+
646
+ /** The parsed value of Vinaya's own keys. */
647
+ export type VinayaSectionConfig = z.infer<z.ZodObject<typeof VINAYA_CONFIG_FRAGMENT>>
648
+
649
+ /**
650
+ * Why `decisionRecords.path` is refused, or `null` when it names a folder
651
+ * inside the repository and outside the doctrine tree. The doctrine tree is
652
+ * `proseGates.doctrineRoot`, or the doctrine map's tree `harness/processes/vinaya-strict` when that is unset: decision
653
+ * records are the repository's own, never part of the doctrine it ships.
654
+ */
655
+ export function decisionRecordsPathIssue(path: string, doctrineRoot: string | undefined): string | null {
656
+ const reason = outsideRepositoryReason(path)
657
+ if (reason) return reason
658
+ const folder = normalizeSpecPath(path)
659
+ if (folder === '' || folder === '.') return 'must name a folder, not the repository root'
660
+ const root = normalizeSpecPath(doctrineRoot ?? DOCTRINE_TREE)
661
+ if (folder === root || folder.startsWith(`${root}/`)) {
662
+ return `must be outside the doctrine tree "${root}" — decision records belong to this repository, not to the doctrine it ships`
663
+ }
664
+ return null
665
+ }
666
+
667
+ /**
668
+ * One rule spans two keys and so lives on the section rather than on a field:
669
+ * `decisionRecords.path` may not sit inside the doctrine tree
670
+ * `proseGates.doctrineRoot` names.
671
+ */
672
+ function decisionRecordsOutsideDoctrine(config: VinayaSectionConfig, ctx: z.RefinementCtx): void {
673
+ const path = config.decisionRecords?.path
674
+ // A path outside the repository is already refused by the field's own schema.
675
+ if (path === undefined || outsideRepositoryReason(path)) return
676
+ const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot)
677
+ if (issue) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['decisionRecords', 'path'], message: issue })
678
+ }
679
+
680
+ // ── Keys the machine-wide file may not set ──────────────────────────────────
681
+
682
+ /** Same reasoning as `globalChecksIgnoredWarning` — a trust decision must come from the reviewed, committed repo file, never a machine-wide personal config. */
683
+ export function globalPrincipalsIgnoredWarning(path: string): string {
684
+ return `${path}: "principals" in the global config is ignored — principals may only be declared from a repo-local vinaya.config.json.`
685
+ }
686
+
687
+ /** Same reasoning as `globalChecksIgnoredWarning` — a role contract is agent-facing doctrine, and which one a role name resolves to must come from the reviewed, committed repo file, never a machine-wide personal config. */
688
+ export function globalRolesIgnoredWarning(path: string): string {
689
+ return `${path}: "roles" registration in the global config is ignored — roles may only be registered from a repo-local vinaya.config.json.`
690
+ }
691
+
692
+ /** Same reasoning as `globalPrincipalsIgnoredWarning` — `releaseActor` gates a merge-authority exemption, same trust class as `principals`. */
693
+ export function globalReleaseActorIgnoredWarning(path: string): string {
694
+ return `${path}: "releaseActor" in the global config is ignored — releaseActor may only be declared from a repo-local vinaya.config.json.`
695
+ }
696
+
697
+ /** Same reasoning as `globalChecksIgnoredWarning` — `tokens.collect` decides what command runs on this turn, and that decision must come from the reviewed, committed repo file, never a machine-wide personal config. */
698
+ export function globalTokensCollectIgnoredWarning(path: string): string {
699
+ return `${path}: "tokens" in the global config is ignored — tokens.collect may only be declared from a repo-local vinaya.config.json.`
700
+ }
701
+
702
+ // ── Resolvers ───────────────────────────────────────────────────────────────
703
+
704
+ /**
705
+ * Resolves the expected author of this repo's Changesets release PR: the
706
+ * repo-local `releaseActor` when set, else `DEFAULT_RELEASE_ACTOR` (the
707
+ * stock `changesets/action` identity). Same sourcing rule as
708
+ * `resolveTrustedPrincipals` — callers MUST pass `loadTrustAnchorConfig()`,
709
+ * never `loadConfig()` or anything env/local-git-derived, since this gates
710
+ * the same class of merge-authority exemption `principals` gates.
711
+ */
712
+ export function resolveReleaseActor(config: VinayaSectionConfig | null): string {
713
+ return config?.releaseActor ?? DEFAULT_RELEASE_ACTOR
714
+ }
715
+
716
+ /**
717
+ * Resolves the effective review policy:
718
+ * `config?.reviewPolicy` when set, else `DEFAULT_REVIEW_POLICY`
719
+ * (`BLOCKER`/`HIGH` — today's behaviour, unchanged for a repo that never sets
720
+ * this key). Per-field: an omitted `codeReviewThreshold`/`securityThreshold`
721
+ * defaults; a PRESENT one that is not a real severity on its role's own scale
722
+ * REFUSES (throws), never falls back to the default — an unknown value is a
723
+ * config defect to fix, not a value to silently downgrade past. The two
724
+ * numeric fields (`maxRounds`, `maxTaskMinutes`, `readyPushTimeoutMinutes`)
725
+ * follow the identical rule, each with its own legal range — `maxTaskMinutes`
726
+ * accepts `0`, which turns the task's wall-clock budget off. Same sourcing
727
+ * rule as `resolveTrustedPrincipals`/`resolveReleaseActor`: callers MUST
728
+ * pass `loadTrustAnchorConfig()` (the default branch), never `loadConfig()`
729
+ * or anything PR-checkout-derived, so a change cannot lower its own
730
+ * threshold — the gate and the loop read the identical source.
731
+ */
732
+ export function resolveReviewPolicy(config: VinayaSectionConfig | null): ReviewPolicy {
733
+ const raw = config?.reviewPolicy
734
+ if (!raw) return DEFAULT_REVIEW_POLICY
735
+
736
+ const codeReviewThreshold = raw.codeReviewThreshold ?? DEFAULT_REVIEW_POLICY.codeReviewThreshold
737
+ if (!isKnownSeverity(CODE_REVIEW_SEVERITY_ORDER, codeReviewThreshold)) {
738
+ throw new Error(
739
+ `vinaya.config.json: reviewPolicy.codeReviewThreshold "${codeReviewThreshold}" is not one of ${CODE_REVIEW_SEVERITY_ORDER.join(' > ')} — fix the config, this never falls back to a default.`
740
+ )
741
+ }
742
+ const securityThreshold = raw.securityThreshold ?? DEFAULT_REVIEW_POLICY.securityThreshold
743
+ if (!isKnownSeverity(SECURITY_SEVERITY_ORDER, securityThreshold)) {
744
+ throw new Error(
745
+ `vinaya.config.json: reviewPolicy.securityThreshold "${securityThreshold}" is not one of ${SECURITY_SEVERITY_ORDER.join(' > ')} — fix the config, this never falls back to a default.`
746
+ )
747
+ }
748
+ // The dev-review-loop's own round
749
+ // cap, replacing `assess-round.ts`'s hardcoded constant. Same refuse-never-
750
+ // downgrade discipline as the two thresholds above: a present-but-invalid
751
+ // value (non-integer, zero, negative) is a config defect to fix.
752
+ const maxRounds = raw.maxRounds ?? DEFAULT_REVIEW_POLICY.maxRounds
753
+ if (!Number.isInteger(maxRounds) || maxRounds < 1) {
754
+ throw new Error(
755
+ `vinaya.config.json: reviewPolicy.maxRounds "${maxRounds}" is not a positive integer — fix the config, this never falls back to a default.`
756
+ )
757
+ }
758
+ // The task's own wall-clock budget, in minutes. Same refuse-never-downgrade
759
+ // discipline as the fields above, with one difference the round cap has no
760
+ // equivalent for: `0` is a LEGAL value that turns the budget off, so the
761
+ // floor here is zero rather than one. A negative or fractional value is
762
+ // still a config defect to fix, never a silent fallback.
763
+ const maxTaskMinutes = raw.maxTaskMinutes ?? DEFAULT_REVIEW_POLICY.maxTaskMinutes
764
+ if (!Number.isInteger(maxTaskMinutes) || maxTaskMinutes < 0) {
765
+ throw new Error(
766
+ `vinaya.config.json: reviewPolicy.maxTaskMinutes "${maxTaskMinutes}" is not a non-negative integer (0 turns the budget off) — fix the config, this never falls back to a default.`
767
+ )
768
+ }
769
+ // The version-2 ready push's test-run limit, in minutes. Same refuse-never-
770
+ // downgrade discipline; the floor is one, since a zero-minute limit would
771
+ // stop every run before it started.
772
+ const readyPushTimeoutMinutes = raw.readyPushTimeoutMinutes ?? DEFAULT_READY_PUSH_TIMEOUT_MINUTES
773
+ if (!Number.isInteger(readyPushTimeoutMinutes) || readyPushTimeoutMinutes < 1) {
774
+ throw new Error(
775
+ `vinaya.config.json: reviewPolicy.readyPushTimeoutMinutes "${readyPushTimeoutMinutes}" is not a positive integer — fix the config, this never falls back to a default.`
776
+ )
777
+ }
778
+ return {
779
+ codeReviewThreshold: codeReviewThreshold as ReviewPolicy['codeReviewThreshold'],
780
+ securityThreshold: securityThreshold as ReviewPolicy['securityThreshold'],
781
+ maxRounds,
782
+ maxTaskMinutes,
783
+ readyPushTimeoutMinutes
784
+ }
785
+ }
786
+
787
+ /** The one file name a local run may use to override pacing settings; gitignored, never committed. */
788
+ export const LOCAL_OVERRIDE_FILENAME = 'vinaya.config.local.json'
789
+
790
+ /** The only keys the local file may set. Anything else in it is ignored with a warning. */
791
+ export const LOCAL_OVERRIDABLE_KEYS = [
792
+ 'reviewPolicy.maxRounds',
793
+ 'reviewPolicy.maxTaskMinutes',
794
+ 'reviewPolicy.readyPushTimeoutMinutes'
795
+ ] as const
796
+
797
+ export type LocalPacingOverride = {
798
+ /** Absolute path of the local file that was read. */
799
+ path: string
800
+ maxRounds?: number
801
+ maxTaskMinutes?: number
802
+ readyPushTimeoutMinutes?: number
803
+ /** Dotted paths present in the file that are outside the allowlist. */
804
+ ignoredKeys: string[]
805
+ }
806
+
807
+ /**
808
+ * The one reader of `vinaya.config.local.json`. Returns the allowlisted pacing
809
+ * values a local run overrides, or `null` when no local file is honoured:
810
+ * a process with `VINAYA_ROLE` set, a CI job (`GITHUB_ACTIONS`), a cwd inside a
811
+ * linked task worktree, a repository with no primary working tree (bare or a
812
+ * separate git dir), a missing file, or a symlinked file. The file is looked up
813
+ * at the primary checkout's root (the dirname of `gitCommonDir`), never by
814
+ * walking up from the cwd. Values are validated with `resolveReviewPolicy`'s
815
+ * own rules and a bad value throws. Keys outside `LOCAL_OVERRIDABLE_KEYS` are
816
+ * ignored with one warning naming them.
817
+ */
818
+ export function resolveLocalPacingOverride(cwd: string = process.cwd()): LocalPacingOverride | null {
819
+ const file = readLocalOverrideFile(
820
+ {
821
+ fileName: LOCAL_OVERRIDE_FILENAME,
822
+ overridableKeys: LOCAL_OVERRIDABLE_KEYS,
823
+ suppressedBy: ['VINAYA_ROLE', 'GITHUB_ACTIONS']
824
+ },
825
+ cwd
826
+ )
827
+ if (!file) return null
828
+ const { path, raw, ignoredKeys } = file
829
+ const policy = (
830
+ raw as {
831
+ reviewPolicy?: { maxRounds?: unknown; maxTaskMinutes?: unknown; readyPushTimeoutMinutes?: unknown }
832
+ }
833
+ ).reviewPolicy
834
+ const result: LocalPacingOverride = { path, ignoredKeys }
835
+ if (policy && typeof policy === 'object' && !Array.isArray(policy)) {
836
+ if (policy.maxRounds !== undefined) {
837
+ const v = policy.maxRounds
838
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 1) {
839
+ throw new Error(
840
+ `${LOCAL_OVERRIDE_FILENAME}: reviewPolicy.maxRounds "${String(v)}" is not a positive integer — fix the file, this never falls back to a default.`
841
+ )
842
+ }
843
+ result.maxRounds = v
844
+ }
845
+ if (policy.maxTaskMinutes !== undefined) {
846
+ const v = policy.maxTaskMinutes
847
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 0) {
848
+ throw new Error(
849
+ `${LOCAL_OVERRIDE_FILENAME}: reviewPolicy.maxTaskMinutes "${String(v)}" is not a non-negative integer (0 turns the budget off) — fix the file, this never falls back to a default.`
850
+ )
851
+ }
852
+ result.maxTaskMinutes = v
853
+ }
854
+ if (policy.readyPushTimeoutMinutes !== undefined) {
855
+ const v = policy.readyPushTimeoutMinutes
856
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 1) {
857
+ throw new Error(
858
+ `${LOCAL_OVERRIDE_FILENAME}: reviewPolicy.readyPushTimeoutMinutes "${String(v)}" is not a positive integer — fix the file, this never falls back to a default.`
859
+ )
860
+ }
861
+ result.readyPushTimeoutMinutes = v
862
+ }
863
+ }
864
+ return result
865
+ }
866
+
867
+ /**
868
+ * The configured agent-configuration security scanner as an argv list, or
869
+ * `null` when unset. The review loop runs this
870
+ * before dispatching the security pass, on the head-verified candidate copy,
871
+ * appending the directory to scan as a final argument (`decideSecurityScan`).
872
+ *
873
+ * Same sourcing rule as `resolveReviewPolicy`/`resolveTrustedPrincipals`: an
874
+ * unattended caller MUST pass `loadTrustAnchorConfig()` (the default branch),
875
+ * never `loadConfig()` or anything PR-checkout-derived — the command names a
876
+ * subprocess that runs in the driver's own environment, so a pull request must
877
+ * not be able to redirect it in its own diff. Pure: takes the already-loaded
878
+ * config, no I/O of its own.
879
+ */
880
+ export function resolveSecurityScanCommand(config: VinayaSectionConfig | null): readonly string[] | null {
881
+ const command = config?.securityScan?.command
882
+ return command && command.length > 0 ? command : null
883
+ }
884
+
885
+ /**
886
+ * Resolves the five gate cutovers: each field of `config?.gateCutovers` when
887
+ * set, else `null`. **An absent key — or an absent field within it — resolves
888
+ * to `null`, which every pure gate reads as NO cutover: the gate applies to
889
+ * every Issue/PR, from number 1 (O1).** This is deliberately the OPPOSITE of
890
+ * `resolveReviewPolicy`'s "absent → the built-in default" — the built-in
891
+ * constants (`OBJECTIVES_SINCE_ISSUE` etc.) are NOT the fallback here; they
892
+ * survive only as each pure validator's own parameter default for a caller
893
+ * that does not resolve config. Every enforcement path calls this and passes
894
+ * the result, so a repository that declares no `gateCutovers` gets no cutover
895
+ * on any gate, while this monorepo restates its historical numbers in its own
896
+ * `vinaya.config.json` and is judged exactly as before (O2).
897
+ *
898
+ * Read from the working-tree config the caller hands in (`loadConfig`/
899
+ * `loadConfigChecked`), never the trust anchor: unlike `principals`/
900
+ * `reviewPolicy` this is not a merge-authority decision, it is the same
901
+ * reviewed-committed trust class the source constants already had, and the
902
+ * value must be present on the CURRENT branch for the migration to hold (the
903
+ * default branch does not carry the key until this change merges).
904
+ */
905
+ export function resolveGateCutovers(config: VinayaSectionConfig | null): GateCutovers {
906
+ const raw = config?.gateCutovers
907
+ if (!raw) return NO_GATE_CUTOVERS
908
+ return {
909
+ objectivesSinceIssue: raw.objectivesSinceIssue ?? null,
910
+ briefSectionsSinceIssue: raw.briefSectionsSinceIssue ?? null,
911
+ documentationSinceIssue: raw.documentationSinceIssue ?? null,
912
+ briefRulesSincePr: raw.briefRulesSincePr ?? null,
913
+ agentBoxesRefusedSincePr: raw.agentBoxesRefusedSincePr ?? null
914
+ }
915
+ }
916
+
917
+ /**
918
+ * The resolved `planning.collisionThreshold`: the declared value when set,
919
+ * else `DEFAULT_COLLISION_THRESHOLD`. Unlike `resolveGateCutovers`, an absent
920
+ * key here resolves to the built-in default rather than to "no rule" — a
921
+ * repository that has never heard of this key still wants a collision it
922
+ * cannot merge cheaply to be declared, whereas an absent cutover genuinely
923
+ * means "this repository has no history to grandfather". `0` is a real,
924
+ * honoured value (the refusal off), never conflated with absence.
925
+ */
926
+ export function resolveCollisionThreshold(config: VinayaSectionConfig | null): number {
927
+ return config?.planning?.collisionThreshold ?? DEFAULT_COLLISION_THRESHOLD
928
+ }
929
+
930
+ /**
931
+ * ⚠️ **Read this before changing anything about how `principals` is
932
+ * resolved.** Three consecutive attempts at this got it wrong, each fixing
933
+ * the previous one's lever while leaving the same class open (across
934
+ * several review rounds):
935
+ *
936
+ * 1. `loadConfig()` — read the PR's own working tree. A PR added its author
937
+ * to `principals` and self-approved.
938
+ * 2. `git show ${BASE_SHA}:...` — `BASE_SHA` was an env var, and a
939
+ * `pull_request`-triggered workflow runs the PR's OWN copy of the
940
+ * workflow YAML, so the PR set `BASE_SHA` to its own head SHA.
941
+ * 3. `git show origin/main:...` with a hardcoded ref — but `origin/main` is
942
+ * a LOCAL remote-tracking ref inside the job's own disk, and the PR's own
943
+ * workflow YAML can run `git update-ref refs/remotes/origin/main HEAD`
944
+ * before this check's step. Reproduced live; the doc comment claiming
945
+ * "only push access to `main` can move it" conflated that local ref with
946
+ * the real protected branch on GitHub.
947
+ *
948
+ * The lesson those three share: **inside a `pull_request`-triggered workflow,
949
+ * NOTHING reachable from the job's own filesystem or environment is a trust
950
+ * boundary against the PR author** — the workflow definition itself comes
951
+ * from the PR. So the config CONTENT is read from **GitHub's API**, which
952
+ * serves the repository's default-branch bytes from server-side state the PR
953
+ * cannot touch, rather than from local git or the working tree.
954
+ *
955
+ * **Precisely scoped claim, because the previous two rounds were undone by
956
+ * overclaiming:** the CONTENT is server-side; the repository IDENTITY used to
957
+ * address that API call still comes from `trustAnchorRepo()`, which reads
958
+ * `GITHUB_REPOSITORY` (set by the Actions runner) and falls back to the
959
+ * `origin` remote URL. Both are PR-influenceable in principle. That is
960
+ * deliberate and not a practical lever: where a PR controls the workflow YAML
961
+ * it already holds a strictly stronger primitive (delete the step entirely),
962
+ * and where the YAML is trusted the runner sets `GITHUB_REPOSITORY` correctly
963
+ * so the remote fallback is never reached. The precedence order is therefore
964
+ * load-bearing — runner value first, remote only as a local-dev fallback —
965
+ * and must not be reordered.
966
+ *
967
+ * **This raises the bar; it is not, by itself, the boundary.** A PR can still
968
+ * edit its own copy of the generated workflow to delete this step, `exit 0`,
969
+ * or otherwise not run the gate at all. **GitHub branch protection with this
970
+ * check marked as a required status check** is the necessary next step — it
971
+ * lives in repository settings, outside any PR's reach — but do not write that
972
+ * it makes review enforcement unbypassable, because it does not. A required
973
+ * status check is satisfied by a conclusion reported under its name; it does
974
+ * not certify that the conclusion came from running the real check. Deleting
975
+ * this *step* still leaves the *job* reporting green, and a step edited to
976
+ * `exit 0` reports success having run nothing — only removing the job or the
977
+ * workflow outright produces the never-reports case that blocks the merge.
978
+ * The trust boundary is who controls the workflow definition producing the
979
+ * required check, and under a `pull_request` trigger that is the PR author,
980
+ * whatever the check is packaged as; packaging decides only the blast radius
981
+ * (a repo vendoring this CLI also hands the PR the check sources, the build
982
+ * script, and the dependency lifecycle scripts the install step runs).
983
+ * `vinaya init` prints the branch-protection recommendation and `vinaya
984
+ * doctor` reports when it is missing; an adopter setting `principals` without
985
+ * branch protection has a useful convention, not a security control, and one
986
+ * setting it *with* branch protection has closed merge-without-a-report and
987
+ * nothing further — the reviewer closes the rest. The docs must never imply
988
+ * otherwise in either direction. See `harness/processes/vinaya-strict/doctrine/enforcement.md`'s ring-0
989
+ * "Spawning a check" row for the full statement.
990
+ */
991
+
992
+ /**
993
+ * Why `resolveTrustedPrincipals` found no Principal list: `not-configured` —
994
+ * no repository resolves for the read, the default branch has no
995
+ * `vinaya.config.json`, or the file sets no valid `principals` — or
996
+ * `read-failed` — the forge read itself failed (no `gh` authentication, an
997
+ * empty CI token, the network).
998
+ */
999
+ export type PrincipalsUnresolvedKind = 'not-configured' | 'read-failed'
1000
+
1001
+ /** The one error `resolveTrustedPrincipals` throws; `message` names the fix (`not-configured`) or the reason (`read-failed`). */
1002
+ export class PrincipalsUnresolvedError extends Error {
1003
+ readonly kind: PrincipalsUnresolvedKind
1004
+
1005
+ constructor(kind: PrincipalsUnresolvedKind, message: string) {
1006
+ super(message)
1007
+ this.name = 'PrincipalsUnresolvedError'
1008
+ this.kind = kind
1009
+ }
1010
+ }
1011
+
1012
+ /** The fix every `not-configured` refusal names. */
1013
+ export const PRINCIPALS_FIX = 'add "principals": [...] to vinaya.config.json on the default branch'
1014
+
1015
+ function principalsNotConfigured(why: string): PrincipalsUnresolvedError {
1016
+ return new PrincipalsUnresolvedError('not-configured', `no Principal is configured (${why}) — ${PRINCIPALS_FIX}.`)
1017
+ }
1018
+
1019
+ /** The trust-anchor reads `resolveTrustedPrincipals` makes, from the composed loader. */
1020
+ export type TrustedPrincipalsReads = {
1021
+ fetch: TrustAnchorFetcher
1022
+ parse(content: string, warn: (why: string) => void): { principals?: string[] } | null
1023
+ }
1024
+
1025
+ /**
1026
+ * The Principal list, read from `principals` in the default branch's
1027
+ * `vinaya.config.json` through the same forge read as `loadTrustAnchorConfig`
1028
+ * (see `TrustAnchorFetcher`'s doc comment for why it is never local git, the
1029
+ * working tree or an environment variable) — with no built-in fallback. Where
1030
+ * no list resolves, this throws `PrincipalsUnresolvedError`, so every check,
1031
+ * command and library path that decides who counts as a Principal refuses
1032
+ * rather than trusting someone the repository never named.
1033
+ *
1034
+ * It follows `loadTrustAnchorConfigOrThrow`'s distinction: a missing file
1035
+ * (`isMissingFileError`), no resolvable repository, a file with no
1036
+ * `principals` and a file that fails the configuration schema are
1037
+ * `not-configured`; any other fetch failure is `read-failed`. It never writes
1038
+ * a warning itself — a check turns the error into its own `CheckError` line
1039
+ * or failure result, a forge-write gate into its refusal, and a command or
1040
+ * library lets it propagate.
1041
+ *
1042
+ * `fetcher` is injectable for tests ONLY; production callers pass nothing.
1043
+ */
1044
+ export function createTrustedPrincipalsResolver(reads: TrustedPrincipalsReads) {
1045
+ return function resolveTrustedPrincipals(fetcher: TrustAnchorFetcher = reads.fetch): string[] {
1046
+ let content: string
1047
+ try {
1048
+ content = fetcher()
1049
+ } catch (err) {
1050
+ if ((err as Error)?.message === NO_TRUST_ANCHOR_REPO_MESSAGE) {
1051
+ throw principalsNotConfigured('no repository resolves for the read')
1052
+ }
1053
+ if (isMissingFileError(err)) throw principalsNotConfigured('the default branch has no vinaya.config.json')
1054
+ throw new PrincipalsUnresolvedError(
1055
+ 'read-failed',
1056
+ `could not read "principals" from vinaya.config.json on the default branch: ${fetchFailureReason(err)}`
1057
+ )
1058
+ }
1059
+ const unusable = { why: '' }
1060
+ const config = reads.parse(content, (why) => {
1061
+ unusable.why = why
1062
+ })
1063
+ if (config === null) {
1064
+ throw principalsNotConfigured(
1065
+ `vinaya.config.json on the default branch ${unusable.why ? `is unusable: ${unusable.why}` : 'is empty'}`
1066
+ )
1067
+ }
1068
+ if (!config.principals)
1069
+ throw principalsNotConfigured('vinaya.config.json on the default branch sets no "principals"')
1070
+ return config.principals
1071
+ }
1072
+ }
1073
+
1074
+ /** The line a swallowed trust-anchor read failure prints. */
1075
+ export function trustAnchorFallbackWarning(why: string): string {
1076
+ return `⚠ could not read the trust-anchor config (\`principals\`/\`releaseActor\`) from the default branch (${why}) — falling back to vinaya's built-in defaults.\n`
1077
+ }
1078
+
1079
+ // ---------------------------------------------------------------------------
1080
+ // tokens.collect trust cache (a security review).
1081
+ //
1082
+ // The problem the printed pre-exec warning did NOT solve: a
1083
+ // declared `tokens.collect` command executes IN-PROCESS, unsandboxed,
1084
+ // automatically, the first time anyone (human or unattended Developer/
1085
+ // Archivist agent) runs the ordinary `vinaya tokens` command against a repo
1086
+ // carrying it — with no barrier between "this value exists in a commit" and
1087
+ // "this value ran". A warning printed synchronously immediately before a
1088
+ // blocking `execFile` call gives a human no real window to react.
1089
+ //
1090
+ // Round 2's fix, direnv-shaped: a declaration must be explicitly TRUSTED
1091
+ // once, per exact declaration, per machine, before `vinaya tokens` will ever
1092
+ // execute it — `getTokensCollectTrust` returns nothing (never runs, never
1093
+ // falls back) until `trustTokensCollectCommand` records it. Approval is a
1094
+ // real human act (`vinaya tokens --trust-collect`, run once, not part of any
1095
+ // generated or automated flow) — this file contains no code path that
1096
+ // self-trusts.
1097
+ //
1098
+ // Round 2 shipped with a real gap round 3 closes: trust bound to the
1099
+ // command STRING alone, never to the CONTENT of the script it invoked —
1100
+ // approving `"node scripts/collect-usage.js"` once trusted whatever that
1101
+ // script currently contained, so a LATER commit editing only the script
1102
+ // (never this config) executed silently on the next run, no re-prompt.
1103
+ // Live-reproduced by security review. Closed by `tokens.collect`'s own
1104
+ // grammar narrowing (`parseTokensCollectDeclaration`, above) rather than by
1105
+ // this cache alone: because a declaration is EXACTLY one interpreter and
1106
+ // one script path, never an open shell string, there is exactly one file it
1107
+ // can ever mean — so trust can pin that file's content (`gitBlobHash`) and
1108
+ // stay rigorous rather than heuristically guessing which token of an
1109
+ // arbitrary command "looks like a path".
1110
+ //
1111
+ // Trust is keyed by (this repo's git common directory, interpreter, script
1112
+ // path) — NOT by worktree path. This repo's own Developer/Archivist
1113
+ // dispatch model creates a fresh worktree per task
1114
+ // (`.worktrees/task/<tranche>/<n>/`), and `git rev-parse --git-common-dir`
1115
+ // resolves to the ONE shared `.git` directory every worktree of a repo
1116
+ // points at — approving a declaration once on a machine covers every future
1117
+ // task worktree of that same repo (the script's bytes are identical there
1118
+ // too, for the same commit), while a genuinely new interpreter, script
1119
+ // path, OR script CONTENT always needs its own fresh approval. A repo the
1120
+ // trust identity cannot be resolved for (`gitCommonDir` returns `null` — no
1121
+ // git, or `git` itself unavailable) is refused, never silently trusted.
1122
+ //
1123
+ // Storage is machine-local (`~/.vinaya/`, the same home `VINAYA_HOME`
1124
+ // already uses for the global config) and deliberately NOT the repo-local
1125
+ // `vinaya.config.json` or anything else a commit can touch — trust is a
1126
+ // standing fact about what THIS operator has personally approved on THIS
1127
+ // machine, and a PR can no more grant itself that trust than it can add
1128
+ // itself to `principals`.
1129
+ // ---------------------------------------------------------------------------
1130
+
1131
+ const TOKENS_COLLECT_TRUST_PATH = join(VINAYA_HOME, 'tokens-collect-trust.json')
1132
+
1133
+ export type TokensCollectTrustEntry = {
1134
+ interpreter: string
1135
+ script: string
1136
+ /** `git hash-object` blob hash of `script`'s bytes at the moment trust was granted. */
1137
+ scriptBlobHash: string
1138
+ trustedAt: string
1139
+ }
1140
+ export type TokensCollectTrustStore = Record<string, TokensCollectTrustEntry>
1141
+
1142
+ function readTokensCollectTrustStore(storePath: string): TokensCollectTrustStore {
1143
+ try {
1144
+ if (!existsSync(storePath)) return {}
1145
+ const raw = JSON.parse(readFileSync(storePath, 'utf-8'))
1146
+ return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
1147
+ } catch {
1148
+ return {}
1149
+ }
1150
+ }
1151
+
1152
+ function writeTokensCollectTrustStore(storePath: string, store: TokensCollectTrustStore): void {
1153
+ const dir = dirname(storePath)
1154
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
1155
+ writeFileSync(storePath, JSON.stringify(store, null, 2), 'utf-8')
1156
+ }
1157
+
1158
+ /**
1159
+ * The `git hash-object` blob hash of a file's CURRENT on-disk bytes —
1160
+ * whatever is actually checked out right now, committed or not (so an
1161
+ * uncommitted local edit is caught exactly like a committed one). If this
1162
+ * content is ever committed unchanged, this is the identical hash that
1163
+ * commit's tree entry for this path carries — the trust cache pins the same
1164
+ * identifier a `git show`/`git cat-file` investigation would use, not a
1165
+ * bespoke one. `null` on any failure (file missing, `git` unavailable,
1166
+ * timeout) — never a license to trust anyway.
1167
+ */
1168
+ export function gitBlobHash(absolutePath: string, cwd: string): string | null {
1169
+ try {
1170
+ const raw = execFileSync('git', ['hash-object', absolutePath], {
1171
+ cwd,
1172
+ encoding: 'utf-8',
1173
+ stdio: ['ignore', 'pipe', 'pipe'],
1174
+ timeout: GIT_IDENTITY_TIMEOUT_MS
1175
+ }).trim()
1176
+ return raw || null
1177
+ } catch {
1178
+ return null
1179
+ }
1180
+ }
1181
+
1182
+ /**
1183
+ * The trust key for one (repo, interpreter, script path) triple — changing
1184
+ * any of the three changes the key, so a different repo, interpreter, or
1185
+ * script path is always a stranger. Script CONTENT is checked separately
1186
+ * (`TokensCollectTrustEntry.scriptBlobHash`, a value the caller compares
1187
+ * itself) rather than folded into this key, so "never approved" and
1188
+ * "approved, but the script's content has since changed" stay two
1189
+ * distinguishable refusals instead of one opaque "not trusted".
1190
+ *
1191
+ * Hashes `JSON.stringify([...])` — provably injective for any well-formed
1192
+ * strings (the surrounding `[`/`,`/`]` structure and per-string escaping can
1193
+ * never itself be produced by escaped content), so no two distinct triples
1194
+ * can ever collide, regardless of what characters any of the three fields
1195
+ * contain.
1196
+ */
1197
+ export function tokensCollectTrustKey(repoGitCommonDir: string, interpreter: string, script: string): string {
1198
+ return createHash('sha256')
1199
+ .update(JSON.stringify([repoGitCommonDir, interpreter, script]))
1200
+ .digest('hex')
1201
+ }
1202
+
1203
+ /**
1204
+ * The recorded trust entry for this exact (repo, interpreter, script path)
1205
+ * triple, or `null` if it has never been approved on this machine. Callers
1206
+ * compare `entry.scriptBlobHash` against the CURRENT content hash
1207
+ * themselves (`gitBlobHash`) — this function does not, precisely so "never
1208
+ * trusted" and "trusted, but content has since changed" stay distinguishable
1209
+ * refusals for the caller to report separately.
1210
+ */
1211
+ export function getTokensCollectTrust(
1212
+ repoGitCommonDir: string,
1213
+ interpreter: string,
1214
+ script: string,
1215
+ storePath: string = TOKENS_COLLECT_TRUST_PATH
1216
+ ): TokensCollectTrustEntry | null {
1217
+ const key = tokensCollectTrustKey(repoGitCommonDir, interpreter, script)
1218
+ return readTokensCollectTrustStore(storePath)[key] ?? null
1219
+ }
1220
+
1221
+ /** Records explicit, one-time approval of this exact (repo, interpreter, script path) triple AT this exact content hash — the only function in this file that grants trust, called from nowhere except the `--trust-collect` CLI path a human types themselves. */
1222
+ export function trustTokensCollectCommand(
1223
+ repoGitCommonDir: string,
1224
+ interpreter: string,
1225
+ script: string,
1226
+ scriptBlobHash: string,
1227
+ storePath: string = TOKENS_COLLECT_TRUST_PATH
1228
+ ): void {
1229
+ const store = readTokensCollectTrustStore(storePath)
1230
+ const key = tokensCollectTrustKey(repoGitCommonDir, interpreter, script)
1231
+ store[key] = { interpreter, script, scriptBlobHash, trustedAt: new Date().toISOString() }
1232
+ writeTokensCollectTrustStore(storePath, store)
1233
+ }
1234
+
1235
+ // ── The section ─────────────────────────────────────────────────────────────
1236
+
1237
+ /** Vinaya's keys stripped from the machine-wide file, each placed in the composed order by `compose.ts`. */
1238
+ export const VINAYA_GLOBAL_ONLY_KEYS = {
1239
+ roles: {
1240
+ key: 'roles',
1241
+ present: (config) => Boolean(config.roles && Object.keys(config.roles).length > 0),
1242
+ warning: globalRolesIgnoredWarning
1243
+ },
1244
+ principals: {
1245
+ key: 'principals',
1246
+ present: (config) => Boolean(config.principals && config.principals.length > 0),
1247
+ warning: globalPrincipalsIgnoredWarning
1248
+ },
1249
+ releaseActor: {
1250
+ key: 'releaseActor',
1251
+ present: (config) => Boolean(config.releaseActor),
1252
+ warning: globalReleaseActorIgnoredWarning
1253
+ },
1254
+ tokens: { key: 'tokens', present: (config) => Boolean(config.tokens), warning: globalTokensCollectIgnoredWarning }
1255
+ } satisfies Record<string, GlobalOnlyKey<VinayaSectionConfig>>
1256
+
1257
+ /** Vinaya's process configuration section. */
1258
+ export const VINAYA_CONFIG_SECTION = {
1259
+ keys: Object.keys(VINAYA_CONFIG_FRAGMENT) as (keyof typeof VINAYA_CONFIG_FRAGMENT)[],
1260
+ fragment: VINAYA_CONFIG_FRAGMENT,
1261
+ refinements: [decisionRecordsOutsideDoctrine],
1262
+ globalOnlyKeys: Object.values(VINAYA_GLOBAL_ONLY_KEYS),
1263
+ resolvers: {
1264
+ resolveReleaseActor,
1265
+ resolveReviewPolicy,
1266
+ resolveSecurityScanCommand,
1267
+ resolveGateCutovers,
1268
+ resolveCollisionThreshold,
1269
+ resolveLocalPacingOverride,
1270
+ decisionRecordsPathIssue,
1271
+ isDefaultedAgentVendorPath,
1272
+ parseTokensCollectDeclaration
1273
+ }
1274
+ } satisfies ProcessConfigSection<
1275
+ typeof VINAYA_CONFIG_FRAGMENT,
1276
+ KernelConfig & VinayaSectionConfig,
1277
+ Record<string, (...args: never[]) => unknown>
1278
+ >