rungate 0.8.13 → 0.8.16

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 (88) hide show
  1. package/README.md +182 -0
  2. package/gates/.gate-salt +1 -1
  3. package/hooks/HarnessAFKGate.hook.ts +5 -1
  4. package/hooks/HookCurrency.hook.ts +11 -8
  5. package/hooks/MergeGuard.hook.ts +7 -1
  6. package/hooks/StaleTTLCleanup.hook.ts +4 -4
  7. package/hooks/VerifyPhaseLock.hook.ts +3 -3
  8. package/hooks/lib/findWorkflow.ts +3 -2
  9. package/hooks/lib/paths.ts +14 -2
  10. package/hooks/lib/utils.ts +23 -3
  11. package/lib/active-milestone.ts +50 -0
  12. package/lib/ai-review-rounds.ts +99 -0
  13. package/lib/ai-review-suppression.ts +200 -21
  14. package/lib/bash-write-guard.ts +397 -23
  15. package/lib/board-flow.ts +280 -0
  16. package/lib/board-lane-health.ts +578 -0
  17. package/lib/board-mirror.ts +136 -39
  18. package/lib/board-ready-fanout.ts +297 -14
  19. package/lib/board-ready-rule.ts +1211 -0
  20. package/lib/board-throughput.ts +136 -0
  21. package/lib/board-walkthrough.ts +240 -0
  22. package/lib/body-evidence.ts +203 -0
  23. package/lib/branch-protection.ts +399 -9
  24. package/lib/bun-version.ts +36 -0
  25. package/lib/cli-commands.ts +75 -4
  26. package/lib/closing-reference-audit.ts +307 -6
  27. package/lib/config-loader.ts +254 -25
  28. package/lib/config-readers.ts +170 -10
  29. package/lib/config-trackable.ts +96 -57
  30. package/lib/conformity.ts +121 -7
  31. package/lib/create-sc.ts +25 -2
  32. package/lib/derived-spec.ts +21 -9
  33. package/lib/filing-compliance.ts +367 -0
  34. package/lib/filing-plan.ts +47 -21
  35. package/lib/finding-arbiter.ts +79 -5
  36. package/lib/finding-jury.ts +43 -4
  37. package/lib/finding-promotion.ts +1123 -0
  38. package/lib/generators/agents-md.ts +149 -0
  39. package/lib/git-isolation.ts +137 -1
  40. package/lib/github-api-base.ts +66 -0
  41. package/lib/github.ts +194 -9
  42. package/lib/graphql-cursor.ts +80 -0
  43. package/lib/hook-scopes.ts +78 -0
  44. package/lib/issue-create-override.ts +415 -3
  45. package/lib/issue-decomposition.ts +124 -7
  46. package/lib/issue-extraction.ts +9 -7
  47. package/lib/issue-file-overlap.ts +373 -0
  48. package/lib/issue-filing-gate.ts +1109 -52
  49. package/lib/issue-repair.ts +90 -9
  50. package/lib/issue-shape.ts +199 -0
  51. package/lib/live-issues.ts +31 -2
  52. package/lib/local-work.ts +423 -0
  53. package/lib/markdown-fence.ts +134 -0
  54. package/lib/milestone-title.ts +46 -0
  55. package/lib/scaffold/ai-review-findings.ts +148 -3
  56. package/lib/scaffold/ai-review-step.ts +65 -5
  57. package/lib/scaffold/ai-review-unmeasured-workflow.ts +3 -0
  58. package/lib/scaffold/steps.ts +115 -9
  59. package/lib/source-census.ts +108 -0
  60. package/lib/spec-deps.ts +55 -11
  61. package/lib/spec-placement.ts +203 -13
  62. package/lib/spec-registry.ts +75 -16
  63. package/lib/spec-source.ts +609 -0
  64. package/lib/spec-write-sweep.ts +4 -0
  65. package/lib/stage-ladder.ts +896 -3
  66. package/lib/state-claim-readings.ts +252 -0
  67. package/lib/success-doc.ts +7 -6
  68. package/lib/test-command-positions.ts +135 -1
  69. package/lib/work-status.ts +551 -0
  70. package/lib/worktree-repo.ts +14 -2
  71. package/package.json +7 -1
  72. package/scripts/ai-review-findings.ts +8 -13
  73. package/scripts/ai-review-threads.ts +16 -17
  74. package/scripts/audit-closing-references.ts +330 -0
  75. package/scripts/audit-specs.ts +59 -103
  76. package/scripts/board-conformance.ts +747 -40
  77. package/scripts/board-mirror.ts +594 -13
  78. package/scripts/board-ready.ts +979 -0
  79. package/scripts/board-snapshot.ts +464 -12
  80. package/scripts/claim-files.ts +578 -0
  81. package/scripts/criterion-inventory.ts +526 -50
  82. package/scripts/finding-promotion.ts +547 -0
  83. package/scripts/generate-code-map.ts +1 -1
  84. package/scripts/plan-issues.ts +279 -40
  85. package/scripts/plan-spec.ts +105 -3
  86. package/scripts/sync-sc-status.ts +147 -7
  87. package/scripts/worktree-census.ts +958 -0
  88. package/scripts/worktree-sweep.ts +269 -0
