@vaultcompass/conductor 0.2.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.
@@ -0,0 +1,268 @@
1
+ // Finding the spec that stands in for a frozen intent contract.
2
+ //
3
+ // The intent gate's native flow wants a contract approved before the work
4
+ // starts. That is a per-task human step, and it is the one piece of ceremony
5
+ // the whole v0.2 design exists to remove from a pull request. So when a
6
+ // repository has no frozen contract of its own, the umbrella looks for the
7
+ // document the work was actually approved from, which in this org is a
8
+ // superpowers spec under docs/superpowers/specs.
9
+ //
10
+ // Everything here is READ-ONLY and does no subprocess work: it decides which
11
+ // file to import, and nothing else. That is what makes the discovery rules
12
+ // testable against a directory of empty files instead of against a running
13
+ // gate.
14
+ //
15
+ // Three sources, in order, and the order is the whole decision:
16
+ //
17
+ // 1. `--spec` on the umbrella's command line. Somebody typed this just now,
18
+ // so it outranks everything, including a checked-in contract. A path
19
+ // here that does not exist is REPORTED rather than replaced by a
20
+ // discovered one: running a different contract than the one a person
21
+ // just named is the wrong kindness.
22
+ //
23
+ // 2. A `Spec:` line in the pull request body. Written by whoever opened the
24
+ // pull request, which is a weaker claim than a command line typed now,
25
+ // and a path here that does not exist FALLS THROUGH to the convention. A
26
+ // typo in a pull request description must not be able to fail a build.
27
+ //
28
+ // 3. The convention: a markdown file directly under docs/superpowers/specs
29
+ // whose name relates to the branch. Directly under, not nested, because
30
+ // that is the layout intent-guard's own importer discovers and an
31
+ // archive subdirectory is not a candidate for this branch's contract.
32
+ import { readFileSync, readdirSync, realpathSync } from 'node:fs';
33
+ import path from 'node:path';
34
+ export const SPEC_DIR = 'docs/superpowers/specs';
35
+ export const PLAN_DIR = 'docs/superpowers/plans';
36
+ /**
37
+ * The branch name with its prefix removed.
38
+ *
39
+ * Only the FIRST segment goes. Dropping everything but the last would turn
40
+ * `feat/online/widget-cache` into `widget-cache` and match a spec about a
41
+ * different feature, and the prefix convention (`feat/`, `fix/`) is exactly
42
+ * one segment deep.
43
+ */
44
+ export function branchSlug(branch) {
45
+ const slash = branch.indexOf('/');
46
+ return slash === -1 ? branch : branch.slice(slash + 1);
47
+ }
48
+ /**
49
+ * A spec or plan filename reduced to the part that identifies the feature.
50
+ *
51
+ * The date prefix and the `-design` suffix are the two pieces of the
52
+ * superpowers naming convention that carry no identity: the same feature's
53
+ * spec and plan differ by exactly those, which is how intent-guard's own
54
+ * importer pairs them.
55
+ */
56
+ export function normalizeStem(fileName) {
57
+ const stem = fileName.replace(/\.md$/i, '');
58
+ return stem.replace(/^\d{4}-\d{2}-\d{2}-/, '').replace(/-design$/, '');
59
+ }
60
+ /** Whether a normalized stem and a slug name the same work. */
61
+ export function stemMatches(stem, slug) {
62
+ if (stem === '' || slug === '') {
63
+ return false;
64
+ }
65
+ return stem.includes(slug) || slug.includes(stem);
66
+ }
67
+ /**
68
+ * The path named by a `Spec:` line in a pull request body.
69
+ *
70
+ * Anchored to the start of a line on purpose: a sentence that happens to
71
+ * contain "the Spec: value" in prose is not somebody naming a file, and
72
+ * treating it as one would silently swap the contract a pull request is
73
+ * checked against.
74
+ *
75
+ * The FIRST such line wins when a body carries two. Not a deep decision, but
76
+ * it has to be a decision rather than whatever the regex happened to do: a
77
+ * pull request edited to add a second line above the first would otherwise
78
+ * change contract without the diff showing it.
79
+ */
80
+ export function specFromPrBody(body) {
81
+ const match = /^Spec:\s*(\S+)/m.exec(body);
82
+ return match === null ? null : match[1];
83
+ }
84
+ /** `pull_request.body` out of a GitHub event payload, or null. */
85
+ export function prBodyFromEvent(eventPath) {
86
+ let parsed;
87
+ try {
88
+ parsed = JSON.parse(readFileSync(eventPath, 'utf8'));
89
+ }
90
+ catch {
91
+ // A missing, unreadable or malformed payload is not an error here. It
92
+ // means this run has no pull request body to read, which is the ordinary
93
+ // case outside a pull request.
94
+ return null;
95
+ }
96
+ if (parsed === null || typeof parsed !== 'object') {
97
+ return null;
98
+ }
99
+ const pull = parsed.pull_request;
100
+ if (pull === null || typeof pull !== 'object') {
101
+ return null;
102
+ }
103
+ const body = pull.body;
104
+ return typeof body === 'string' ? body : null;
105
+ }
106
+ /** Markdown files directly under `dir`, sorted lexically. Never throws. */
107
+ function markdownFilesIn(repoRoot, dir) {
108
+ let entries;
109
+ try {
110
+ entries = readdirSync(path.join(repoRoot, dir), { withFileTypes: true })
111
+ .filter((entry) => entry.isFile() && /\.md$/i.test(entry.name))
112
+ .map((entry) => entry.name);
113
+ }
114
+ catch {
115
+ return [];
116
+ }
117
+ return entries.sort();
118
+ }
119
+ function exists(repoRoot, relative) {
120
+ try {
121
+ readFileSync(path.join(repoRoot, relative));
122
+ return true;
123
+ }
124
+ catch {
125
+ return false;
126
+ }
127
+ }
128
+ /**
129
+ * The best of the candidates whose stem relates to `target`, or undefined.
130
+ *
131
+ * `stemMatches` decides who is a CANDIDATE; this decides who wins, and the
132
+ * two are different questions. Ranking on the lexically newest filename alone
133
+ * was answering the second with the first: a loose candidate carrying a later
134
+ * date beat the spec whose stem was the branch slug exactly, and an undated
135
+ * name beat everything because it sorts after every date. A pull request was
136
+ * then measured against a different feature's requirements, with nothing in
137
+ * the report saying so, since naming the spec it used is exactly what the
138
+ * report does.
139
+ *
140
+ * So: an exact stem first, then the most specific stem, and only then the
141
+ * newest name. Specificity is stem LENGTH, which is crude but is the property
142
+ * the failure actually had: "superpowers" beat
143
+ * "1.2.1-base-and-superpowers" by being shorter and vaguer.
144
+ */
145
+ function bestMatch(names, target) {
146
+ return names
147
+ .filter((name) => stemMatches(normalizeStem(name), target))
148
+ .sort((a, b) => {
149
+ const stemA = normalizeStem(a);
150
+ const stemB = normalizeStem(b);
151
+ const exactA = stemA === target ? 0 : 1;
152
+ const exactB = stemB === target ? 0 : 1;
153
+ if (exactA !== exactB) {
154
+ return exactA - exactB;
155
+ }
156
+ if (stemA.length !== stemB.length) {
157
+ return stemB.length - stemA.length;
158
+ }
159
+ // Newest name last in lexical order, so descending puts it first. The
160
+ // names carry an ISO date prefix, so this is date order among equally
161
+ // good candidates and nothing more.
162
+ return a < b ? 1 : a > b ? -1 : 0;
163
+ })[0];
164
+ }
165
+ /**
166
+ * The plan belonging to a spec.
167
+ *
168
+ * The stem must be EQUAL, not merely related. The loose rule paired one
169
+ * feature's spec with another feature's plan, which freezes a set of
170
+ * requirements against a change budget belonging to different work: the
171
+ * resulting block or pass is about neither of them. No plan is a fine
172
+ * outcome, since intent-guard imports a spec on its own; the wrong plan is
173
+ * not.
174
+ *
175
+ * Applied to any spec, however it was chosen, rather than only to a
176
+ * conventionally discovered one: a spec named in a pull request body has a
177
+ * plan beside it just as often.
178
+ */
179
+ function planFor(repoRoot, specPath) {
180
+ const specStem = normalizeStem(path.basename(specPath));
181
+ const matches = markdownFilesIn(repoRoot, PLAN_DIR).filter((name) => normalizeStem(name) === specStem);
182
+ const newest = matches[matches.length - 1];
183
+ return newest === undefined ? null : `${PLAN_DIR}/${newest}`;
184
+ }
185
+ /** Normalizes a user-supplied path to a repository-relative one. */
186
+ function relativeToRoot(repoRoot, candidate) {
187
+ const relative = path.isAbsolute(candidate)
188
+ ? path.relative(repoRoot, candidate)
189
+ : path.normalize(candidate);
190
+ return relative.split(path.sep).join('/');
191
+ }
192
+ /**
193
+ * Whether a repository-relative path names a file that is really inside the
194
+ * repository.
195
+ *
196
+ * Only the pull request body is held to this. That body is written by whoever
197
+ * opened the pull request, and on a FORK pull request that is somebody with
198
+ * no write access at all: without the check, a `Spec: ../../etc/something`
199
+ * line imports an arbitrary readable file from the runner into a contract,
200
+ * and its path then appears in `contractSource` and in the `--approved-by`
201
+ * string.
202
+ *
203
+ * The test is on the RESOLVED path, not on the spelling. Testing the string
204
+ * left a two-step route to the same escape, and one pull request can take
205
+ * both steps: on a `pull_request` event `actions/checkout` checks out the
206
+ * merge ref, so a fork's own commits are in the tree, and the same pull
207
+ * request can add a symlink pointing outside AND the `Spec:` line naming it.
208
+ * To a string test that line is an ordinary relative path.
209
+ *
210
+ * A path that will not resolve at all -- a dangling symlink, a missing file,
211
+ * a directory nothing may read -- is not contained either, which lands it in
212
+ * the same place as a path that is simply not there: fall through to the
213
+ * convention.
214
+ *
215
+ * This is containment, NOT a ban on symlinks. One pointing at a file inside
216
+ * the repository resolves inside it and is used, because a repository that
217
+ * keeps its specs behind a link is doing something ordinary.
218
+ *
219
+ * `--spec` is deliberately NOT held to any of this. A person typed that on
220
+ * the command line just now, and pointing at a spec kept outside the checkout
221
+ * is a real thing to want.
222
+ */
223
+ function resolvesInsideRoot(repoRoot, relative) {
224
+ try {
225
+ // The root is resolved too. On macOS a temporary directory reaches the
226
+ // caller through a symlink, so comparing a resolved candidate against an
227
+ // unresolved root would report every path in such a tree as an escape.
228
+ const root = realpathSync(repoRoot);
229
+ const resolved = realpathSync(path.join(repoRoot, relative));
230
+ const inside = path.relative(root, resolved);
231
+ return inside !== '' && !inside.startsWith(`..${path.sep}`) && inside !== '..' && !path.isAbsolute(inside);
232
+ }
233
+ catch {
234
+ return false;
235
+ }
236
+ }
237
+ export function discoverSpec(options) {
238
+ const { repoRoot } = options;
239
+ if (options.spec !== undefined) {
240
+ const relative = relativeToRoot(repoRoot, options.spec);
241
+ if (!exists(repoRoot, relative)) {
242
+ return { kind: 'missing-flag', spec: relative };
243
+ }
244
+ return { kind: 'flag', spec: relative, plan: planFor(repoRoot, relative) };
245
+ }
246
+ if (options.prBody !== undefined) {
247
+ const named = specFromPrBody(options.prBody);
248
+ if (named !== null) {
249
+ const relative = relativeToRoot(repoRoot, named);
250
+ // A path out of the tree is treated exactly as a path that is not
251
+ // there: fall through to the convention. Same posture, same reason, and
252
+ // it keeps an unusable Spec: line from being able to silence the gate.
253
+ // Containment subsumes existence here, since a path that does not
254
+ // resolve is not contained.
255
+ if (resolvesInsideRoot(repoRoot, relative)) {
256
+ return { kind: 'pr-body', spec: relative, plan: planFor(repoRoot, relative) };
257
+ }
258
+ }
259
+ }
260
+ if (options.branch !== undefined) {
261
+ const best = bestMatch(markdownFilesIn(repoRoot, SPEC_DIR), branchSlug(options.branch));
262
+ if (best !== undefined) {
263
+ const relative = `${SPEC_DIR}/${best}`;
264
+ return { kind: 'convention', spec: relative, plan: planFor(repoRoot, relative) };
265
+ }
266
+ }
267
+ return { kind: 'none' };
268
+ }
@@ -0,0 +1,58 @@
1
+ import { type Finding, type NormalizedGateOutput } from './envelope.js';
2
+ import type { GateRole, Product } from './policy.js';
3
+ export declare function normalizeDepGuard(raw: unknown, version: string | null): NormalizedGateOutput;
4
+ export declare function normalizeVaultGuard(raw: unknown, version: string | null): NormalizedGateOutput;
5
+ /**
6
+ * The three ways the intent gate can block on the STATE of the contract
7
+ * rather than on anything in the diff.
8
+ *
9
+ * These matter because the gate pushes them into the same `reasons` array as
10
+ * its budget and drift reasons, and exposes no structured field saying which
11
+ * is which. So a run with an unfrozen contract AND a budget violation used
12
+ * to report only the budget violation: the reason the commit could not be
13
+ * fixed by editing the diff was in neither report.
14
+ *
15
+ * The prefixes are copied from intent-guard's own gate.ts. They are matched
16
+ * as prefixes rather than whole strings because one of the three
17
+ * interpolates an error message, and they are enumerated in a test against
18
+ * the real strings, so an upstream rewording turns that test red instead of
19
+ * silently dropping a reason out of every report.
20
+ */
21
+ export declare const GATE_STATE_REASON_KINDS: readonly ["contract-invalid", "contract-missing", "contract-unfrozen"];
22
+ export type GateStateReasonKind = (typeof GATE_STATE_REASON_KINDS)[number];
23
+ /** Which gate-state reason this is, or null when it is a budget or drift reason. */
24
+ export declare function classifyGateStateReason(reason: string): GateStateReasonKind | null;
25
+ export declare function normalizeIntentGuard(raw: unknown, version: string | null): NormalizedGateOutput;
26
+ export type GateProblemRule = 'conductor/gate-missing' | 'conductor/gate-output-unparseable' | 'conductor/gate-failed';
27
+ /**
28
+ * The finding raised when an ENABLED gate's binary cannot be found.
29
+ *
30
+ * A gate that is switched on and silently does not run is the failure this
31
+ * whole family exists to prevent: the report reads clean because nothing
32
+ * looked. So it is a finding, it blocks, and it says which names were
33
+ * tried, so the fix is in the message rather than in a support thread.
34
+ */
35
+ export declare function normalizeMissingGate(role: GateRole, product: Product, candidates: string[]): Finding;
36
+ /**
37
+ * The finding raised when a gate's `command:` names a file that is not
38
+ * there.
39
+ *
40
+ * It names ONLY that path. The candidate list belongs to resolution, and
41
+ * resolution never happened here: the user pointed at one specific file, so
42
+ * listing the names the umbrella would otherwise have searched for suggests
43
+ * it looked for them and implies the fix is to install one of them, when
44
+ * the fix is in their policy file.
45
+ */
46
+ export declare function normalizeMisconfiguredGate(role: GateRole, product: Product, command: string, detail: string): Finding;
47
+ /**
48
+ * The finding raised when a gate answered but the umbrella could not read
49
+ * the answer: invalid JSON, a shape the normalizer does not know, or any
50
+ * unexpected error thrown while normalizing.
51
+ *
52
+ * `detail` is an error MESSAGE, never a stack. A stack would put a local
53
+ * filesystem path into a report that gets uploaded, and it would tell the
54
+ * user nothing they can act on.
55
+ */
56
+ export declare function normalizeUnparseableGate(role: GateRole, product: Product, detail: string): Finding;
57
+ /** The finding raised when a gate could not be run or did not complete. */
58
+ export declare function normalizeFailedGate(role: GateRole, product: Product, detail: string): Finding;