rungate 0.2.0 → 0.3.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 (282) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/canary.ts +117 -0
  11. package/lib/check-registry.ts +226 -0
  12. package/lib/ci-checkout.ts +400 -0
  13. package/lib/cli-commands.ts +137 -0
  14. package/lib/compliance-backfill.ts +220 -0
  15. package/lib/compliance-report.ts +504 -0
  16. package/lib/compliance.ts +361 -0
  17. package/lib/config-loader.ts +255 -0
  18. package/lib/conformity.ts +1818 -131
  19. package/lib/container-provenance.ts +230 -0
  20. package/lib/create-brief.ts +150 -0
  21. package/lib/create-sc.ts +272 -0
  22. package/lib/deep-merge.ts +69 -0
  23. package/lib/dev-liveness.ts +214 -0
  24. package/lib/directive-extractor.ts +210 -0
  25. package/lib/distribution-standing.ts +113 -0
  26. package/lib/doc-hygiene.ts +238 -0
  27. package/lib/eval-criteria.ts +6 -0
  28. package/lib/evidence-portability.ts +123 -0
  29. package/lib/evidence-prevalidator.ts +390 -0
  30. package/lib/evidence-required.ts +150 -0
  31. package/lib/evidence-satisfiability.ts +288 -0
  32. package/lib/frontmatter.ts +163 -0
  33. package/lib/gap-scanner.ts +348 -0
  34. package/lib/gate-enforcement.ts +366 -0
  35. package/lib/generators/agent-briefs.ts +136 -0
  36. package/lib/generators/agents-md.ts +506 -0
  37. package/lib/generators/code-map.ts +60 -0
  38. package/lib/generators/types.ts +184 -0
  39. package/lib/git-ref-normalizer.ts +107 -0
  40. package/lib/github.ts +539 -0
  41. package/lib/harness-identity.ts +63 -0
  42. package/lib/hill-climb.ts +164 -0
  43. package/lib/instruction-effectiveness.ts +131 -0
  44. package/lib/issue-closure-audit.ts +225 -0
  45. package/lib/issue-create-override.ts +343 -0
  46. package/lib/js-top-level-code.ts +250 -0
  47. package/lib/liveness-contradiction.ts +149 -0
  48. package/lib/organize.ts +505 -0
  49. package/lib/paths.ts +197 -6
  50. package/lib/post-fix-verify.ts +157 -0
  51. package/lib/prior-branch.ts +489 -0
  52. package/lib/project-state-shape.ts +166 -0
  53. package/lib/promote-outputs.ts +156 -0
  54. package/lib/prove-label-gate.ts +35 -0
  55. package/lib/reachability.ts +302 -0
  56. package/lib/release-preflight.ts +186 -0
  57. package/lib/rule-health-pipeline.ts +264 -0
  58. package/lib/rule-health-trend.ts +161 -0
  59. package/lib/rule-provenance.ts +149 -0
  60. package/lib/rule-registry.ts +128 -0
  61. package/lib/rungate-schema.ts +114 -4
  62. package/lib/sc-claim-forms.ts +179 -0
  63. package/lib/sc-cover.ts +150 -0
  64. package/lib/sc-guard.ts +157 -0
  65. package/lib/sc-ids.ts +344 -0
  66. package/lib/scaffold/defaults.ts +165 -0
  67. package/lib/scaffold/managed-workflow.ts +370 -0
  68. package/lib/scaffold/owned-files.ts +265 -0
  69. package/lib/scaffold/steps.ts +2680 -0
  70. package/lib/scanner.ts +701 -0
  71. package/lib/screenshot-upload.ts +73 -0
  72. package/lib/secret-patterns.ts +112 -0
  73. package/lib/security-verdict.ts +616 -0
  74. package/lib/signal-phrases.ts +1 -0
  75. package/lib/spec-change-conformity.ts +80 -0
  76. package/lib/spec-files.ts +62 -0
  77. package/lib/spec-registry.ts +133 -0
  78. package/lib/spec-updater.ts +96 -0
  79. package/lib/stale-cleanup.ts +224 -0
  80. package/lib/stale-issue-scanner.ts +36 -0
  81. package/lib/strip-js-comments.ts +269 -0
  82. package/lib/suite-measurement.ts +228 -0
  83. package/lib/task-completion-checks.ts +177 -0
  84. package/lib/test-suite-lock.ts +1136 -0
  85. package/lib/transcript-checker.ts +1140 -0
  86. package/lib/validators/spec-validators.ts +171 -0
  87. package/lib/verdict-capture.ts +73 -0
  88. package/lib/verified-push.ts +358 -0
  89. package/lib/workflow-security.ts +174 -0
  90. package/lib/worktree-cleanup.ts +250 -0
  91. package/lib/worktree-collect.ts +283 -0
  92. package/lib/worktree-isolation.ts +82 -0
  93. package/package.json +36 -3
  94. package/prompts/ac-adversary.md +14 -2
  95. package/prompts/aditi.md +5 -0
  96. package/prompts/blast-radius.md +5 -0
  97. package/prompts/container-verify.md +5 -0
  98. package/prompts/discovery.md +4 -0
  99. package/prompts/environment.md +5 -0
  100. package/prompts/evidence-hierarchy.md +5 -0
  101. package/prompts/evidence-validator.md +11 -0
  102. package/prompts/marcus.md +5 -0
  103. package/prompts/prevention.md +5 -0
  104. package/prompts/prove-reproducer.md +12 -0
  105. package/prompts/quinn-decision-tree.md +5 -0
  106. package/prompts/quinn-ui-brief.md +5 -0
  107. package/prompts/quinn.md +5 -0
  108. package/prompts/rca.md +5 -0
  109. package/prompts/read-before-write.md +4 -0
  110. package/prompts/regression.md +5 -0
  111. package/prompts/serena.md +5 -0
  112. package/scripts/audit-specs.ts +464 -0
  113. package/scripts/convert-spec.ts +293 -0
  114. package/scripts/create-sc.ts +92 -0
  115. package/scripts/create-spec.ts +166 -0
  116. package/scripts/extract-constraints.ts +4 -3
  117. package/scripts/generate-code-map.ts +1 -1
  118. package/scripts/scaffold-project.ts +138 -1426
  119. package/scripts/sync-spec-tests.ts +211 -126
  120. package/.claude/agents/aditi.md +0 -47
  121. package/.claude/agents/marcus.md +0 -50
  122. package/.claude/agents/quinn.md +0 -58
  123. package/.claude/agents/rook.md +0 -47
  124. package/.claude/agents/serena.md +0 -46
  125. package/.claude/rungate.json +0 -11
  126. package/.fallowrc.json +0 -28
  127. package/.github/copilot-instructions.md +0 -20
  128. package/.rungate/conformity-findings.json +0 -648
  129. package/AGENTS.md +0 -106
  130. package/CODE-MAP.md +0 -50
  131. package/HARNESS.md +0 -88
  132. package/bun.lock +0 -26
  133. package/bunfig.toml +0 -2
  134. package/config/brief-policies.json +0 -28
  135. package/config/ceremony-profiles.json +0 -212
  136. package/config/consumer-cascade-map.json +0 -24
  137. package/config/doc-cascade-map.json +0 -24
  138. package/config/eval.json +0 -84
  139. package/config/profiles/account-plan.yaml +0 -36
  140. package/config/profiles/campaign.yaml +0 -94
  141. package/config/prove-evidence.schema.json +0 -65
  142. package/config/spec-policies.json +0 -36
  143. package/config/workflow-schema.json +0 -281
  144. package/gates/SCHEMA-GUIDE.md +0 -121
  145. package/gates/ac-quality.test.ts +0 -106
  146. package/gates/adversarial.test.ts +0 -274
  147. package/gates/brief-assembler.test.ts +0 -429
  148. package/gates/brief-assembler.ts +0 -334
  149. package/gates/bunfig.toml +0 -2
  150. package/gates/chain.test.ts +0 -91
  151. package/gates/e2e-smoke.test.ts +0 -234
  152. package/gates/error-classifier.test.ts +0 -249
  153. package/gates/error-classifier.ts +0 -89
  154. package/gates/orchestrator.test.ts +0 -950
  155. package/gates/orchestrator.ts +0 -569
  156. package/gates/preload.ts +0 -77
  157. package/gates/prompts/ac-adversary.md +0 -20
  158. package/gates/prompts/evidence-validator.md +0 -22
  159. package/gates/prompts/prove-reproducer.md +0 -53
  160. package/gates/prove.test.ts +0 -164
  161. package/gates/run-gate.ts +0 -936
  162. package/gates/schema-parity.test.ts +0 -197
  163. package/gates/schema.ts +0 -362
  164. package/gates/self-heal.test.ts +0 -511
  165. package/gates/self-heal.ts +0 -121
  166. package/gates/ship-orchestrator.test.ts +0 -379
  167. package/gates/ship-orchestrator.ts +0 -363
  168. package/gates/test-fixtures/broken-no-environments.json +0 -60
  169. package/gates/test-fixtures/valid-standard.json +0 -54
  170. package/gates/test-utils.ts +0 -43
  171. package/gates/witness.ts +0 -220
  172. package/gates/workflow.test.ts +0 -1053
  173. package/hooks/AgentBriefGuard.hook.ts +0 -586
  174. package/hooks/AgentVerdictCapture.hook.ts +0 -134
  175. package/hooks/AutoVerifyGate.hook.ts +0 -76
  176. package/hooks/GateEnforcement.hook.ts +0 -273
  177. package/hooks/IssueCloseGuard.hook.ts +0 -116
  178. package/hooks/MergeGuard.hook.ts +0 -55
  179. package/hooks/StaleTTLCleanup.hook.ts +0 -133
  180. package/hooks/VerifyPhaseLock.hook.ts +0 -81
  181. package/hooks/WorkflowStateGuard.hook.ts +0 -37
  182. package/hooks/lib/agentDetection.ts +0 -70
  183. package/hooks/lib/findWorkflow.ts +0 -101
  184. package/hooks/lib/parseStdin.ts +0 -37
  185. package/hooks/lib/paths.ts +0 -111
  186. package/hooks/lib/utils.ts +0 -81
  187. package/reference/migration-manifest.json +0 -554
  188. package/reference/prompts/agent-aditi.md +0 -38
  189. package/reference/prompts/agent-marcus.md +0 -38
  190. package/reference/prompts/agent-quinn.md +0 -38
  191. package/reference/prompts/agent-rook.md +0 -37
  192. package/reference/prompts/agent-serena.md +0 -37
  193. package/reference/prompts/council-skill.md +0 -170
  194. package/reference/prompts/goal-skill.md +0 -235
  195. package/reference/prompts/prove-skill.md +0 -283
  196. package/reference/prompts/quinn-standard.md +0 -246
  197. package/reference/prompts/ship-convergence.md +0 -65
  198. package/reference/prompts/ship-escalation.md +0 -43
  199. package/reference/prompts/ship-iteration.md +0 -382
  200. package/reference/prompts/ship-pending-patches.md +0 -246
  201. package/reference/prompts/ship-reference.md +0 -250
  202. package/reference/prompts/ship-skill.md +0 -347
  203. package/reference/prompts/ship-templates.md +0 -215
  204. package/reference/scripts/batch-status.sh +0 -68
  205. package/reference/scripts/chain-compat-check.sh +0 -67
  206. package/reference/scripts/context-audit.sh +0 -314
  207. package/reference/scripts/dead-export-check.sh +0 -61
  208. package/reference/scripts/generate-qc-tables.sh +0 -92
  209. package/reference/scripts/harness-init.sh +0 -111
  210. package/reference/scripts/pai-054-baseline-check.sh +0 -40
  211. package/reference/scripts/prove-smoke-test.sh +0 -112
  212. package/reference/scripts/setup-keychain-salt.sh +0 -12
  213. package/reference/scripts/skill-optimizer-friday.sh +0 -88
  214. package/reference/scripts/skill-qc-test.sh +0 -351
  215. package/reference/scripts/skill-synthesize-tonight.sh +0 -66
  216. package/reference/specs/HARNESS-EXTRACTION-SPEC.md +0 -263
  217. package/reference/specs/harness-v3-bash-deletion-plan.md +0 -65
  218. package/reference/specs/harness-v3-migration-plan.md +0 -188
  219. package/scripts/decision-reconcile.sh +0 -74
  220. package/scripts/decision-reconcile.ts +0 -152
  221. package/scripts/git-hooks/pre-commit +0 -76
  222. package/scripts/git-hooks/pre-push +0 -271
  223. package/scripts/harness-skill-check.sh +0 -52
  224. package/scripts/lib/gap-emit.sh +0 -65
  225. package/scripts/lib/jq-update.sh +0 -30
  226. package/scripts/lib/resolve-slug.sh +0 -30
  227. package/scripts/lib/verify-spec-compliance.sh +0 -102
  228. package/scripts/prove-backfill.sh +0 -87
  229. package/scripts/scaffold-rungate-config.ts +0 -91
  230. package/scripts/self-containment-check.sh +0 -109
  231. package/scripts/skill-qc-validator.sh +0 -402
  232. package/scripts/slug-resolver.sh +0 -14
  233. package/specs/BOOTSTRAP-DATA-FLOW-SPEC.md +0 -2493
  234. package/specs/BOOTSTRAP-TEST-PLAN.md +0 -571
  235. package/specs/HARNESS-GATES.md +0 -256
  236. package/specs/HARNESS-SKILL-CHAIN.md +0 -286
  237. package/specs/HARNESS-SKILL-CONTRACT.md +0 -93
  238. package/specs/HARNESS-STANDARD.md +0 -488
  239. package/specs/SPEC-TEMPLATE.md +0 -53
  240. package/specs/bootstrap-data-flow.png +0 -0
  241. package/specs/harness-automation-matrix.md +0 -314
  242. package/specs/harness-automation-matrix.rules.json +0 -64
  243. package/test/anti.test.ts +0 -80
  244. package/test/contract-negative.test.ts +0 -86
  245. package/test/contract.test.ts +0 -158
  246. package/test/external-deps.test.ts +0 -48
  247. package/test/fixtures/golden-project/.env.example +0 -3
  248. package/test/fixtures/golden-project/Makefile +0 -7
  249. package/test/fixtures/golden-project/docs/adr/ADR-001-framework.md +0 -23
  250. package/test/fixtures/golden-project/docs/setup-guide.md +0 -10
  251. package/test/fixtures/golden-project/package.json +0 -10
  252. package/test/fixtures/golden-project/specs/api-spec.md +0 -20
  253. package/test/fixtures/golden-project/src/auth.ts +0 -8
  254. package/test/fixtures/golden-project/src/db.ts +0 -11
  255. package/test/fixtures/golden-project/src/index.ts +0 -19
  256. package/test/fixtures/golden-project/src/utils/format.ts +0 -3
  257. package/test/fixtures/golden-project/test/auth.test.ts +0 -15
  258. package/test/fixtures/golden-project/tsconfig.json +0 -12
  259. package/test/meta-sc-coverage.test.ts +0 -159
  260. package/test/phase-0.test.ts +0 -846
  261. package/test/phase-1.test.ts +0 -617
  262. package/test/phase-2.test.ts +0 -620
  263. package/test/phase-3.test.ts +0 -99
  264. package/test/scaffold-conformity.test.ts +0 -8
  265. package/test/schema-canary.test.ts +0 -51
  266. package/test/spec-compliance-auto.test.ts +0 -64
  267. package/test/spec-compliance.test.ts +0 -295
  268. package/test/spec-discovery.test.ts +0 -68
  269. package/test/spec-drift.test.ts +0 -5
  270. package/test/structure.test.ts +0 -165
  271. package/test/unit/agent-brief-guard-ship.test.ts +0 -293
  272. package/test/unit/extract-constraints.test.ts +0 -145
  273. package/test/unit/issue-close-guard.test.ts +0 -204
  274. package/test/unit/scaffold-project.test.ts +0 -417
  275. package/test/unit/skill-cooccurrence.test.ts +0 -177
  276. package/test/unit/skill-sequence-logger.test.ts +0 -244
  277. package/test/unit/workflow-state-guard.test.ts +0 -95
  278. package/workflows/batch-ship.js +0 -295
  279. package/workflows/council.js +0 -481
  280. package/workflows/prove.js +0 -560
  281. package/workflows/ship.js +0 -789
  282. package/workflows/verify.js +0 -236