@@ -696,5 +696,154 @@ Check the claim against the repo before you build on it.
696
696
  `,
697
697
  });
698
698
 
699
+ // #1742 — a consumer that cannot report what it found upstream has not
700
+ // been supported, it has been shipped to. Measured 2026-11-03: the
701
+ // `from-consumer` label did not exist among 23 labels, no milestone was a
702
+ // triage lane among 18, and there was no rule. Consumers reached for
703
+ // `external-audit` — the label Jason's decision (c) ruled out — and
704
+ // fifteen open issues carry it.
705
+ //
706
+ // **Inline here, like every other rule, and NOT in a module of its own.**
707
+ // #1742's file list predicted `lib/scaffold/reporting-upstream.ts`; that
708
+ // shape was built and withdrawn, because `test/harness-fixed-point.test.ts`
709
+ // copies this generator into an `mkdtemp` tree and the new import died
710
+ // there with `Cannot find module`. That is Tier 1 of
711
+ // `.claude/rules/self-referential-tests.md` exactly — and a battery whose
712
+ // mutant fails to load goes GREEN while witnessing nothing, so the cheap
713
+ // fix of teaching the copier one more path buys a second thing to keep in
714
+ // step. Every other rule in this file is inline; so is this one.
715
+ //
716
+ // **Path-scoped to `package.json`, and the scope is forced twice over.**
717
+ // `scripts/check-instruction-surface.ts` read 258 bytes of headroom under
718
+ // the 64,000-byte budget, so an unscoped rule reddens
719
+ // `.claude/agents/aditi.md` — a file with nothing to do with reporting
720
+ // upstream. A scoped rule is billed against every file its globs match,
721
+ // and `harness-managed.md` already claims `AGENTS.md`, both workflows,
722
+ // `.claude/agents/**`, `.claude/rules/**`, `CODE-MAP.md` and
723
+ // `test/scaffold-conformity.test.ts` — a second rule on any of those sums
724
+ // with it and goes over. The harness config directory was the first
725
+ // choice and CONFIG-1 refuses it: a config path spelled in a string is a
726
+ // direct access site, which is the same trap `STEPS_NOT_MINIMAL` in
727
+ // `lib/scaffold/profiles.ts` describes in its own comment.
728
+ //
729
+ // `package.json` is what is left, and the first version of this comment
730
+ // justified it with "it holds the `rungate` dependency entry, which is the
731
+ // version this rule tells the reporter to quote." **That was false**, and
732
+ // the AI review of #1813 said so: this repository's own `package.json` is
733
+ // `"name": "rungate"` with a top-level `version`, no such entry — and a
734
+ // workspace-linked consumer's entry is a path, not a version.
735
+ //
736
+ // The scope stands on the honest reading instead. `package.json` is the
737
+ // file that answers *what is rungate to this project* — a dependency, a
738
+ // link, or the project itself — and that is precisely the question an
739
+ // agent is holding when it needs this rule. The rule now enumerates all
740
+ // three and says UNMEASURED when none resolves.
741
+ //
742
+ // **No `isHarnessItself` branch**, which is where the review's own fix
743
+ // pointed. It catches rungate's own repo and NOT the workspace-linked
744
+ // consumer the review named in the same paragraph, so it closes one of
745
+ // the two cases and reads as if it closed both — the shape #1810 spent
746
+ // three rounds on, each repair loosening the branch the next one arrived
747
+ // through. Prose covering every case has no branch to drift, and
748
+ // `test/gen-agents-md.test.ts` asserts the harness and a consumer get
749
+ // byte-identical content so none can be added without being noticed.
750
+ //
751
+ // Emitted into EVERY profile, including minimal. `RULES_NOT_MINIMAL`
752
+ // excludes a rule naming machinery the profile did not install, and this
753
+ // one names a tracker that exists either way — a minimal consumer is if
754
+ // anything the likeliest to hit something and have nowhere to put it.
755
+ rules.push({
756
+ filename: "reporting-upstream.md",
757
+ content: `---
758
+ description: How to report a problem you found in rungate itself, from this repository
759
+ paths:
760
+ - "package.json"
761
+ ---
762
+
763
+ ## You found something in rungate, not in this project
764
+
765
+ File it on **hornjason/rungate**, not here, and not as a code comment that
766
+ nobody upstream reads.
767
+
768
+ \`\`\`bash
769
+ gh issue create --repo hornjason/rungate \\
770
+ --label from-consumer \\
771
+ --title "<the symptom, not the fix>" \\
772
+ --body-file <a file you wrote FIRST, in a separate command>
773
+ \`\`\`
774
+
775
+ ## Show the body to your user before you send it
776
+
777
+ **hornjason/rungate is somebody else's repository, and its issues are
778
+ public.** Filing there publishes whatever you wrote, permanently — a
779
+ deletion later does not un-cache or un-index it. So the body is not yours to
780
+ send on your own judgement: write the file, show it to your user, and send
781
+ it only once they have said yes.
782
+
783
+ What goes in it is the **smallest thing that reproduces the problem**, and
784
+ nothing else:
785
+
786
+ - a reproducer you constructed, never a paste of this project's source,
787
+ config, logs, stack traces, test output or data
788
+ - paths only where the path IS the symptom — and say so
789
+ - no credentials, tokens, keys, internal hostnames, URLs or customer data,
790
+ including inside a quoted error message
791
+
792
+ If you cannot describe the problem without one of those, that is the thing
793
+ to tell your user. It is not a reason to send it anyway.
794
+
795
+ ## The label is \`from-consumer\`, and it is not \`external-audit\`
796
+
797
+ \`external-audit\` means *rungate audited something else*. A consumer report
798
+ is the opposite direction, and conflating them is how a report from a real
799
+ user lands in a queue nobody triages as user feedback.
800
+
801
+ If \`from-consumer\` does not exist on the repository, say so in the body
802
+ rather than substituting the nearest label. A label chosen because it was
803
+ available is a routing decision nobody made.
804
+
805
+ ## What the body must carry
806
+
807
+ The three sections every issue there needs. No criterion id — you cannot
808
+ know one from here and you are not expected to:
809
+
810
+ - **What must become true** — the symptom, with the numbers you measured
811
+ - **Files this will change** — if you know; *unknown* is an honest answer
812
+ - **How we will know** — what you would run to see it fixed
813
+
814
+ **Say which version of rungate you are on, and how you know.** A report
815
+ against a version nobody can identify cannot be reproduced, and will be
816
+ closed as such.
817
+
818
+ Where that number lives depends on how rungate reached this project, and
819
+ there is no one key to read:
820
+
821
+ - a declared dependency — the \`rungate\` entry under \`dependencies\` or
822
+ \`devDependencies\` in \`package.json\`
823
+ - a workspace or \`link:\` resolution — the entry is a path, not a version,
824
+ so read \`version\` out of the resolved package's own \`package.json\`
825
+ - **this project IS rungate** — then nothing below applies. There is no
826
+ upstream to report to: what you found is an ordinary issue on this
827
+ repository, and the version is the top-level \`version\` field.
828
+
829
+ If none of those resolves, write **UNMEASURED** and say which you tried.
830
+ Guessing a version is worse than not supplying one — it sends the
831
+ maintainers to the wrong tree.
832
+
833
+ ## Do not open a pull request first
834
+
835
+ File the issue, link it, and wait for a reply. A pull request from a
836
+ consumer against a harness they do not own is expensive to review and
837
+ frequently solves the wrong half of the problem — the maintainers may
838
+ already know the cause.
839
+
840
+ ## What belongs here instead
841
+
842
+ A problem in **this** project's own code, config or specs is an ordinary
843
+ issue on this repository. The test is simple: if deleting rungate would
844
+ make the problem go away it is upstream, and if it would not it is yours.
845
+ `,
846
+ });
847
+
699
848
  return rules;
700
849
  }
@@ -92,6 +92,135 @@ export const GIT_ISOLATION_CONFIG: ReadonlyArray<readonly [string, string]> = Ob
92
92
  ["safe.directory", "*"],
93
93
  ] as const);
94
94
 
95
+ /**
96
+ * Ambient variables that must be **removed**, as against the three above
97
+ * which are **set**.
98
+ *
99
+ * Two families, one property: each lets whoever populated the environment
100
+ * redirect or reconfigure a git call that named neither, and nothing
101
+ * downstream can tell — the reading comes back clean, confident, and about
102
+ * another tree or another config.
103
+ *
104
+ * - **Location.** `GIT_DIR` and friends outrank `-C <root>`'s discovery, so
105
+ * a reader pointed at one checkout reports on a different one.
106
+ * - **`GIT_CONFIG*`,** matched as a PREFIX because the injection form is
107
+ * open-ended: `GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=core.fsmonitor
108
+ * GIT_CONFIG_VALUE_0=<command>` is config at command scope, and `KEY_<n>`
109
+ * has no last element to enumerate. `GIT_CONFIG_GLOBAL` and
110
+ * `GIT_CONFIG_SYSTEM` are in the family too: pointed at a file the
111
+ * caller wrote, they are the same attack spelled as a path.
112
+ *
113
+ * **The `-c` flags are not a substitute, and the prefix is not redundant
114
+ * with them.** Measured on git 2.50.1: `-c core.fsmonitor=` DOES beat
115
+ * `GIT_CONFIG_KEY_0=core.fsmonitor`, so command-scope flags win where they
116
+ * overlap — but {@link GIT_ISOLATION_CONFIG} names four keys, and the
117
+ * injection can name any key git has. Neither covers the other, which is
118
+ * the same conclusion the env-vars-AND-`-c` section above reaches from the
119
+ * other direction. Review of #1896 round 9.
120
+ */
121
+ export const GIT_LOCATION_VARS = [
122
+ "GIT_DIR",
123
+ "GIT_WORK_TREE",
124
+ "GIT_INDEX_FILE",
125
+ "GIT_CEILING_DIRECTORIES",
126
+ "GIT_OBJECT_DIRECTORY",
127
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
128
+ "GIT_COMMON_DIR",
129
+ ] as const;
130
+
131
+ /** The prefix form, so `KEY_0`…`KEY_<n>` needs no enumeration. */
132
+ export const GIT_AMBIENT_CONFIG_PREFIX = "GIT_CONFIG";
133
+
134
+ /**
135
+ * **The decider: every ambient `GIT_*` is removed.** The named lists in
136
+ * this file document WHY; they do not decide.
137
+ *
138
+ * Three review rounds added names to a list — locations, then the config
139
+ * prefix, then the exec vars — and each round found the previous list
140
+ * short. That is not bad luck about one entry. A denylist over a namespace
141
+ * its owner keeps extending is short by construction, and the fourth patch
142
+ * would have been as temporary as the third. So the population is the
143
+ * namespace, and a `GIT_` variable git adds next year is excluded without
144
+ * an edit here.
145
+ *
146
+ * The allowlist is EMPTY on purpose. Everything this file needs set — the
147
+ * three in {@link GIT_ISOLATION_ENV}, and a caller's
148
+ * `GIT_TERMINAL_PROMPT` — is applied AFTER the sweep by whoever wants it,
149
+ * so nothing has to survive it.
150
+ *
151
+ * **Scope is `GIT_` only, and `SSH_` is deliberately NOT swept.**
152
+ * `SSH_AUTH_SOCK` is an agent socket rather than a command, and removing
153
+ * it breaks fetching over SSH for every consumer using an agent — a cost
154
+ * with no matching gain. `SSH_ASKPASS` is a command, so it is named in
155
+ * {@link GIT_EXEC_VARS} and removed individually. Review of #1896 round 11.
156
+ */
157
+ export const GIT_AMBIENT_NAMESPACE = "GIT_";
158
+
159
+ /** Names allowed to survive the sweep. Empty, and see the note above. */
160
+ export const GIT_AMBIENT_ALLOWED: ReadonlySet<string> = new Set<string>();
161
+
162
+ /**
163
+ * Variables whose VALUE git executes as a command.
164
+ *
165
+ * These are here for consistency, and the argument is short: stripping
166
+ * `GIT_CONFIG_*` already removes an injected `core.sshCommand`, `core.pager`
167
+ * and `core.fsmonitor`. Anyone able to set `GIT_CONFIG_KEY_0` can set
168
+ * `GIT_SSH_COMMAND`, so closing the config spelling of a route and leaving
169
+ * the direct spelling open buys nothing — it only makes the registry look
170
+ * complete. Review of #1896 round 10.
171
+ *
172
+ * **`GIT_SSH_COMMAND` has a real cost and it is accepted deliberately.** A
173
+ * deploy-key setup that passes `ssh -i <key>` through the environment
174
+ * rather than through `core.sshCommand` will fail to authenticate. In
175
+ * `lib/spec-source.ts` — this registry's only remote-reaching consumer — a
176
+ * failed fetch is recorded as `staleness` and the reading continues, so the
177
+ * cost is a reported stale ref rather than a refusal or a wrong answer.
178
+ * That is the direction this module is required to be wrong in.
179
+ *
180
+ * `GIT_EXTERNAL_DIFF` is listed despite being unreachable from the one call
181
+ * that could run it: measured on git 2.50.1, `diff --quiet` short-circuits
182
+ * before the external driver while a plain `diff` does invoke it (the
183
+ * control). A registry that only covers today's call sites is the narrower
184
+ * kind of denylist this whole round was about.
185
+ */
186
+ export const GIT_EXEC_VARS = [
187
+ "GIT_SSH",
188
+ "GIT_SSH_COMMAND",
189
+ "GIT_ASKPASS",
190
+ "SSH_ASKPASS",
191
+ "GIT_PROXY_COMMAND",
192
+ "GIT_EXTERNAL_DIFF",
193
+ "GIT_TEXTCONV_CACHE",
194
+ "GIT_PAGER",
195
+ "GIT_EDITOR",
196
+ "GIT_SEQUENCE_EDITOR",
197
+ ] as const;
198
+
199
+ /**
200
+ * `base` with both families removed, and NOTHING set.
201
+ *
202
+ * Separate from {@link gitIsolatedEnv} because the two halves have
203
+ * different costs. Removing an ambient override can only restore git's
204
+ * own defaults, so it is safe for a command that reaches a remote;
205
+ * *setting* `GIT_CONFIG_GLOBAL=/dev/null` discards `credential.helper`
206
+ * with everything else, which is why `gitCredentialEnv` exists. A caller
207
+ * that must fetch wants this one alone.
208
+ */
209
+ export function withoutAmbientGitOverrides(
210
+ base: NodeJS.ProcessEnv = process.env,
211
+ ): NodeJS.ProcessEnv {
212
+ const env: NodeJS.ProcessEnv = { ...base };
213
+ for (const name of Object.keys(env)) {
214
+ if (name.startsWith(GIT_AMBIENT_NAMESPACE) && !GIT_AMBIENT_ALLOWED.has(name)) delete env[name];
215
+ }
216
+ // The one command-bearing name outside the namespace. Everything else
217
+ // under `SSH_` is left alone — see {@link GIT_AMBIENT_NAMESPACE}.
218
+ for (const name of GIT_EXEC_VARS) {
219
+ if (!name.startsWith(GIT_AMBIENT_NAMESPACE)) delete env[name];
220
+ }
221
+ return env;
222
+ }
223
+
95
224
  /**
96
225
  * The shell-prefix projection: `VAR=… VAR=… git -c k=v …`, ready to be
97
226
  * interpolated in front of a subcommand in a generated script.
@@ -132,11 +261,18 @@ export function gitIsolatedArgs(args: readonly string[] = []): string[] {
132
261
  *
133
262
  * Takes the base environment as a parameter rather than reading
134
263
  * `process.env`, so a case can drive it without touching the machine's.
264
+ *
265
+ * The strip happens HERE rather than being left to the caller to compose,
266
+ * because the two steps are order-sensitive and only one order is safe:
267
+ * stripping `GIT_CONFIG*` after setting it removes the isolation this
268
+ * function exists to apply, and the result looks exactly like the
269
+ * isolated case. Both halves are individually correct and the series is
270
+ * not, so there is no composition for a caller to get wrong.
135
271
  */
