@futurelastic/colab-handbook 0.0.0-bootstrap.0 → 1.12.0-rc.9

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 (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +310 -3
  3. package/README.vi.md +280 -0
  4. package/audit/audit.mjs +3035 -0
  5. package/package.json +26 -5
  6. package/templates/README.md +257 -0
  7. package/templates/adr-README.md +57 -0
  8. package/templates/branch-name.yml +51 -0
  9. package/templates/ci-laravel.yml +540 -0
  10. package/templates/ci-node.yml +291 -0
  11. package/templates/ci-python.yml +281 -0
  12. package/templates/deploy-xserver.yml +531 -0
  13. package/templates/dist-refs.yml +177 -0
  14. package/templates/docs-lint.mjs +993 -0
  15. package/templates/docs-lint.yml +55 -0
  16. package/templates/gotchas-d-README.md +41 -0
  17. package/templates/identity-vocabulary.example +58 -0
  18. package/templates/npx-launcher.mjs +213 -0
  19. package/templates/pre-commit-dispatch +88 -0
  20. package/templates/pre-commit-identity +267 -0
  21. package/templates/pre-push-guard +137 -0
  22. package/templates/release-auto.yml +475 -0
  23. package/templates/release-tag.yml +245 -0
  24. package/templates/repo-CLAUDE-block.md +21 -0
  25. package/tools/colab +13785 -0
  26. package/tools/lib/adopt.js +882 -0
  27. package/tools/lib/axis-authority.js +96 -0
  28. package/tools/lib/base-ci-verdict.js +93 -0
  29. package/tools/lib/blocked-by.js +262 -0
  30. package/tools/lib/branch-name.js +137 -0
  31. package/tools/lib/checklist.js +143 -0
  32. package/tools/lib/ci-cure.js +512 -0
  33. package/tools/lib/ci-grant.js +307 -0
  34. package/tools/lib/ci-verdict.js +113 -0
  35. package/tools/lib/claim-comments.js +212 -0
  36. package/tools/lib/claim-identity.js +195 -0
  37. package/tools/lib/codeowners.js +208 -0
  38. package/tools/lib/consumer-evidence.js +74 -0
  39. package/tools/lib/container-close.js +141 -0
  40. package/tools/lib/cure-diff.js +267 -0
  41. package/tools/lib/decision-record.js +335 -0
  42. package/tools/lib/dirty-owner.js +150 -0
  43. package/tools/lib/disposition.js +378 -0
  44. package/tools/lib/docs-only.js +156 -0
  45. package/tools/lib/exposure-shape.js +207 -0
  46. package/tools/lib/gate.js +80 -0
  47. package/tools/lib/git.js +1059 -0
  48. package/tools/lib/group-labels.js +120 -0
  49. package/tools/lib/hermetic.js +193 -0
  50. package/tools/lib/identity.js +187 -0
  51. package/tools/lib/install-check.js +259 -0
  52. package/tools/lib/instruction-file.js +302 -0
  53. package/tools/lib/journal.js +430 -0
  54. package/tools/lib/labels.js +653 -0
  55. package/tools/lib/landed.js +230 -0
  56. package/tools/lib/local-adopt.js +133 -0
  57. package/tools/lib/lockfile-drift.js +119 -0
  58. package/tools/lib/machine-trailer.js +83 -0
  59. package/tools/lib/machine.js +238 -0
  60. package/tools/lib/migration-grant.js +641 -0
  61. package/tools/lib/migration-paths.js +135 -0
  62. package/tools/lib/notify.js +188 -0
  63. package/tools/lib/npm-publish-guard.js +242 -0
  64. package/tools/lib/orphan-worktree.js +127 -0
  65. package/tools/lib/owner-branch.js +182 -0
  66. package/tools/lib/place.js +782 -0
  67. package/tools/lib/ports.js +167 -0
  68. package/tools/lib/procs.js +185 -0
  69. package/tools/lib/readiness.js +240 -0
  70. package/tools/lib/records.js +185 -0
  71. package/tools/lib/refs-brake.js +95 -0
  72. package/tools/lib/release-channel.js +99 -0
  73. package/tools/lib/release-cut.js +822 -0
  74. package/tools/lib/release-finalize.js +481 -0
  75. package/tools/lib/release-policy.js +358 -0
  76. package/tools/lib/release-tag.js +225 -0
  77. package/tools/lib/ship-batch.js +277 -0
  78. package/tools/lib/ship-roles.js +71 -0
  79. package/tools/lib/ship-target-sync.js +181 -0
  80. package/tools/lib/shipguard.js +317 -0
  81. package/tools/lib/shipped-branch.js +56 -0
  82. package/tools/lib/solo.js +213 -0
  83. package/tools/lib/squash.js +515 -0
  84. package/tools/lib/stale-base.js +70 -0
  85. package/tools/lib/stamp.js +740 -0
  86. package/tools/lib/state.js +262 -0
  87. package/tools/lib/teardown.js +83 -0
  88. package/tools/lib/trust-humans.js +104 -0
  89. package/tools/lib/util.js +98 -0
  90. package/tools/lib/wake.js +188 -0
  91. package/tools/lib/workflow-triggers.js +273 -0
  92. package/tools/lib/writes-authority.js +237 -0
  93. package/tools/lib/yaml.js +101 -0
  94. package/bin/cli.js +0 -3
@@ -0,0 +1,150 @@
1
+ 'use strict';
2
+ /**
3
+ * "The trunk checkout is dirty — whose is it?" (#294).
4
+ *
5
+ * `git status`, wherever this fleet asks it, answers exactly one question: is the repo root
6
+ * dirty. It has no opinion on whose change that is — a working tree carries no metadata linking a
7
+ * line back to a session. CONVENTIONS.md §4 used to fill that gap with an assumption ("an
8
+ * uncommitted file in the shared main checkout is someone else's live, uncommitted work"), and
9
+ * #294 is the measured case where that assumption was exactly backwards: a session's own stray
10
+ * relative-path write, read as someone else's, shipped uninvestigated and left the trunk checkout
11
+ * dirty for every other session's merge to trip over.
12
+ *
13
+ * This module is the attribution GUESS that replaces the assumption — never a certainty. It ranks
14
+ * two signals, in order:
15
+ *
16
+ * 1. BRANCH OVERLAP — does a live worktree's own branch touch this exact path (a real git diff
17
+ * against its base)? Strong: it is precisely the observed #294 shape, a file edited on both
18
+ * sides with the trunk copy carrying content the worktree copy does not.
19
+ * 2. TIME WINDOW — was exactly one live worktree's session already open when this path last
20
+ * changed on disk? Weak and only reached when branch overlap found nothing — an mtime
21
+ * correlation, not a content fact.
22
+ *
23
+ * Exactly one live worktree matching a signal is `attributed`, more than one is `ambiguous` (the
24
+ * signal picked out a set, not an owner), and neither signal producing a single match is
25
+ * `unattributed` — which covers "no live worktree in this repo" every bit as much as "the file
26
+ * predates every live worktree's session", because both leave nothing to name.
27
+ *
28
+ * PURE BY CONSTRUCTION, same posture as base-ci-verdict.js / ci-verdict.js / shipguard.js: plain
29
+ * data in, a verdict out. No git, no gh, no fs, no clock — the caller (tools/colab) does every
30
+ * subprocess/filesystem read (a `git diff --name-only` per live worktree, an `fs.statSync` per
31
+ * dirty path) and hands this module the numbers it needs. Every branch is directly reachable from
32
+ * `node --test`.
33
+ *
34
+ * ADVISORY ONLY. Nothing here is wired into any precondition — it enriches the ALREADY-COMPUTED
35
+ * "trunk checkout ready" check's `detail` string, never its `ok`/`class`/exit code. A wrong guess
36
+ * here costs a misleading hint in a report; a wrong guess baked into a gate would cost a merge.
37
+ */
38
+
39
+ /**
40
+ * One porcelain line's path, tolerating a caller whose SOURCE STRING already lost a leading
41
+ * character.
42
+ *
43
+ * The ordinary shape is a 2-character status code, one space, then the path (index 2 is the
44
+ * space) — `git.js`'s own `statusPorcelain` relies on that same fixed offset for its
45
+ * tracked/untracked split. But this module's callers hand in `git.dirtyTracked(...)`'s return
46
+ * value, and `git.js`'s `run()` wrapper `.trim()`s the ENTIRE multi-line status blob as ONE
47
+ * string before it is ever split into lines — so when the very first porcelain line in that blob
48
+ * begins with a literal space (an unstaged-only change, e.g. ` M path.md`), that space is the
49
+ * first character of the whole blob and is stripped, shifting just that one line to a
50
+ * 1-character-code + space + path shape (`M path.md`). Which line (if any) was first is already
51
+ * lost by the time this module sees the filtered, joined string, so this checks each line's own
52
+ * shape rather than assuming a fixed position: index 2 is the space in the ordinary case, index 1
53
+ * in the shifted one. (This is a property of the shared `git.js` wrapper, not a bug in it worth
54
+ * fixing there — `dirtyTracked`'s callers elsewhere only ever treat its return value as an opaque
55
+ * "is something dirty" string, never parse it positionally, which is exactly why this narrow case
56
+ * was never visible before #294 needed to read a PATH out of it.)
57
+ *
58
+ * A rename line reads `R old -> new`; the path this module (and every caller attributing a
59
+ * CURRENT dirty file) cares about is the destination, so `-> ` wins when present.
60
+ */
61
+ function pathFromPorcelainLine(line) {
62
+ let rest;
63
+ if (line.length > 2 && line[2] === ' ') rest = line.slice(3);
64
+ else if (line.length > 1 && line[1] === ' ') rest = line.slice(2);
65
+ else rest = line;
66
+ const arrow = rest.indexOf(' -> ');
67
+ return arrow === -1 ? rest : rest.slice(arrow + 4);
68
+ }
69
+
70
+ /** Parse `git status --porcelain [-uall]` output into a plain list of repo-relative paths. */
71
+ function parsePorcelainPaths(porcelainText) {
72
+ if (!porcelainText) return [];
73
+ return String(porcelainText).split('\n').filter(Boolean).map(pathFromPorcelainLine);
74
+ }
75
+
76
+ function toCandidate(wt, confidence) {
77
+ return {
78
+ worktree: wt.name,
79
+ branch: wt.branch || null,
80
+ session: wt.session || null,
81
+ sessionName: wt.sessionName || null,
82
+ confidence,
83
+ };
84
+ }
85
+
86
+ /**
87
+ * `dirtyPaths`: array of `{ path, mtimeMs }` (or a bare path string when no mtime is known —
88
+ * mtimeMs then reads as `null`). `worktrees`: array of `{ name, branch, session, sessionName,
89
+ * touchedPaths, createdAtMs }` — every entry the CALLER already judged to be a live candidate;
90
+ * this module does not itself decide which worktrees count as live (that is `colab`'s own
91
+ * `st.worktrees[...].status` reading, not a fact this module can derive from the shapes it is
92
+ * handed). `touchedPaths` is that worktree's branch's own `git diff --name-only <base>...<branch>`
93
+ * output; `createdAtMs` is `null` when the caller could not resolve a timestamp.
94
+ *
95
+ * Returns `{ paths: [{ path, verdict, candidates, why }] }` — one entry per input path, in the
96
+ * same order, `verdict` one of `attributed | ambiguous | unattributed`.
97
+ */
98
+ function attributeDirtyPaths({ dirtyPaths, worktrees }) {
99
+ const wts = Array.isArray(worktrees) ? worktrees : [];
100
+ const inputs = Array.isArray(dirtyPaths) ? dirtyPaths : [];
101
+ const paths = inputs.map((entry) => {
102
+ const p = typeof entry === 'string' ? entry : entry.path;
103
+ const mtimeMs = typeof entry === 'string' ? null
104
+ : (typeof entry.mtimeMs === 'number' ? entry.mtimeMs : null);
105
+ return attributeOne(p, mtimeMs, wts);
106
+ });
107
+ return { paths };
108
+ }
109
+
110
+ function attributeOne(p, mtimeMs, wts) {
111
+ const branchHits = wts.filter((w) => Array.isArray(w.touchedPaths) && w.touchedPaths.includes(p));
112
+ if (branchHits.length === 1) {
113
+ return {
114
+ path: p, verdict: 'attributed', candidates: [toCandidate(branchHits[0], 'branch-overlap')],
115
+ why: `${branchHits[0].branch || branchHits[0].name}'s own branch diff touches this path`,
116
+ };
117
+ }
118
+ if (branchHits.length > 1) {
119
+ return {
120
+ path: p, verdict: 'ambiguous', candidates: branchHits.map((w) => toCandidate(w, 'branch-overlap')),
121
+ why: `${branchHits.length} live branches touch this path — no single owner`,
122
+ };
123
+ }
124
+
125
+ if (mtimeMs != null) {
126
+ const timeHits = wts.filter((w) => typeof w.createdAtMs === 'number' && w.createdAtMs <= mtimeMs);
127
+ if (timeHits.length === 1) {
128
+ return {
129
+ path: p, verdict: 'attributed', candidates: [toCandidate(timeHits[0], 'time-window')],
130
+ why: `only ${timeHits[0].branch || timeHits[0].name}'s session was open when this path last ` +
131
+ 'changed — weak signal, no branch touched it directly',
132
+ };
133
+ }
134
+ if (timeHits.length > 1) {
135
+ return {
136
+ path: p, verdict: 'ambiguous', candidates: timeHits.map((w) => toCandidate(w, 'time-window')),
137
+ why: `${timeHits.length} live sessions were already open when this path last changed — no single owner`,
138
+ };
139
+ }
140
+ }
141
+
142
+ return {
143
+ path: p, verdict: 'unattributed', candidates: [],
144
+ why: wts.length === 0
145
+ ? 'no live worktree in this repo to attribute to'
146
+ : 'no live branch touches this path, and it predates every live session (or no mtime was available)',
147
+ };
148
+ }
149
+
150
+ module.exports = { attributeDirtyPaths, parsePorcelainPaths };
@@ -0,0 +1,378 @@
1
+ 'use strict';
2
+ /**
3
+ * tools/lib/disposition.js — "who may apply this disposition, unattended?", answered once.
4
+ *
5
+ * A disposition session (a 🩺 ops session, a producing lane) may not close its own issue —
6
+ * looking something up is not doing it. It measures or acts, posts evidence, and proposes a
7
+ * disposition; a later pass APPLIES it. Whether that pass may be an agent working unattended,
8
+ * or must be a human, is a deterministic rule over measurable inputs — never a judgement an
9
+ * agent makes about its own confidence (CONVENTIONS.md §5, *Disposition*).
10
+ *
11
+ * WHY THIS IS A MODULE AND NOT PROSE. Two consumers must reach the same verdict from the same
12
+ * evidence: the dashboard's authority check and the skill that runs the pass. Two prose copies
13
+ * of one table is the two-places-drift disease this handbook exists to kill — the same reason
14
+ * axis-authority.js, landed.js and readiness.js exist. The acceptance is "same evidence ⇒ same
15
+ * verdict", and it holds BY CONSTRUCTION only if both call one function (or copy-and-own this
16
+ * file per §9), rather than both reading the table with their own eyes.
17
+ *
18
+ * PURE BY CONSTRUCTION: facts in, verdict out. No git, no network, no `gh`, no tracker write.
19
+ * The caller gathers (the marker, the evidence fields, the descriptor, the graph) and this
20
+ * decides. That is what lets a consumer outside this repo reach the same verdict from facts it
21
+ * collected its own way.
22
+ *
23
+ * WHICH DIRECTION THIS FAILS IN. Towards `human`, always. An absent, malformed or unresolvable
24
+ * fact never yields `agent` — the same posture readiness.js takes towards `ready`. Getting this
25
+ * backwards spends a human's attention on something mechanical (cheap, visible); getting it
26
+ * right-ways-round wrong closes an issue nobody checked (expensive, invisible).
27
+ *
28
+ * THREE PLACES THIS DEPARTS FROM ITS SOURCE, each deliberate, each because the source was
29
+ * written for a repo that answers a question this one answers differently:
30
+ *
31
+ * 1. TIER → THE AXIS OF RECORD. The source table reads "tier A ⇒ human, tier B/C ⇒ agent".
32
+ * This handbook made `exposure` the axis of record and `tier` a legacy read of it (§2,
33
+ * #144): `A -> released`, `C -> live`, `B -> null`. Writing the letters in here would
34
+ * re-weld the axis this repo deliberately cut. So the rule is stated on `exposure`
35
+ * (`released` ⇒ human) and a legacy descriptor is read THROUGH axis-authority.js — which
36
+ * also means a bare `tier: B` resolves to `null`, i.e. no opinion, i.e. `human`. That is
37
+ * not a stricter reading smuggled in: `tier: B` genuinely carries no derivable opinion
38
+ * about what consumes the repo, and this fleet has `none`, `self` and `released` all
39
+ * measured under it.
40
+ * 2. `not planned` → THE TOKEN `not-planned`. The KIND keeps GitHub's own close-reason
41
+ * spelling, because that is the string the close is made with. The MARKER TOKEN cannot
42
+ * carry a space: the token set is closed and read by EQUALITY (the rule `colab:grade`
43
+ * already sets), and whitespace inside a token makes the parse ambiguous rather than the
44
+ * comparison strict. Kind and token therefore differ for exactly this one member.
45
+ * 3. THE TWO SHARED INPUTS GATE ONLY `done` AND `not planned`. The source states the axis
46
+ * input as "a human confirms anything that *closes*", and the skip-fence input as "any
47
+ * evidence naming one of these ⇒ human". Taken at maximum width that would drag `split`
48
+ * and `routed-out` in, since those close the issue too — but the source's own table says
49
+ * "never — filing is mechanical" for both, and its human list names exactly the
50
+ * `done`/`not planned` pair. Read together: the gate is on the kinds whose close ASSERTS
51
+ * AN OUTCOME, not on the kinds that merely re-home the work. Filing a sub-issue asserts
52
+ * nothing about a production surface; `done` asserts that a fenced action was performed
53
+ * and verified, which is the whole reason the fence exists.
54
+ */
55
+
56
+ const { axisOfRecord } = require('./axis-authority');
57
+ const { parseWakeLine } = require('./wake');
58
+
59
+ // ---------------------------------------------------------------------------------------------
60
+ // Vocabulary
61
+ // ---------------------------------------------------------------------------------------------
62
+
63
+ const AGENT = 'agent';
64
+ const HUMAN = 'human';
65
+
66
+ /**
67
+ * The seven dispositions, by KIND — the prose name, and for `not planned` the literal string
68
+ * GitHub's close reason takes. Frozen and closed: a kind outside this list is not a disposition
69
+ * with an unknown authority, it is not a disposition.
70
+ */
71
+ const KINDS = Object.freeze(['done', 'split', 'routed-out', 'hold', 'needs-boss', 'not planned', 'leave']);
72
+
73
+ /**
74
+ * The same seven by MARKER TOKEN. No token is a prefix or a decorated variant of another — the
75
+ * property `colab:grade`'s token set has, and for the identical reason: a reader comparing by
76
+ * equality can then never mistake a qualifier for a verdict, and a reader that (wrongly) compares
77
+ * by prefix cannot be silently right for a while and wrong later.
78
+ */
79
+ const TOKEN_BY_KIND = Object.freeze({
80
+ done: 'done',
81
+ split: 'split',
82
+ 'routed-out': 'routed-out',
83
+ hold: 'hold',
84
+ 'needs-boss': 'needs-boss',
85
+ 'not planned': 'not-planned',
86
+ leave: 'leave',
87
+ });
88
+ const KIND_BY_TOKEN = Object.freeze(
89
+ Object.fromEntries(Object.entries(TOKEN_BY_KIND).map(([kind, token]) => [token, kind]))
90
+ );
91
+ const TOKENS = Object.freeze(Object.values(TOKEN_BY_KIND));
92
+
93
+ /**
94
+ * The kinds whose close asserts an outcome, and which the axis and skip-fence inputs therefore
95
+ * gate. See departure 3 in the header: `split` and `routed-out` also close, and are deliberately
96
+ * NOT here.
97
+ */
98
+ const ASSERTS_AN_OUTCOME = Object.freeze(['done', 'not planned']);
99
+
100
+ /**
101
+ * The classes a disposition pass may never conclude on its own, whatever the exposure — the same
102
+ * set the decisions lane already fences off as human-only. Callers name the classes their
103
+ * evidence touches; this module does not sniff prose for them.
104
+ */
105
+ const SKIP_FENCE_CLASSES = Object.freeze(['production', 'credentials', 'destructive', 'non-undoable', 'promotion']);
106
+
107
+ /**
108
+ * The fixed evidence shape a disposition rides on. Free-form evidence is a FINDING, not a
109
+ * disposition: a pass that cannot tell what was done from what remains cannot verify either.
110
+ * `crossCheck` is deliberately not in this list — it is required by `done` specifically (a
111
+ * second, independent command confirming the effect), not by the evidence shape in general.
112
+ */
113
+ const EVIDENCE_FIELDS = Object.freeze(['what', 'command', 'result', 'remains']);
114
+
115
+ /**
116
+ * PROPOSAL, not a measured threshold (CONVENTIONS.md §5 says so in the same words). A hold whose
117
+ * wake condition has sat this long without movement wants a human to confirm it is still wanted.
118
+ * Exported so a consumer can measure against a different number rather than fork the module, and
119
+ * so the day someone measures it, one constant moves.
120
+ */
121
+ const HOLD_STALE_DAYS = 30;
122
+
123
+ /**
124
+ * One marker per line, `proposed=<token>`, the shape `colab:grade verdict=<token>` already uses.
125
+ * Exported as a PATTERN STRING, not a compiled `/g` RegExp: a global RegExp carries `lastIndex`,
126
+ * so a shared one makes `.test()` alternate true/false across calls for a consumer that reaches
127
+ * for the export instead of the function. The lazy `(\S+?)` is what lets `routed-out` survive —
128
+ * a character class excluding `-` silently truncated it to `routed`, which then read as an
129
+ * unrecognised token, which fails safe to `human` and would have looked like policy.
130
+ */
131
+ const MARKER_PATTERN = String.raw`<!--\s*colab:disposition\s+proposed=(\S+?)\s*-->`;
132
+
133
+ // ---------------------------------------------------------------------------------------------
134
+ // Reading and writing the marker
135
+ // ---------------------------------------------------------------------------------------------
136
+
137
+ /**
138
+ * Find the proposed disposition in a comment body. Returns `null` when no marker is present at
139
+ * all, else `{ token, kind, recognised }`.
140
+ *
141
+ * DEGRADE, NEVER GATE — and it cuts both ways here. A missing marker means "no proposal", never
142
+ * "no evidence exists": a consumer may not treat its absence as a verdict. An UNRECOGNISED token,
143
+ * or two markers proposing different things, reads as `recognised: false` with `kind: null` —
144
+ * "not cleared", never a silent default to the safe-looking value. Read by equality on `token`,
145
+ * never by prefix, never by heading text.
146
+ */
147
+ function parseMarker(text) {
148
+ if (typeof text !== 'string' || text === '') return null;
149
+ const tokens = [...text.matchAll(new RegExp(MARKER_PATTERN, 'g'))].map((m) => m[1]);
150
+ if (tokens.length === 0) return null;
151
+ const distinct = [...new Set(tokens)];
152
+ if (distinct.length > 1) {
153
+ return { token: null, kind: null, recognised: false, why: `${distinct.length} markers proposing different dispositions` };
154
+ }
155
+ const token = distinct[0];
156
+ const kind = Object.prototype.hasOwnProperty.call(KIND_BY_TOKEN, token) ? KIND_BY_TOKEN[token] : null;
157
+ return kind
158
+ ? { token, kind, recognised: true }
159
+ : { token, kind: null, recognised: false, why: `unrecognised disposition token "${token}"` };
160
+ }
161
+
162
+ /**
163
+ * The marker line for a kind. Throws on anything outside the closed set — a writer inventing a
164
+ * token is a bug at the writer, not a token a reader should have to cope with.
165
+ */
166
+ function formatMarker(kind) {
167
+ if (!Object.prototype.hasOwnProperty.call(TOKEN_BY_KIND, kind)) {
168
+ throw new Error(`not a disposition kind: ${JSON.stringify(kind)} (one of: ${KINDS.join(', ')})`);
169
+ }
170
+ return `<!-- colab:disposition proposed=${TOKEN_BY_KIND[kind]} -->`;
171
+ }
172
+
173
+ /**
174
+ * Does this evidence have the fixed shape? `{ complete, missing }`. A field present but empty (or
175
+ * whitespace) counts as missing — a heading with nothing under it is the commonest way free-form
176
+ * evidence passes for structured.
177
+ */
178
+ function evidenceShape(evidence) {
179
+ const e = evidence && typeof evidence === 'object' ? evidence : {};
180
+ const missing = EVIDENCE_FIELDS.filter((f) => typeof e[f] !== 'string' || e[f].trim() === '');
181
+ return { complete: missing.length === 0, missing };
182
+ }
183
+
184
+ // ---------------------------------------------------------------------------------------------
185
+ // The authority table
186
+ // ---------------------------------------------------------------------------------------------
187
+
188
+ /**
189
+ * Does the repo's axis of record permit an agent to apply an outcome-asserting disposition
190
+ * unattended? `{ ok, why }`. Accepts a resolved `exposure` (for a consumer that already has one)
191
+ * or a parsed `.github/project.yml` under `project`; the descriptor is read through
192
+ * axis-authority.js so the legacy `tier` read stays in one place. Anything unresolvable is `human`.
193
+ */
194
+ function axisPermits({ exposure, project } = {}) {
195
+ const resolved = exposure === undefined || exposure === null ? axisOfRecord(project).exposure : exposure;
196
+ if (resolved === 'none' || resolved === 'self' || resolved === 'live') {
197
+ return { ok: true, why: `exposure ${resolved} — the agent applies` };
198
+ }
199
+ if (resolved === 'released') {
200
+ return { ok: false, why: 'exposure released — a human confirms anything that asserts an outcome' };
201
+ }
202
+ return {
203
+ ok: false,
204
+ why: 'no axis of record resolves (a bare tier: B carries no opinion) — unresolvable reads as human',
205
+ };
206
+ }
207
+
208
+ function fencedClasses(skipFence) {
209
+ if (skipFence === true) return ['unnamed'];
210
+ if (!Array.isArray(skipFence)) return [];
211
+ return skipFence.filter((c) => typeof c === 'string' && c.trim() !== '');
212
+ }
213
+
214
+ // Does this wake fact name something that ends the park? A `review-by:<date>`, a real `blockedBy`
215
+ // edge, or — since #382 — a `wake:` value from the closed vocabulary (tools/lib/wake.js):
216
+ // `conditions` is the value as written on the Hold: line, or an array of condition strings. One
217
+ // piece outside the vocabulary refuses the whole value, exactly as wake.js does — prose is not a
218
+ // wake, however specific it sounds.
219
+ function namesAWake(w) {
220
+ if ((typeof w.reviewBy === 'string' && w.reviewBy.trim() !== '') || w.blockedBy === true) return true;
221
+ if (w.conditions === undefined || w.conditions === null) return false;
222
+ return parseWakeLine(w.conditions).ok;
223
+ }
224
+
225
+ function verdict(kind, authority, applicable, why, blockers, extra) {
226
+ return Object.assign({ kind, authority, applicable, why, blockers: blockers || [] }, extra || {});
227
+ }
228
+
229
+ /**
230
+ * Who may apply the proposed disposition, and is it applicable at all?
231
+ *
232
+ * Returns `{ kind, authority, applicable, why, blockers[], converted? }`:
233
+ * - `authority` — the closed two-value answer this module exists for: `agent` | `human`.
234
+ * - `applicable` — whether the disposition's OWN precondition is met. `false` means applying it
235
+ * is wrong for anybody; the fix is to supply the missing fact (file the sub-issue, name the
236
+ * wake), not to escalate. The two fields are independent on purpose: "an agent may do this"
237
+ * and "this is a coherent thing to do yet" are different questions, and collapsing them is how
238
+ * a mechanical gap gets routed to a human as if it were a judgement call.
239
+ * - `converted` — set only for `leave`, which no agent ever applies: `hold` when a wake is
240
+ * nameable, else `finding`.
241
+ *
242
+ * A human may always apply any disposition on any issue — the agent's verdict is a proposal, never
243
+ * a lock. `authority: 'agent'` therefore means "an agent MAY, unattended", never "a human may not".
244
+ *
245
+ * Facts (all optional; absent reads as unproven, never as satisfied):
246
+ * kind | token, exposure | project, skipFence[], evidence{what,command,result,remains},
247
+ * crossCheck, acceptance{ticked,remainderDeclared}, gateNode,
248
+ * wake{reviewBy,blockedBy,conditions,ageDays,movedSince}, subIssue{filed,delivery,wake,evidenceCopied},
249
+ * routedTo{ref,linksBack}, supersededBy{ref,state,referencesThis}
250
+ */
251
+ function classify(facts) {
252
+ const f = facts && typeof facts === 'object' ? facts : {};
253
+ const kind = f.kind !== undefined && f.kind !== null
254
+ ? f.kind
255
+ : (f.token !== undefined && f.token !== null ? KIND_BY_TOKEN[f.token] : undefined);
256
+
257
+ if (!KINDS.includes(kind)) {
258
+ return verdict(null, HUMAN, false, 'not a recognised disposition — not cleared, never a default', []);
259
+ }
260
+
261
+ const fenced = fencedClasses(f.skipFence);
262
+ const shape = evidenceShape(f.evidence);
263
+
264
+ // The two shared inputs, evaluated only for the kinds whose close asserts an outcome.
265
+ const sharedBlockers = [];
266
+ if (ASSERTS_AN_OUTCOME.includes(kind)) {
267
+ const axis = axisPermits(f);
268
+ if (!axis.ok) sharedBlockers.push(axis.why);
269
+ if (fenced.length) sharedBlockers.push(`skip-fence class named in the evidence: ${fenced.join(', ')}`);
270
+ }
271
+
272
+ switch (kind) {
273
+ case 'done': {
274
+ if (!shape.complete) {
275
+ return verdict(kind, HUMAN, false,
276
+ 'evidence is not in the fixed shape — free-form evidence is a finding, not a disposition',
277
+ [`evidence missing: ${shape.missing.join(', ')}`]);
278
+ }
279
+ const blockers = [...sharedBlockers];
280
+ if (typeof f.crossCheck !== 'string' || f.crossCheck.trim() === '') {
281
+ blockers.push('no re-runnable cross-check command recorded — measurement cannot cross-check itself');
282
+ }
283
+ const acc = f.acceptance && typeof f.acceptance === 'object' ? f.acceptance : {};
284
+ if (acc.ticked !== true && acc.remainderDeclared !== true) {
285
+ blockers.push('acceptance neither ticked nor a remainder declared');
286
+ }
287
+ if (f.gateNode === true) blockers.push('the issue is a gate node for something still open');
288
+ return blockers.length
289
+ ? verdict(kind, HUMAN, true, 'a human must confirm this close', blockers)
290
+ : verdict(kind, AGENT, true, 'executed and cross-checked, nothing gated — the agent applies', []);
291
+ }
292
+
293
+ case 'split': {
294
+ // "never — filing is mechanical". Unmet mechanics do not escalate; they name what to file.
295
+ const s = f.subIssue && typeof f.subIssue === 'object' ? f.subIssue : {};
296
+ const blockers = [];
297
+ if (s.filed !== true) blockers.push('remainder not filed as a native sub-issue');
298
+ if (s.delivery !== true) blockers.push('sub-issue does not carry the same delivery: label');
299
+ if (s.wake !== true) blockers.push('sub-issue carries no wake condition');
300
+ if (s.evidenceCopied !== true) blockers.push('evidence not copied across to the sub-issue');
301
+ return blockers.length
302
+ ? verdict(kind, AGENT, false, 'the split is not filed yet — file it, do not escalate it', blockers)
303
+ : verdict(kind, AGENT, true, 'remainder filed and carried across — filing is mechanical', []);
304
+ }
305
+
306
+ case 'routed-out': {
307
+ const r = f.routedTo && typeof f.routedTo === 'object' ? f.routedTo : {};
308
+ const blockers = [];
309
+ if (typeof r.ref !== 'string' || r.ref.trim() === '') blockers.push('no <other-repo>#N filed');
310
+ if (r.linksBack !== true) blockers.push('the destination issue does not link back to this one');
311
+ return blockers.length
312
+ ? verdict(kind, AGENT, false, 'the route is not complete yet — finish the filing', blockers)
313
+ : verdict(kind, AGENT, true, 'filed elsewhere and linked back — filing is mechanical', []);
314
+ }
315
+
316
+ case 'hold': {
317
+ const w = f.wake && typeof f.wake === 'object' ? f.wake : {};
318
+ if (!namesAWake(w)) {
319
+ return verdict(kind, AGENT, false,
320
+ 'a park with no wake condition is not a hold — it is a silent wontfix, and should be said plainly',
321
+ ['no review-by:<date>, no blockedBy edge, and no wake: condition from the closed vocabulary']);
322
+ }
323
+ const stale = Number.isFinite(w.ageDays) && w.ageDays > HOLD_STALE_DAYS && w.movedSince !== true;
324
+ return stale
325
+ ? verdict(kind, HUMAN, true,
326
+ `the wake condition has stood ${w.ageDays} days without movement — a human confirms it is still wanted (${HOLD_STALE_DAYS} d is a PROPOSAL, unmeasured)`,
327
+ [`wake older than ${HOLD_STALE_DAYS} days with no movement`])
328
+ : verdict(kind, AGENT, true, 'the park names what it is waiting on — the agent applies', []);
329
+ }
330
+
331
+ case 'needs-boss':
332
+ // Record-first: the pass writes the question down with the apply lever pre-filled and moves
333
+ // on. It does not stop and wait, and it never applies this itself.
334
+ return verdict(kind, HUMAN, true,
335
+ 'never applied by an agent — the agent records the question, Boss answers, the issue returns to intake', []);
336
+
337
+ case 'not planned': {
338
+ const sup = f.supersededBy && typeof f.supersededBy === 'object' ? f.supersededBy : {};
339
+ const superseded = (typeof sup.ref === 'string' && sup.ref.trim() !== '')
340
+ && (sup.state === 'merged' || sup.state === 'closed')
341
+ && sup.referencesThis === true;
342
+ if (!superseded) {
343
+ return verdict(kind, HUMAN, true,
344
+ 'an abandoned direction is a human judgement, always — only a merged or closed replacement referencing this issue makes it mechanical',
345
+ ['no merged/closed replacement referencing this issue']);
346
+ }
347
+ return sharedBlockers.length
348
+ ? verdict(kind, HUMAN, true, 'superseded, but a human must confirm this close', sharedBlockers)
349
+ : verdict(kind, AGENT, true, 'superseded by a merged or closed replacement that references this issue', []);
350
+ }
351
+
352
+ case 'leave': {
353
+ // An agent never applies `leave`. It converts: a nameable wake is a `hold`; nothing to name
354
+ // is a finding — an issue on its fourth session with no disposition is a brief problem, not
355
+ // a measurement problem. (A human may still leave with a reason; that reason is the wake.)
356
+ const w = f.wake && typeof f.wake === 'object' ? f.wake : {};
357
+ if (!namesAWake(w)) {
358
+ return verdict(kind, HUMAN, false,
359
+ 'no wake condition can be named — this is a finding about the brief, not a disposition',
360
+ ['leave proposed with nothing to wake on'], { converted: 'finding' });
361
+ }
362
+ const asHold = classify(Object.assign({}, f, { kind: 'hold', token: undefined }));
363
+ return verdict(kind, asHold.authority, asHold.applicable,
364
+ `leave converts to hold: ${asHold.why}`, asHold.blockers, { converted: 'hold' });
365
+ }
366
+
367
+ /* istanbul ignore next — unreachable: KINDS.includes(kind) guarded above */
368
+ default:
369
+ return verdict(null, HUMAN, false, 'not a recognised disposition — not cleared, never a default', []);
370
+ }
371
+ }
372
+
373
+ module.exports = {
374
+ AGENT, HUMAN,
375
+ KINDS, TOKENS, TOKEN_BY_KIND, KIND_BY_TOKEN,
376
+ ASSERTS_AN_OUTCOME, SKIP_FENCE_CLASSES, EVIDENCE_FIELDS, HOLD_STALE_DAYS, MARKER_PATTERN,
377
+ parseMarker, formatMarker, evidenceShape, axisPermits, classify,
378
+ };