shapeup-sdlc 3.2.0 → 3.4.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,319 @@
1
+ #!/usr/bin/env node
2
+ // The round build gate — does the FEATURE build and launch, before the judge is asked about it.
3
+ //
4
+ // WHY A GATE ABOVE T0. A T0 verdict is one scope's fixtures, run inside that scope's substrate, and
5
+ // the fixtures are the scope-architect's to write. Nothing in that layer proves the feature as a
6
+ // whole compiles or starts. Measured on a live mobile run: every one of 30 T0 trials went green on
7
+ // its first try — the fixtures were TypeScript stand-ins, structural greps and a test-suite wrapper
8
+ // that never compiled its sources — while the ledger's own `run_cmd` failed, and once the compiler
9
+ // could actually reach the new files it reported 58 errors. Three rounds of EVAL then graded a
10
+ // blank screen: nothing in the loop had ever installed or launched the app. The hill shards, derived
11
+ // from those T0 verdicts, all read DOWNHILL_EXECUTION.
12
+ //
13
+ // Two lessons, and this gate is both:
14
+ //
15
+ // 1. A green exit code from the build is not proof the feature compiled. Some toolchains compile
16
+ // only what is reachable from an entry point, so a scope's files can sit outside the compiled
17
+ // set and the build stays green. The exit code is the necessary half; `build_probe` is where a
18
+ // project asserts the other half (the artifact covers what the run wrote), in whatever way its
19
+ // toolchain makes possible.
20
+ // 2. Nothing else in the loop launches the app. `launch_probe` is where a project installs, starts
21
+ // and asserts a first screen. For the mobile archetype its absence is called out every round,
22
+ // because "on-device install unverified" was an L0 risk with no owner for three rounds.
23
+ //
24
+ // WHAT RUNS, in order, each stopping the rest on failure: the ledger's `run_cmd` (the build),
25
+ // then the profile's `build_probe`, then its `launch_probe`. All three are commands the tech lead
26
+ // pinned at GATE L0 — this script invents none of them, and a run that declares none of them gets
27
+ // exit 3 and no artifact, which every reader treats as "no gate declared" rather than as green.
28
+ //
29
+ // THE RED GATE IS THE NEXT ROUND'S BUG LIST. `harness compile` reads the latest gate artifact for
30
+ // the previous round and addresses each failing step to the scopes whose substrate contains the
31
+ // files the output names (unowned → every scope, marked), exactly as it does for an EVAL verdict.
32
+ // `reduce hill` reads the same artifact: a T0-green verdict from a round whose gate is red moves no
33
+ // scope downhill. Both are the same file, written once here — zero LLM tokens, same as T0.
34
+ //
35
+ // Usage:
36
+ // node "${CLAUDE_PLUGIN_ROOT}/kernel/harness.mjs" verify build --slug <slug> --round N [--cwd <dir>]
37
+ //
38
+ // Exit code: 0 = green, 1 = red, 2 = bad argv, 3 = nothing declared (no run_cmd, no probes).
39
+
40
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from "node:fs";
41
+ import { join, resolve } from "node:path";
42
+ import { spawnSync } from "node:child_process";
43
+ import { createHash } from "node:crypto";
44
+ import { runArgs, isMain } from "../lib/argv.mjs";
45
+ import { harnessRun, projectProfile, roundBuildDir, localRoot, runIdFromRoot } from "../lib/paths.mjs";
46
+ import { readContract, readAllContracts, PROJECT_PROFILE, SCOPE_CONTRACT, splitFrontmatter } from "../lib/contract.mjs";
47
+ import { scopesDir } from "../lib/paths.mjs";
48
+ import { digest } from "../probe/digest.mjs";
49
+
50
+ /** The three steps, in the order they run. */
51
+ export const STEPS = ["run_cmd", "build_probe", "launch_probe"];
52
+
53
+ /** Archetypes whose product cannot be judged without being launched on a device or simulator. */
54
+ export const LAUNCH_REQUIRED_ARCHETYPES = new Set(["mobile"]);
55
+
56
+ const TAIL_BYTES = 8 * 1024;
57
+ const tail = (s) => (s || "").length > TAIL_BYTES ? (s || "").slice(-TAIL_BYTES) : (s || "");
58
+
59
+ /**
60
+ * The commands this gate runs for a feature, read from the artifacts that declare them.
61
+ *
62
+ * `run_cmd` comes from the run ledger's frontmatter (`harness-run.md`, written at GATE L0 and
63
+ * already what every EVAL order carries); the two probes come from the committed project profile.
64
+ * Nothing is inferred: an absent field is an absent step.
65
+ *
66
+ * @param {string} cwd - Project root.
67
+ * @param {string} slug - Feature slug.
68
+ * @returns {{archetype:(string|null), steps:Array<{kind:string, cmd:string}>, warnings:string[]}}
69
+ * The declared steps in run order, the profile's archetype, and the warnings a reader should
70
+ * see — currently one: a launch-required archetype with no `launch_probe`.
71
+ */
72
+ export function declaredSteps(cwd, slug) {
73
+ const warnings = [];
74
+ let runCmd = null;
75
+ try {
76
+ const hr = splitFrontmatter(readFileSync(harnessRun(cwd, slug), "utf8")).meta || {};
77
+ runCmd = typeof hr.run_cmd === "string" && hr.run_cmd.trim() ? hr.run_cmd.trim() : null;
78
+ } catch { /* no ledger — no run_cmd */ }
79
+
80
+ let profile = null;
81
+ const pp = projectProfile(cwd, slug);
82
+ if (existsSync(pp)) profile = readContract(pp, PROJECT_PROFILE)?.contract || null;
83
+ const archetype = typeof profile?.archetype === "string" ? profile.archetype : null;
84
+ const pick = (k) => (typeof profile?.[k] === "string" && profile[k].trim() ? profile[k].trim() : null);
85
+
86
+ const steps = [];
87
+ if (runCmd) { steps.push({ kind: "run_cmd", cmd: runCmd }); warnings.push(...fixtureCoverageWarnings(cwd, slug, runCmd)); }
88
+ else warnings.push("the run ledger declares no run_cmd — the build itself is not part of this gate");
89
+ const buildProbe = pick("build_probe");
90
+ if (buildProbe) steps.push({ kind: "build_probe", cmd: buildProbe });
91
+ const launchProbe = pick("launch_probe");
92
+ if (launchProbe) steps.push({ kind: "launch_probe", cmd: launchProbe });
93
+ else if (archetype && LAUNCH_REQUIRED_ARCHETYPES.has(archetype)) {
94
+ warnings.push(`archetype ${archetype} declares no launch_probe in project-profile.md — nothing in the loop ` +
95
+ `launches the app, so a blank first screen survives every round. Give the install/launch risk an owner: ` +
96
+ `a command that installs the built artifact, starts it, asserts the first screen and fails on fatal logs.`);
97
+ }
98
+ return { archetype, steps, warnings };
99
+ }
100
+
101
+ /**
102
+ * The executable a run command actually invokes — its basename, past any `cd …&&`, `env`, or
103
+ * `VAR=value` prefix. `cd app && DEVECO_SDK_HOME=/x /tools/hvigor/bin/hvigorw assembleHap` → `hvigorw`.
104
+ * @param {string} runCmd - The ledger's run command.
105
+ * @returns {(string|null)} The tool's basename, or null when none can be read.
106
+ */
107
+ export function buildTool(runCmd) {
108
+ const segments = String(runCmd || "").split(/&&|;|\|\|/).map((s) => s.trim()).filter(Boolean);
109
+ for (const seg of segments) {
110
+ const tokens = seg.split(/\s+/).filter((t) => t && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(t) && t !== "env" && t !== "cd");
111
+ if (seg.startsWith("cd ")) continue;
112
+ if (!tokens.length) continue;
113
+ const base = tokens[0].split(/[\\/]/).pop();
114
+ if (base) return base;
115
+ }
116
+ return null;
117
+ }
118
+
119
+ /**
120
+ * Scopes whose fixtures never invoke the build tool `run_cmd` names — ADVISORY.
121
+ *
122
+ * A T0 layer can be entirely green on a feature that does not compile when every fixture is a
123
+ * grep or a stand-in compiler (measured: 13 of 15 fixtures on one run). The harness cannot know
124
+ * what a project's fixtures should run, but it can see when none of a scope's fixture commands
125
+ * mention the tool the ledger builds with, and say so beside the gate's verdict. A warning, not a
126
+ * failure: a library scope with no compiled surface is a legitimate reason for the mismatch.
127
+ *
128
+ * @param {string} cwd - Project root.
129
+ * @param {string} slug - Feature slug.
130
+ * @param {(string|null)} runCmd - The ledger's run command.
131
+ * @returns {string[]} One warning per scope whose fixtures name the tool nowhere.
132
+ */
133
+ export function fixtureCoverageWarnings(cwd, slug, runCmd) {
134
+ const tool = buildTool(runCmd);
135
+ if (!tool) return [];
136
+ const out = [];
137
+ let contracts = [];
138
+ try { contracts = readAllContracts(scopesDir(cwd, slug), SCOPE_CONTRACT).map((x) => x.contract); } catch { return []; }
139
+ for (const c of contracts) {
140
+ const fixtures = Array.isArray(c.e2e_verification_fixtures) ? c.e2e_verification_fixtures : [];
141
+ if (!fixtures.length || fixtures.some((f) => String(f).includes(tool))) continue;
142
+ out.push(`scope ${c.scope_id}: none of its ${fixtures.length} fixture(s) invoke ${tool} (the ledger's build tool) — ` +
143
+ `its T0 green is not evidence the scope compiles; only this gate's run_cmd is.`);
144
+ }
145
+ return out;
146
+ }
147
+
148
+ /**
149
+ * Run one gate command and capture its outcome (10-minute timeout), output tails kept for the digest.
150
+ * @param {{kind:string, cmd:string}} step - The step to run.
151
+ * @param {string} cwd - Working directory.
152
+ * @returns {object} `{kind, cmd, exit, pass, stdout_tail, stderr_tail, error?}`.
153
+ */
154
+ export function runStep(step, cwd) {
155
+ const r = spawnSync(step.cmd, { shell: true, cwd, encoding: "utf8", timeout: 10 * 60 * 1000 });
156
+ const error = r.error ? String(r.error.message || r.error) : null;
157
+ return {
158
+ kind: step.kind, cmd: step.cmd,
159
+ exit: r.status ?? 1, pass: r.status === 0,
160
+ stdout_tail: tail(r.stdout), stderr_tail: tail(r.stderr),
161
+ ...(error ? { error } : {}),
162
+ };
163
+ }
164
+
165
+ /**
166
+ * Run the declared steps in order, stopping at the first failure — a probe over a build that did
167
+ * not complete answers nothing, and would only bury the real error under a second one.
168
+ *
169
+ * @param {Array<{kind:string, cmd:string}>} steps - From {@link declaredSteps}.
170
+ * @param {string} cwd - Working directory.
171
+ * @returns {{overall:("green"|"red"), steps:Array<object>}} Every declared step, the ones not
172
+ * reached marked `skipped: true`.
173
+ */
174
+ export function runGate(steps, cwd) {
175
+ const out = [];
176
+ let failed = false;
177
+ for (const step of steps) {
178
+ if (failed) { out.push({ kind: step.kind, cmd: step.cmd, skipped: true }); continue; }
179
+ const r = runStep(step, cwd);
180
+ out.push(r);
181
+ if (!r.pass) failed = true;
182
+ }
183
+ return { overall: failed ? "red" : "green", steps: out };
184
+ }
185
+
186
+ /**
187
+ * Every gate artifact for a round, oldest first.
188
+ * @param {string} cwd - Project root.
189
+ * @param {string} slug - Feature slug.
190
+ * @param {number} round - Round number.
191
+ * @returns {Array<{path:string, trial:number, body:object}>} Parsed artifacts; unreadable ones skipped.
192
+ */
193
+ export function roundBuildArtifacts(cwd, slug, round) {
194
+ const dir = roundBuildDir(cwd, slug);
195
+ let files;
196
+ try { files = readdirSync(dir); } catch { return []; }
197
+ const out = [];
198
+ for (const f of files) {
199
+ const m = f.match(/^r(\d+)-t(\d+)\.json$/);
200
+ if (!m || Number(m[1]) !== Number(round)) continue;
201
+ try { out.push({ path: join(dir, f), trial: Number(m[2]), body: JSON.parse(readFileSync(join(dir, f), "utf8")) }); }
202
+ catch { /* skip */ }
203
+ }
204
+ return out.sort((a, b) => a.trial - b.trial);
205
+ }
206
+
207
+ /**
208
+ * The gate's latest word on a round — the artifact readers branch on.
209
+ *
210
+ * Latest, because the gate may run again after a hand fix between launches, and the run must act on
211
+ * the current state of the build, not the first one recorded. Every earlier artifact stays on disk.
212
+ *
213
+ * @param {string} cwd - Project root.
214
+ * @param {string} slug - Feature slug.
215
+ * @param {number} round - Round number.
216
+ * @returns {(object|null)} The latest artifact body, or null when the gate never ran for this round.
217
+ */
218
+ export function latestRoundBuild(cwd, slug, round) {
219
+ const all = roundBuildArtifacts(cwd, slug, round);
220
+ return all.length ? all[all.length - 1].body : null;
221
+ }
222
+
223
+ /**
224
+ * The rounds whose latest gate artifact is red — the set `reduce hill` subtracts from.
225
+ * @param {string} cwd - Project root.
226
+ * @param {string} slug - Feature slug.
227
+ * @returns {Set<number>} Round numbers; empty when the gate never ran (non-regression: every
228
+ * T0 verdict then counts exactly as it did before the gate existed).
229
+ */
230
+ export function redBuildRounds(cwd, slug) {
231
+ const latest = new Map();
232
+ let files;
233
+ try { files = readdirSync(roundBuildDir(cwd, slug)); } catch { return new Set(); }
234
+ for (const f of files) {
235
+ const m = f.match(/^r(\d+)-t(\d+)\.json$/);
236
+ if (!m) continue;
237
+ const round = Number(m[1]), trial = Number(m[2]);
238
+ if (!latest.has(round) || latest.get(round).trial < trial) latest.set(round, { trial, file: f });
239
+ }
240
+ const red = new Set();
241
+ for (const [round, { file }] of latest) {
242
+ try {
243
+ if (JSON.parse(readFileSync(join(roundBuildDir(cwd, slug), file), "utf8")).overall === "red") red.add(round);
244
+ } catch { /* unreadable → not proven red */ }
245
+ }
246
+ return red;
247
+ }
248
+
249
+ /**
250
+ * Write the gate artifact immutably (`wx`, next ordinal on collision — the T0 convention).
251
+ * @param {string} cwd - Project root.
252
+ * @param {string} slug - Feature slug.
253
+ * @param {number} round - Round number.
254
+ * @param {object} body - Artifact fields.
255
+ * @returns {{path:string, sha256:string, trial:number}} Where it landed and its digest.
256
+ */
257
+ export function writeRoundBuild(cwd, slug, round, body) {
258
+ const dir = roundBuildDir(cwd, slug);
259
+ mkdirSync(dir, { recursive: true });
260
+ const existing = roundBuildArtifacts(cwd, slug, round);
261
+ for (let trial = (existing.length ? existing[existing.length - 1].trial : 0) + 1; ; trial++) {
262
+ const path = join(dir, `r${round}-t${trial}.json`);
263
+ const text = JSON.stringify({ schema_version: 1, round, trial, at: new Date().toISOString(), ...body }, null, 2);
264
+ try {
265
+ writeFileSync(path, text, { flag: "wx" });
266
+ return { path, sha256: createHash("sha256").update(text).digest("hex"), trial };
267
+ } catch (e) { if (e.code !== "EEXIST") throw e; }
268
+ }
269
+ }
270
+
271
+ export const ARGV_SPEC = {
272
+ usage: "harness.mjs verify build --slug <slug> --round <N> [--cwd <dir>]",
273
+ _: { arity: 0, max: 0, name: "(no positional operands)" },
274
+ slug: { type: "str", required: true },
275
+ round: { type: "int", min: 1, required: true },
276
+ cwd: { type: "path" },
277
+ };
278
+
279
+ /**
280
+ * Run the round build gate and write its artifact.
281
+ *
282
+ * @param {string[]} rawArgv - The subcommand's own arguments (harness.mjs strips the verb words).
283
+ * @returns {Promise<void>} Exits 0 green, 1 red, 3 nothing declared, 2 bad argv.
284
+ */
285
+ export async function cli(rawArgv) {
286
+ const args = runArgs(ARGV_SPEC, rawArgv);
287
+ const cwd = resolve(args.cwd || process.cwd());
288
+ const { slug, round } = args;
289
+ const { archetype, steps, warnings } = declaredSteps(cwd, slug);
290
+ for (const w of warnings) console.error(`build-gate: ${w}`);
291
+
292
+ if (steps.length === 0) {
293
+ console.log(JSON.stringify({ round, overall: "skipped", steps: [], warnings,
294
+ reason: "nothing declared — no run_cmd in the run ledger, no build_probe or launch_probe in project-profile.md" }, null, 2));
295
+ process.exit(3);
296
+ }
297
+
298
+ const gate = runGate(steps, cwd);
299
+ const failing = gate.steps.filter((s) => !s.skipped && !s.pass);
300
+ const discovered = failing.flatMap((s) => digest(`${s.stdout_tail}\n${s.stderr_tail}`));
301
+ const runId = runIdFromRoot(localRoot(cwd, slug));
302
+ const { path, sha256, trial } = writeRoundBuild(cwd, slug, round, {
303
+ ...(runId ? { run_id: runId } : {}),
304
+ archetype,
305
+ overall: gate.overall,
306
+ steps: gate.steps,
307
+ warnings,
308
+ discovered_tasks: discovered.slice(0, 16),
309
+ });
310
+
311
+ console.log(JSON.stringify({
312
+ path, sha256, trial, round, overall: gate.overall, warnings,
313
+ steps: gate.steps.map((s) => (s.skipped ? { kind: s.kind, skipped: true } : { kind: s.kind, exit: s.exit, pass: s.pass })),
314
+ ...(failing.length ? { failed_step: failing[0].kind, stderr_tail: failing[0].stderr_tail.slice(-1200) } : {}),
315
+ }, null, 2));
316
+ process.exit(gate.overall === "green" ? 0 : 1);
317
+ }
318
+
319
+ if (isMain(import.meta.url)) cli(process.argv.slice(2));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shapeup-sdlc",
3
- "version": "3.2.0",
3
+ "version": "3.4.0",
4
4
  "description": "Shape Up for coding agents \u2014 with gates the agent can't talk its way past. Harness for Claude Code.",
5
5
  "bin": {
6
6
  "shapeup-sdlc": "bin/init.mjs"