136
272
  export function gitIsolatedEnv(
137
273
  base: NodeJS.ProcessEnv = process.env,
138
274
  ): NodeJS.ProcessEnv {
139
- return { ...base, ...GIT_ISOLATION_ENV };
275
+ return { ...withoutAmbientGitOverrides(base), ...GIT_ISOLATION_ENV };
140
276
  }
141
277
 
142
278
  /**
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Where GitHub is, and the one knob that moves it — #1935.
3
+ *
4
+ * `scripts/board-ready.ts` hard-coded `https://api.github.com` at both of its
5
+ * fetch sites, which is what made the script undriveable by a test: nothing
6
+ * executed its `main()` past the argument and credential guards, so every
7
+ * decision it makes was verified by reading its source text.
8
+ *
9
+ * **Loopback only, and a refusal rather than a fallback.** This variable
10
+ * redirects requests that carry a ProjectsV2 PAT. An override naming any
11
+ * other host would send that credential to it, so a value this cannot prove
12
+ * is loopback stops the run before the token is used. Falling back to the
13
+ * live API instead would be the same request with the operator's intent
14
+ * discarded — Silent Default Substitution
15
+ * (`.claude/rules/config-access.md`) in the direction that leaks.
16
+ *
17
+ * It lives here rather than in the script because the script ends in
18
+ * `process.exit(await main())` and cannot be imported: a predicate nothing
19
+ * can call is a predicate nothing can enumerate the population of.
20
+ */
21
+ export const API_BASE_ENV = "RUNGATE_GITHUB_API_BASE";
22
+
23
+ export const LIVE_API_BASE = "https://api.github.com";
24
+
25
+ /**
26
+ * The hosts an override may name. Closed, and spelled as a list rather than
27
+ * a pattern: `127.0.0.1.evil.test` and `localhost.evil.test` both satisfy
28
+ * every "starts with" and "contains" spelling of this check.
29
+ *
30
+ * **`[::1]` bracketed, and no bare `::1`.** Review round 1 of #1982 caught
31
+ * the unbracketed form sitting here unreachable: WHATWG parsing requires an
32
+ * IPv6 literal to be bracketed, so `new URL("http://::1")` THROWS and
33
+ * `u.hostname` never produces the bare string. An entry nothing can match is
34
+ * a host form a reader believes is handled. `BR-79` asserts both readings so
35
+ * it cannot come back silently.
36
+ */
37
+ const LOOPBACK_HOSTS: readonly string[] = ["127.0.0.1", "localhost", "[::1]"];
38
+
39
+ export type ApiBaseReading =
40
+ | { readonly base: string; readonly why: null }
41
+ | { readonly base: null; readonly why: string };
42
+
43
+ /** `{ base }`, or `{ why }` naming what was refused. Never a quiet default. */
44
+ export function resolveApiBase(raw: string | undefined): ApiBaseReading {
45
+ const v = (raw ?? "").trim();
46
+ if (v === "") return { base: LIVE_API_BASE, why: null };
47
+ let u: URL;
48
+ try {
49
+ u = new URL(v);
50
+ } catch {
51
+ return { base: null, why: `${API_BASE_ENV} is set to "${v}", which is not a URL` };
52
+ }
53
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
54
+ return { base: null, why: `${API_BASE_ENV} is set to "${v}", whose scheme is not http or https` };
55
+ }
56
+ if (!LOOPBACK_HOSTS.includes(u.hostname)) {
57
+ return {
58
+ base: null,
59
+ why:
60
+ `${API_BASE_ENV} is set to "${v}", whose host ${u.hostname} is not loopback. This run ` +
61
+ `holds a board-writing credential and will not send it anywhere else. Nothing was read.`,
62
+ };
63
+ }
64
+ // No trailing slash, so every caller composes paths the same way.
65
+ return { base: `${u.origin}${u.pathname.replace(/\/+$/, "")}`, why: null };
66
+ }
package/lib/github.ts CHANGED
@@ -46,6 +46,12 @@ export interface GitHubClient {
46
46
  * `listMilestones` below passes `all` and does not expose the choice.
47
47
  */
48
48
  listMilestones: (params: { owner: string; repo: string; state?: string; per_page?: number }) => Promise<{ data: any[] }>;
49
+ /**
50
+ * One issue's comments. Paginated by the caller — `listIssueComments`
51
+ * below walks every page, because a single page silently truncates and
52
+ * a short list reads as a smaller answer rather than a wrong one.
53
+ */
54
+ listComments: (params: { owner: string; repo: string; issue_number: number; per_page?: number; page?: number }) => Promise<{ data: any[] }>;
49
55
  createMilestone: (params: { owner: string; repo: string; title: string; description?: string }) => Promise<{ data: any }>;
50
56
  updateMilestone: (params: { owner: string; repo: string; milestone_number: number; title?: string; description?: string }) => Promise<{ data: any }>;
51
57
  };