package/lib/github.ts ADDED
@@ -0,0 +1,539 @@
1
+ /**
2
+ * lib/github.ts — Shared Octokit-based GitHub client
3
+ *
4
+ * SC-489: exports [createGitHubClient, getIssue, addComment, addLabels]
5
+ * SC-490: exports [createPR, updatePR, listPRs, closeIssue]
6
+ * SC-491: contains [GITHUB_TOKEN, Octokit, issues.addLabels]
7
+ * SC-493: POST additive label strategy documented
8
+ *
9
+ * Design decisions (from GITHUB-API-MIGRATION-SPEC):
10
+ * - D-2: @octokit/rest as the TypeScript SDK
11
+ * - D-3: Auth via GITHUB_TOKEN environment variable
12
+ * - D-4: Single auth point, reusable across hooks/gates/lib, mockable for tests
13
+ * - D-5: POST /issues/{n}/labels for label append (additive by design, not PUT/replace)
14
+ * - D-7: MCP fallback to Octokit when MCP server not connected
15
+ *
16
+ * Label operations use POST (additive) — never PUT (replace-all).
17
+ * The POST endpoint appends labels without removing existing ones,
18
+ * eliminating the read-merge-write race condition that PUT would require.
19
+ */
20
+
21
+ import { Octokit } from "@octokit/rest";
22
+
23
+ // ── Types ──────────────────────────────────────────────────────────────────
24
+
25
+ export interface GitHubClient {
26
+ rest: {
27
+ issues: {
28
+ get: (params: { owner: string; repo: string; issue_number: number }) => Promise<{ data: any }>;
29
+ create: (params: { owner: string; repo: string; title: string; body?: string; labels?: string[] }) => Promise<{ data: any }>;
30
+ createComment: (params: { owner: string; repo: string; issue_number: number; body: string }) => Promise<{ data: any }>;
31
+ addLabels: (params: { owner: string; repo: string; issue_number: number; labels: string[] }) => Promise<{ data: any }>;
32
+ update: (params: { owner: string; repo: string; issue_number: number; state?: string; [key: string]: any }) => Promise<{ data: any }>;
33
+ };
34
+ pulls: {
35
+ create: (params: { owner: string; repo: string; title: string; head: string; base: string; body?: string; draft?: boolean }) => Promise<{ data: any }>;
36
+ get: (params: { owner: string; repo: string; pull_number: number }) => Promise<{ data: any }>;
37
+ update: (params: { owner: string; repo: string; pull_number: number; [key: string]: any }) => Promise<{ data: any }>;
38
+ list: (params: { owner: string; repo: string; [key: string]: any }) => Promise<{ data: any[] }>;
39
+ };
40
+ };
41
+ /**
42
+ * The GraphQL endpoint, for the handful of operations REST does not expose.
43
+ *
44
+ * `markPullRequestReadyForReview` is the only one today (#252): PATCH
45
+ * /pulls/{n} silently ignores a `draft` field, so a run that tried to
46
+ * undraft over REST would report success and leave the PR a draft.
47
+ */
48
+ graphql: (query: string, variables?: Record<string, unknown>) => Promise<any>;
49
+ }
50
+
51
+ export interface CreatePROptions {
52
+ title: string;
53
+ head: string;
54
+ base: string;
55
+ body?: string;
56
+ /**
57
+ * Open the PR as a draft (#252).
58
+ *
59
+ * ship.js opens its PR before the ship gate, the blocking-grade check and
60
+ * two staleness refusals, so all of those can fail with a reviewable PR
61
+ * already on the branch. Run `wf_e105dd33-220` did exactly that: it returned
62
+ * SHIP_FAILED and left #250 open and `mergeable: MERGEABLE`, carrying code
63
+ * that destroyed a consumer's CI. Defaults false, because a human opening a
64
+ * PR means it.
65
+ */
66
+ draft?: boolean;
67
+ }
68
+
69
+ export interface UpdatePROptions {
70
+ title?: string;
71
+ body?: string;
72
+ state?: string;
73
+ }
74
+
75
+ export interface ListPRsOptions {
76
+ state?: "open" | "closed" | "all";
77
+ head?: string;
78
+ base?: string;
79
+ sort?: string;
80
+ direction?: "asc" | "desc";
81
+ per_page?: number;
82
+ }
83
+
84
+ // ── Client factory ─────────────────────────────────────────────────────────
85
+
86
+ /**
87
+ * Create a GitHub client authenticated via GITHUB_TOKEN env var.
88
+ * Client is created once per call — callers should cache the instance
89
+ * (D-4: single auth point, created once per process).
90
+ */
91
+ export function createGitHubClient(): GitHubClient {
92
+ const token = resolveGitHubToken();
93
+ if (!token) {
94
+ throw new Error(
95
+ "GITHUB_TOKEN environment variable is not set — required for GitHub API access " +
96
+ "(GH_TOKEN is also accepted)",
97
+ );
98
+ }
99
+ const baseUrl = resolveApiBaseUrl();
100
+ return new Octokit(baseUrl ? { auth: token, baseUrl } : { auth: token }) as unknown as GitHubClient;
101
+ }
102
+
103
+ /**
104
+ * The API base from `GITHUB_API_URL` (D-8), or undefined for Octokit's default.
105
+ *
106
+ * `GITHUB_API_URL` is the conventional companion to the token variables — gh
107
+ * CLI and GitHub Actions both set it — and honouring it makes GitHub
108
+ * Enterprise usable and lets tests point the client somewhere harmless
109
+ * instead of at the real API.
110
+ *
111
+ * **Allowlisted hosts only: GitHub itself, or loopback.** This variable
112
+ * redirects an endpoint that carries a bearer token, so it is an
113
+ * exfiltration primitive for anyone who can set it. An earlier version
114
+ * allowed any `https` host, reasoning that whoever controls the environment
115
+ * can usually read the token anyway. Security review flagged it twice and
116
+ * was right the second time: "usually" is not "always".
117
+ *
118
+ * The allowlist is not loopback-only, though, and CI is what taught me that:
119
+ * **GitHub Actions sets `GITHUB_API_URL=https://api.github.com` on every
120
+ * run.** A loopback-only rule therefore refused the genuine GitHub API and
121
+ * broke the whole suite in CI while passing locally, where the variable is
122
+ * unset. The differential was the fix's bug, not the test's.
123
+ *
124
+ * So the token can reach GitHub, or a port on this machine, and nowhere else.
125
+ * Hostname is compared exactly, so `api.github.com.evil.com` and a loopback
126
+ * name hidden in the userinfo (`https://127.0.0.1@evil.com`) are both
127
+ * refused. GitHub Enterprise needs a host outside this list and stays a
128
+ * separate, deliberate decision rather than a side effect of a test seam.
129
+ */
130
+ const ALLOWED_API_HOSTS = new Set([
131
+ "api.github.com",
132
+ "github.com",
133
+ "localhost",
134
+ "127.0.0.1",
135
+ "[::1]",
136
+ "::1",
137
+ ]);
138
+
139
+ export function resolveApiBaseUrl(): string | undefined {
140
+ const raw = process.env.GITHUB_API_URL?.trim();
141
+ if (!raw) return undefined;
142
+ let url: URL;
143
+ try {
144
+ url = new URL(raw);
145
+ } catch {
146
+ throw new Error(`GITHUB_API_URL is not a valid URL: ${raw}`);
147
+ }
148
+ if (!ALLOWED_API_HOSTS.has(url.hostname)) {
149
+ throw new Error(
150
+ `GITHUB_API_URL may only point at GitHub or loopback — refusing to send a token to ${url.hostname}`,
151
+ );
152
+ }
153
+ return raw;
154
+ }
155
+
156
+ /**
157
+ * The GitHub credential, under either of the two conventional names.
158
+ *
159
+ * #139: this read `GITHUB_TOKEN` alone, and nothing sets it. `gh auth status`
160
+ * on Jason's machine reports the account is authenticated via `GH_TOKEN`, so
161
+ * every Octokit call in the repo threw at construction — the prove gate said
162
+ * so loudly, `gates/orchestrator.ts` dropped the `shipped` label into a
163
+ * `.catch(() => {})`, and `hooks/IssueCloseGuard.hook.ts` stopped guarding
164
+ * (#140).
165
+ *
166
+ * D-3 of GITHUB-API-MIGRATION-SPEC chose the single name on the grounds that
167
+ * it was "already set by `gh` CLI auth". It is not: `gh` reads `GH_TOKEN` and
168
+ * exports nothing. Accepting both is what makes D-7's "Octokit always works"
169
+ * true in an environment authenticated the ordinary way.
170
+ *
171
+ * `GITHUB_TOKEN` wins when both are present, so a deliberately scoped token
172
+ * can override a broader ambient one. Empty strings count as absent — an
173
+ * exported-but-unset variable must produce the clear error here rather than
174
+ * an unauthenticated client that 401s somewhere less obvious.
175
+ */
176
+ export function resolveGitHubToken(): string | undefined {
177
+ for (const name of ["GITHUB_TOKEN", "GH_TOKEN"]) {
178
+ const v = process.env[name];
179
+ // Trimmed, not just tested: `GH_TOKEN=$(cat token)` carries a trailing
180
+ // newline, and Octokit sends it in the Authorization header, where it
181
+ // 401s with nothing pointing at the whitespace as the cause.
182
+ if (v && v.trim()) return v.trim();
183
+ }
184
+ return undefined;
185
+ }
186
+
187
+ // ── Helpers ────────────────────────────────────────────────────────────────
188
+
189
+ /**
190
+ * Parse "owner/repo" into { owner, repo }, rejecting anything that is not one.
191
+ *
192
+ * The shape check alone was not enough, and the measurement is unambiguous.
193
+ * Octokit interpolates these into the request path, and the URL layer
194
+ * resolves `..` segments before the request goes out:
195
+ *
196
+ * --repo "owner/.." -> GET /repos/issues/7
197
+ * --repo "../x" -> GET /x/issues/7 <- out of /repos entirely
198
+ *
199
+ * The second one is arbitrary API-path construction with whatever verb the
200
+ * caller's operation uses. Query strings and fragments were already safe —
201
+ * `owner/na?x=1` arrives percent-encoded — so traversal is the whole of it.
202
+ *
203
+ * It mattered more once #137 made a repo slug a command-line argument, but it
204
+ * was always reachable: `gates/orchestrator.ts` and `lib/branch-cleanup.ts`
205
+ * pass slugs through here too. GitHub owner and repository names are
206
+ * `[A-Za-z0-9._-]` only, so requiring exactly that rejects nothing real.
207
+ */
208
+ const REPO_SEGMENT = /^[A-Za-z0-9._-]+$/;
209
+
210
+ export function parseOwnerRepo(repoSlug: string): { owner: string; repo: string } {
211
+ const parts = repoSlug.split("/");
212
+ if (parts.length !== 2) {
213
+ throw new Error(`Invalid repo format: "${repoSlug}" — expected "owner/repo"`);
214
+ }
215
+ for (const part of parts) {
216
+ if (!REPO_SEGMENT.test(part) || part === "." || part === "..") {
217
+ throw new Error(
218
+ `Invalid repo format: "${repoSlug}" — "${part}" is not a GitHub owner or repository name`,
219
+ );
220
+ }
221
+ }
222
+ return { owner: parts[0], repo: parts[1] };
223
+ }
224
+
225
+ // ── Issue operations ───────────────────────────────────────────────────────
226
+
227
+ /**
228
+ * Get issue details by number.
229
+ */
230
+ export async function getIssue(client: GitHubClient, repoSlug: string, issueNumber: number): Promise<any> {
231
+ const { owner, repo } = parseOwnerRepo(repoSlug);
232
+ const response = await client.rest.issues.get({
233
+ owner,
234
+ repo,
235
+ issue_number: issueNumber,
236
+ });
237
+ return response.data;
238
+ }
239
+
240
+ /**
241
+ * An issue's label names (#395).
242
+ *
243
+ * Exists because `gates/workflow.test.ts` read labels by shelling out to the
244
+ * GitHub CLI — a synchronous exec of `issue view --json labels`, with the
245
+ * issue number and repo slug interpolated into the command string.
246
+ *
247
+ * That call is NOT reproduced here, and the omission is deliberate rather
248
+ * than stylistic. `test/ticked-sc-cover.test.ts` scans `lib/`, `hooks/` and
249
+ * `gates/` for exactly that spelling, and a docblock quoting it verbatim
250
+ * would be a violation sitting inside the module written to remove one.
251
+ * Today the scan's pattern happens not to match across a ` * ` comment
252
+ * prefix, which is luck and not design — the same kind of luck that let the
253
+ * original survive. Describe it; do not spell it.
254
+ *
255
+ * Two things were wrong with it beyond the architecture GITHUB-API-
256
+ * MIGRATION-SPEC.md lays down. It needed `gh` installed and authenticated in
257
+ * whatever environment the gate ran in — often CI or a worktree. And it
258
+ * interpolated two values out of workflow state into a SHELL STRING; this
259
+ * takes arguments, and Octokit puts them in a URL path and a query, so there
260
+ * is no command line for them to be part of.
261
+ *
262
+ * Worth recording how it survived: SC-502 forbids exactly this and was
263
+ * ticked over it for the criterion's whole life, because the call puts
264
+ * `execSync(` on one line and the command on the next and every grep for it
265
+ * was line-oriented. A text search cannot see across a line break, which is
266
+ * the "detector narrower than what it detects" shape in
267
+ * `.claude/rules/checks-must-be-able-to-fail.md`.
268
+ *
269
+ * The shape is defensive because the API's is: `labels` is a list whose
270
+ * entries are either a string or an object carrying `name`.
271
+ */
272
+ export async function getIssueLabels(
273
+ client: GitHubClient,
274
+ repoSlug: string,
275
+ issueNumber: number,
276
+ ): Promise<string[]> {
277
+ const issue = await getIssue(client, repoSlug, issueNumber);
278
+ const raw = Array.isArray(issue?.labels) ? issue.labels : [];
279
+ return raw
280
+ .map((l: unknown) => (typeof l === "string" ? l : (l as { name?: unknown })?.name))
281
+ .filter((n: unknown): n is string => typeof n === "string" && n.length > 0);
282
+ }
283
+
284
+ /**
285
+ * Add a comment to an issue.
286
+ */
287
+ export async function addComment(client: GitHubClient, repoSlug: string, issueNumber: number, body: string): Promise<any> {
288
+ const { owner, repo } = parseOwnerRepo(repoSlug);
289
+ const response = await client.rest.issues.createComment({
290
+ owner,
291
+ repo,
292
+ issue_number: issueNumber,
293
+ body,
294
+ });
295
+ return response.data;
296
+ }
297
+
298
+ /**
299
+ * Add labels to an issue using POST (additive, not replace).
300
+ *
301
+ * Uses issues.addLabels which maps to POST /repos/{owner}/{repo}/issues/{issue_number}/labels.
302
+ * POST is additive by design — it appends labels without removing existing ones.
303
+ * This eliminates the read-merge-write race condition that PUT would require.
304
+ *
305
+ * D-5: POST /issues/{n}/labels for label append (not PUT)
306
+ */
307
+ export async function addLabels(client: GitHubClient, repoSlug: string, issueNumber: number, labels: string[]): Promise<any> {
308
+ const { owner, repo } = parseOwnerRepo(repoSlug);
309
+ const response = await client.rest.issues.addLabels({
310
+ owner,
311
+ repo,
312
+ issue_number: issueNumber,
313
+ labels,
314
+ });
315
+ return response.data;
316
+ }
317
+
318
+ /**
319
+ * Create a new issue.
320
+ *
321
+ * Used by ship.js when Discovery rescopes a large issue into phases: phase 1
322
+ * stays on the parent, the rest become sub-issues.
323
+ */
324
+ export async function createIssue(
325
+ client: GitHubClient,
326
+ repoSlug: string,
327
+ opts: { title: string; body?: string; labels?: string[] },
328
+ ): Promise<any> {
329
+ const { owner, repo } = parseOwnerRepo(repoSlug);
330
+ const response = await client.rest.issues.create({
331
+ owner,
332
+ repo,
333
+ title: opts.title,
334
+ ...(opts.body !== undefined ? { body: opts.body } : {}),
335
+ ...(opts.labels?.length ? { labels: opts.labels } : {}),
336
+ });
337
+ return response.data;
338
+ }
339
+
340
+ /**
341
+ * Update an issue's body and/or state.
342
+ *
343
+ * Labels are deliberately NOT part of this call. `PATCH /issues/{n}` with a
344
+ * `labels` array REPLACES the whole set, which is the read-merge-write race
345
+ * D-5 exists to avoid. Callers that want to add a label use `addLabels`.
346
+ */
347
+ export async function updateIssue(
348
+ client: GitHubClient,
349
+ repoSlug: string,
350
+ issueNumber: number,
351
+ opts: { body?: string; title?: string; state?: "open" | "closed" },
352
+ ): Promise<any> {
353
+ const { owner, repo } = parseOwnerRepo(repoSlug);
354
+ const response = await client.rest.issues.update({
355
+ owner,
356
+ repo,
357
+ issue_number: issueNumber,
358
+ ...opts,
359
+ });
360
+ return response.data;
361
+ }
362
+
363
+ /**
364
+ * Close an issue by setting state to "closed".
365
+ */
366
+ export async function closeIssue(client: GitHubClient, repoSlug: string, issueNumber: number): Promise<any> {
367
+ const { owner, repo } = parseOwnerRepo(repoSlug);
368
+ const response = await client.rest.issues.update({
369
+ owner,
370
+ repo,
371
+ issue_number: issueNumber,
372
+ state: "closed",
373
+ });
374
+ return response.data;
375
+ }
376
+
377
+ // ── Pull request operations ────────────────────────────────────────────────
378
+
379
+ /**
380
+ * Create a new pull request.
381
+ */
382
+ export async function createPR(client: GitHubClient, repoSlug: string, opts: CreatePROptions): Promise<any> {
383
+ const { owner, repo } = parseOwnerRepo(repoSlug);
384
+ const response = await client.rest.pulls.create({
385
+ owner,
386
+ repo,
387
+ title: opts.title,
388
+ head: opts.head,
389
+ base: opts.base,
390
+ body: opts.body,
391
+ draft: opts.draft === true,
392
+ });
393
+ return response.data;
394
+ }
395
+
396
+ /**
397
+ * Take a draft PR out of draft (#252).
398
+ *
399
+ * Separate from `updatePR` because the REST PATCH endpoint does not flip
400
+ * `draft` — it is a GraphQL mutation — and a caller that set `draft: false`
401
+ * through `updatePR` would get a silent no-op, which is the fail-open shape
402
+ * this whole area keeps producing. Throwing on an unavailable client is
403
+ * deliberate: a run that cannot mark its PR ready must say so, not ship a
404
+ * draft nobody notices is a draft.
405
+ */
406
+ export async function markPRReady(
407
+ client: GitHubClient,
408
+ repoSlug: string,
409
+ prNumber: number,
410
+ ): Promise<{ number: number; isDraft: boolean }> {
411
+ const { owner, repo } = parseOwnerRepo(repoSlug);
412
+ const pr = await client.rest.pulls.get({ owner, repo, pull_number: prNumber });
413
+ const nodeId = pr.data.node_id;
414
+ if (!nodeId) {
415
+ throw new Error(`markPRReady: PR #${prNumber} has no node_id, so it cannot be marked ready`);
416
+ }
417
+ await client.graphql(
418
+ `mutation($id: ID!) { markPullRequestReadyForReview(input: {pullRequestId: $id}) { clientMutationId } }`,
419
+ { id: nodeId },
420
+ );
421
+ return { number: prNumber, isDraft: false };
422
+ }
423
+
424
+ /**
425
+ * Update an existing pull request.
426
+ */
427
+ export async function updatePR(client: GitHubClient, repoSlug: string, prNumber: number, opts: UpdatePROptions): Promise<any> {
428
+ const { owner, repo } = parseOwnerRepo(repoSlug);
429
+ const response = await client.rest.pulls.update({
430
+ owner,
431
+ repo,
432
+ pull_number: prNumber,
433
+ ...opts,
434
+ });
435
+ return response.data;
436
+ }
437
+
438
+ /**
439
+ * Create the PR for `head`, or update the one that already exists.
440
+ *
441
+ * A ship run can reach this step more than once — a gate heals and re-runs,
442
+ * or a regression sends it back through implement — so "create" alone fails
443
+ * the second time with a 422 the caller has no way to distinguish from a real
444
+ * error. Upsert is the operation the workflow actually wants.
445
+ *
446
+ * The lookup filters server-side on `owner:branch`, the form the REST API
447
+ * documents for the `head` parameter. Listing every open PR and filtering here
448
+ * would silently miss a match once the repo has more than one page of them.
449
+ */
450
+ export async function upsertPR(
451
+ client: GitHubClient,
452
+ repoSlug: string,
453
+ opts: CreatePROptions,
454
+ ): Promise<{ number: number; html_url: string; action: "created" | "updated"; draft: boolean }> {
455
+ const { owner } = parseOwnerRepo(repoSlug);
456
+ const existing = await listPRs(client, repoSlug, {
457
+ state: "open",
458
+ head: `${owner}:${opts.head}`,
459
+ });
460
+ if (existing.length > 0) {
461
+ const pr = existing[0];
462
+ const updated = await updatePR(client, repoSlug, pr.number, {
463
+ title: opts.title,
464
+ ...(opts.body !== undefined ? { body: opts.body } : {}),
465
+ });
466
+ // An existing PR IS dragged back into draft when the caller asks for one,
467
+ // and the first version of this got that wrong (#252, found by security
468
+ // review before merge). The comment it carried — "a PR a human already
469
+ // marked ready is theirs" — does not survive contact with how this harness
470
+ // runs: a re-ship pushes new commits to the SAME branch, so run A undrafts
471
+ // #N, run B updates it and then refuses, and #N is mergeable carrying
472
+ // run B's unproven code. Whatever the human approved is not what is on the
473
+ // branch any more, which is exactly why their ready-mark cannot stand.
474
+ //
475
+ // Protecting the first run on a branch and nothing after it is no
476
+ // protection at all here: #155, #164, #169 and #171 all exist because this
477
+ // workflow re-enters its own phases.
478
+ const draft = opts.draft === true
479
+ ? await convertPRToDraft(client, repoSlug, pr.number, pr)
480
+ : pr.draft === true;
481
+ return { number: pr.number, html_url: updated.html_url ?? pr.html_url, action: "updated", draft };
482
+ }
483
+ const created = await createPR(client, repoSlug, opts);
484
+ // Reported from the response rather than echoed from the request: the caller
485
+ // records this as the state of the artefact, and a field it asked for is not
486
+ // a field it observed.
487
+ return {
488
+ number: created.number,
489
+ html_url: created.html_url,
490
+ action: "created",
491
+ draft: created.draft === true,
492
+ };
493
+ }
494
+
495
+ /**
496
+ * Put a PR back into draft, and report what it is now (#252).
497
+ *
498
+ * Already-draft is a no-op rather than a redundant mutation — a re-ship hits
499
+ * this on every round, and a convert that fired unconditionally would be
500
+ * indistinguishable in a test from one that fired for the right reason.
501
+ *
502
+ * Throws when the PR has no node id, because the mutation is keyed on it and
503
+ * returning `true` with nothing sent would be the fail-open this whole area
504
+ * keeps producing: a refusal artefact claiming the PR is unmergeable while it
505
+ * sits there mergeable.
506
+ */
507
+ async function convertPRToDraft(
508
+ client: GitHubClient,
509
+ repoSlug: string,
510
+ prNumber: number,
511
+ pr: { node_id?: string; draft?: boolean },
512
+ ): Promise<boolean> {
513
+ if (pr.draft === true) return true;
514
+ const nodeId = pr.node_id;
515
+ if (!nodeId) {
516
+ throw new Error(
517
+ `upsertPR: PR #${prNumber} has no node_id, so it cannot be converted to a draft — ` +
518
+ "refusing rather than reporting a draft that was never made",
519
+ );
520
+ }
521
+ await client.graphql(
522
+ `mutation($id: ID!) { convertPullRequestToDraft(input: {pullRequestId: $id}) { clientMutationId } }`,
523
+ { id: nodeId },
524
+ );
525
+ return true;
526
+ }
527
+
528
+ /**
529
+ * List pull requests with optional filters.
530
+ */
531
+ export async function listPRs(client: GitHubClient, repoSlug: string, opts?: ListPRsOptions): Promise<any[]> {
532
+ const { owner, repo } = parseOwnerRepo(repoSlug);
533
+ const response = await client.rest.pulls.list({
534
+ owner,
535
+ repo,
536
+ ...opts,
537
+ });
538
+ return response.data;
539
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Is this project the harness itself?
3
+ *
4
+ * One question, one answer, one place (#380). It was answered in four places
5
+ * with four inline implementations, and they had drifted:
6
+ *
7
+ * | site | unreadable package.json |
8
+ * |---|---|
9
+ * | `isHarnessItself` in `lib/generators/agents-md.ts` | caught — reads as a consumer |
10
+ * | `generateAgentBriefsStep`'s `isSelf` | **threw**, killing the scaffold run |
11
+ * | `lib/scanner.ts` | caught |
12
+ * | `lib/conformity.ts` PKG-3 | caught |
13
+ *
14
+ * Three of four agreed, and nothing could notice the fourth because there
15
+ * was nothing to compare it against. #208 added the fourth copy while its
16
+ * own commit message argued — about a different function — that two deciders
17
+ * of the same fact survive any mutation of either.
18
+ *
19
+ * ## Why a leaf module rather than the owner it already had
20
+ *
21
+ * `lib/generators/agents-md.ts` declared it first and SC-811 names it there,
22
+ * so that is where it should live. It cannot: `lib/scanner.ts` is forbidden
23
+ * by SC-365 / AC-3 from importing any generator, and that constraint is
24
+ * right — the scanner is the module other scripts pull in precisely because
25
+ * it drags nothing behind it.
26
+ *
27
+ * So the predicate moves down to a leaf that imports nothing but `fs` and
28
+ * `path`, and `agents-md.ts` re-exports it. A re-export is one binding under
29
+ * two names, which is the opposite of two deciders: mutate this and both
30
+ * callers change.
31
+ *
32
+ * ## The direction this is allowed to be wrong in
33
+ *
34
+ * Toward "consumer". A consumer form run inside the harness is visibly wrong
35
+ * on its first command — `bunx rungate` resolves to the published package
36
+ * rather than the working tree. The source form in a consumer resolves to
37
+ * nothing at all, silently, in a project whose maintainer has no reason to
38
+ * suspect the harness guessed.
39
+ */
40
+ import { readFileSync } from "fs";
41
+ import { join } from "path";
42
+
43
+ /** The harness's own package name. The one fact this module knows. */
44
+ export const HARNESS_PACKAGE = "rungate";
45
+
46
+ export function isHarnessItself(root: string): boolean {
47
+ try {
48
+ return JSON.parse(readFileSync(join(root, "package.json"), "utf-8"))?.name === HARNESS_PACKAGE;
49
+ } catch {
50
+ // Missing, or unreadable. A consumer, as far as this is concerned.
51
+ //
52
+ // This `catch` is the drift the issue is about: one of the four copies
53
+ // did not have it, so a half-written package.json aborted the scaffold
54
+ // there and was a shrug everywhere else.
55
+ //
56
+ // There is no `existsSync` guard in front of it on purpose. The first
57
+ // draft had one and it scored 0 on mutation — removing it changed no
58
+ // answer, because a missing file throws into this same `catch`. A
59
+ // branch that cannot change an answer reads to the next person as if it
60
+ // can, so it is gone rather than commented.
61
+ return false;
62
+ }
63
+ }