@@ -623,6 +629,79 @@ export async function listOpenIssues(
623
629
  return { considered: rows.length, perPage, truncated: rows.length >= perPage, droppedRows, issues };
624
630
  }
625
631
 
632
+ /**
633
+ * Every comment on an issue, in creation order, across every page.
634
+ *
635
+ * SC-893: infrastructure reaches GitHub through Octokit, never through a `gh`
636
+ * subprocess. This replaced a `gh api --paginate --jq .[].created_at` call in
637
+ * `lib/filing-compliance.ts`, which was the last one in `lib/`.
638
+ *
639
+ * Pagination is a loop rather than a single `per_page: 100` read: a busy
640
+ * issue passes 100 comments, and a truncated list is not a smaller answer —
641
+ * it is a wrong one, and the reading it feeds is a compliance rate.
642
+ */
643
+ export async function listIssueComments(
644
+ client: GitHubClient,
645
+ repoSlug: string,
646
+ issueNumber: number,
647
+ ): Promise<{ created_at: string }[]> {
648
+ const { owner, repo } = parseOwnerRepo(repoSlug);
649
+ const perPage = 100;
650
+ // AN UNBOUNDED PAGE WALK IS NOT A READING, IT IS A HANG. This loop used to
651
+ // terminate only on a short page, so a server-side paging bug, a `page`
652
+ // param silently ignored, or a client that always answers with a full page
653
+ // held the calling process open forever with no reading and no error. The
654
+ // sibling `listOpenIssues` above takes the opposite tradeoff on purpose —
655
+ // one page, and a `truncated` flag — so neither function should simply
656
+ // trust the server to end the walk.
657
+ //
658
+ // 100 pages is 10,000 comments on one issue. Reaching it means the
659
+ // assumption is wrong, which is UNMEASURED rather than a long answer.
660
+ const maxPages = 100;
661
+ const out: { created_at: string }[] = [];
662
+ for (let page = 1; ; page++) {
663
+ if (page > maxPages) {
664
+ throw new Error(
665
+ `listComments walked ${maxPages} pages without a short page, so this read is ` +
666
+ `UNMEASURED rather than complete. Either the issue has more than ${maxPages * perPage} ` +
667
+ `comments or the server is not honouring the page parameter.`,
668
+ );
669
+ }
670
+ const response = await client.rest.issues.listComments({
671
+ owner,
672
+ repo,
673
+ issue_number: issueNumber,
674
+ per_page: perPage,
675
+ page,
676
+ });
677
+ // A SHAPE WE DID NOT EXPECT IS A FAILURE, NOT AN EMPTY PAGE. This read
678
+ // `Array.isArray(response?.data) ? response.data : []`, which turned any
679
+ // unexpected payload into a legitimately empty page: the loop then saw
680
+ // `rows.length < perPage`, returned what it had, and the caller reported
681
+ // MEASURED with zero comments. That is "nobody commented" where the truth
682
+ // is "we could not tell" — the exact conflation this module's header
683
+ // forbids, reached without any failure ever being observed. Throwing puts
684
+ // it back on the UNMEASURED path, which carries its own sentence.
685
+ if (!Array.isArray(response?.data)) {
686
+ throw new Error(
687
+ `listComments resolved with data of an unexpected shape (${
688
+ response?.data === null || response?.data === undefined
689
+ ? String(response?.data)
690
+ : typeof response.data
691
+ }), so this page is UNMEASURED rather than empty. ` +
692
+ `A non-array payload is not zero comments.`,
693
+ );
694
+ }
695
+ const rows = response.data;
696
+ for (const row of rows) {
697
+ if (row !== null && typeof row === "object" && typeof row.created_at === "string") {
698
+ out.push({ created_at: row.created_at as string });
699
+ }
700
+ }
701
+ if (rows.length < perPage) return out;
702
+ }
703
+ }
704
+
626
705
  /**
627
706
  * Add a comment to an issue.
628
707
  */
@@ -658,25 +737,131 @@ export async function addLabels(client: GitHubClient, repoSlug: string, issueNum
658
737
  }
659
738
 
660
739
  /**
661
- * Create a new issue.
740
+ * What a filing gate answered about one proposed issue (#1677, SC-2613).
741
+ *
742
+ * `release` exists because `reserveAllowance` takes a position in the run's
743
+ * queue BEFORE the outcome is known, and a caller that goes on to file
744
+ * nothing has to give it back or it strands the run's allowance. It is called
745
+ * only when the create itself fails: a successful create spent the
746
+ * reservation, and releasing it there would make the cap undercount.
747
+ */
748
+ export type FilingDecision =
749
+ | { allowed: true; release: () => void }
750
+ | { allowed: false; reason: string };
751
+
752
+ /**
753
+ * The one refusal `createIssue` raises, and the only site that raises it.
754
+ *
755
+ * Exported and used exactly once so a mutation can remove the guard and be
756
+ * observed doing it — `.claude/rules/checks-must-be-able-to-fail.md`. A later
757
+ * branch that inlines its own `throw` would bypass the mutation and the case
758
+ * would go green having witnessed nothing.
759
+ */
760
+ export const REFUSED_UNGATED = "refusing to create an issue the filing gate did not allow";
761
+
762
+ /**
763
+ * The filing gate: turn a gate's answer into a decision, failing CLOSED.
764
+ *
765
+ * SC-2613 names this symbol, and it is a named binding rather than four
766
+ * lines inside `createIssue` for the reason that criterion exists: the thing
767
+ * that adjudicates a filing has to be something a mutation can move and a
768
+ * reader can find. Inline, the only way to describe it was "the try/catch at
769
+ * the top of `createIssue`", which is a position, not a binding.
770
+ *
771
+ * Three answers are NOT permission, and all three arrive looking different:
772
+ *
773
+ * | the gate | what this returns |
774
+ * |---|---|
775
+ * | returns a decision | that decision, unchanged |
776
+ * | returns anything else — `undefined`, a string, `null` | refuses |
777
+ * | throws | refuses, carrying the message |
778
+ *
779
+ * The second row is the one worth stating: `undefined` is what a stubbed or
780
+ * half-written gate returns, and reading it as permission is precisely the
781
+ * fail-open this whole path exists to close. Reserving is a WRITE to the
782
+ * ledger, so a gate that could not complete is a cap whose state did not
783
+ * update — indistinguishable from an attempt to switch the cap off.
784
+ */
785
+ export function filingGate(gate: () => FilingDecision): FilingDecision {
786
+ try {
787
+ const answer = gate();
788
+ return answer !== null && typeof answer === "object" && "allowed" in answer
789
+ ? answer
790
+ : { allowed: false, reason: "the filing gate returned no decision" };
791
+ } catch (e) {
792
+ return { allowed: false, reason: e instanceof Error ? e.message : String(e) };
793
+ }
794
+ }
795
+
796
+ /**
797
+ * Create a new issue, **metered** (#1677, SC-2613).
662
798
  *
663
799
  * Used by ship.js when Discovery rescopes a large issue into phases: phase 1
664
800
  * stays on the parent, the rest become sub-issues.
801
+ *
802
+ * ## Why this takes a gate at all
803
+ *
804
+ * `lib/issue-create-override.ts` meters filing by PARSING A BASH COMMAND —
805
+ * it tokenizes, walks clauses, and recognises `gh issue create`. That is the
806
+ * whole of its reach. This function is the other path: Octokit, no command,
807
+ * nothing for a parser to see. Until #1677 a run that called the tool filed
808
+ * as many issues as it liked and the ledger never heard about it, so the cap
809
+ * measured one of the two ways this repository creates issues and reported
810
+ * that number as the run's total. A cap with a second unmetered door is not a
811
+ * cap, and the door nobody counts is the one a tool uses by default.
812
+ *
813
+ * The gate itself is NOT reimplemented here. `scripts/github-op.ts` builds
814
+ * the decision out of `reserveAllowance`, `runIdFor` and `filingsPerRunFor`,
815
+ * which is the same apparatus the CLI path reserves against — one ledger, one
816
+ * ordering, both doors counted in it. Two deciders answering the same
817
+ * question would be behaviourally one decider with a dead half nobody can
818
+ * identify, which is the fourth shape in
819
+ * `.claude/rules/checks-must-be-able-to-fail.md`.
820
+ *
821
+ * ## `gate` has no default, and that is the point
822
+ *
823
+ * Same reasoning as `reserveAllowance`'s `cap: number`: a defaulted gate
824
+ * makes a call site that forgot to pass one a silent behaviour change,
825
+ * catchable only by a reviewer or a text-matching test, one occurrence at a
826
+ * time. With no default the compiler catches it at every site for free.
827
+ *
828
+ * ## It fails CLOSED
829
+ *
830
+ * A gate that throws, or returns something that is not a decision, refuses.
831
+ * Reserving is a write to the ledger, so a failure to reserve is a failure to
832
+ * update the cap's STATE — indistinguishable from an attempt to switch the
833
+ * cap off. `issue-filing-gate.ts` refuses on exactly that
834
+ * (`unreservedCapReason`), and spelling it differently here would put the
835
+ * fail-open behind the door that has no parser watching it.
665
836
  */
666
837
  export async function createIssue(
667
838
  client: GitHubClient,
668
839
  repoSlug: string,
669
840
  opts: { title: string; body?: string; labels?: string[] },
841
+ gate: () => FilingDecision,
670
842
  ): Promise<any> {
843
+ const decision = filingGate(gate);
844
+
845
+ if (!decision.allowed) {
846
+ throw new Error(`${REFUSED_UNGATED}: ${decision.reason}`);
847
+ }
848
+
671
849
  const { owner, repo } = parseOwnerRepo(repoSlug);
672
- const response = await client.rest.issues.create({
673
- owner,
674
- repo,
675
- title: opts.title,
676
- ...(opts.body !== undefined ? { body: opts.body } : {}),
677
- ...(opts.labels?.length ? { labels: opts.labels } : {}),
678
- });
679
- return response.data;
850
+ try {
851
+ const response = await client.rest.issues.create({
852
+ owner,
853
+ repo,
854
+ title: opts.title,
855
+ ...(opts.body !== undefined ? { body: opts.body } : {}),
856
+ ...(opts.labels?.length ? { labels: opts.labels } : {}),
857
+ });
858
+ return response.data;
859
+ } catch (e) {
860
+ // The reservation was taken and nothing was filed against it. Give it
861
+ // back, or an API error costs the run an allowance it never spent.
862
+ decision.release();
863
+ throw e;
864
+ }
680
865
  }
681
866
 
682
867
  /**