@mstar-harness/cli 3.10.3 → 3.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/mstar-harness.js +743 -85
  2. package/package.json +1 -1
@@ -4256,6 +4256,158 @@ async function registerPlanWorkflow(workflowId, options) {
4256
4256
  return { workflowId, snapshotPath, recovered: false };
4257
4257
  });
4258
4258
  }
4259
+ function iterationWorkflowRegistrationIdentity(snapshot) {
4260
+ const coordinator = snapshot.coordination?.coordinator;
4261
+ return stableJson({
4262
+ id: snapshot.id,
4263
+ type: snapshot.type,
4264
+ status: snapshot.status,
4265
+ compass_ref: snapshot.compass_ref ?? null,
4266
+ branch: snapshot.branch ?? null,
4267
+ project: snapshot.project ?? null,
4268
+ plans: snapshot.plans,
4269
+ coordinator: coordinator ? { session_id: coordinator.session_id, session_file: coordinator.session_file } : null
4270
+ });
4271
+ }
4272
+ async function registerIterationWorkflow(workflowId, options) {
4273
+ const refuse = (detail) => new Error(`registerIterationWorkflow: ${detail}`);
4274
+ if (typeof options !== "object" || options === null || Array.isArray(options)) {
4275
+ throw refuse("options must be an object (harnessDir, compassRef, branch, rows)");
4276
+ }
4277
+ if (typeof options.harnessDir !== "string" || options.harnessDir.trim() === "") {
4278
+ throw refuse("options.harnessDir is required (must contain status.json + workflows/)");
4279
+ }
4280
+ assertSafePathComponent(workflowId, "workflow id");
4281
+ if (typeof options.compassRef !== "string" || options.compassRef.trim() === "") {
4282
+ throw refuse("options.compassRef must be a non-empty string");
4283
+ }
4284
+ if (typeof options.branch !== "object" || options.branch === null || Array.isArray(options.branch)) {
4285
+ throw refuse("options.branch must be an object (base, integration, target)");
4286
+ }
4287
+ for (const anchor of ["base", "integration", "target"]) {
4288
+ const value = options.branch[anchor];
4289
+ if (typeof value !== "string" || value.trim() === "") {
4290
+ throw refuse(`options.branch.${anchor} must be a non-empty string`);
4291
+ }
4292
+ }
4293
+ if (options.project !== undefined && (typeof options.project !== "string" || options.project.trim() === "")) {
4294
+ throw refuse("options.project must be a non-empty string when given");
4295
+ }
4296
+ const rows = options.rows;
4297
+ if (!Array.isArray(rows) || rows.length === 0) {
4298
+ throw refuse("options.rows must be a non-empty array of { id, title, file }");
4299
+ }
4300
+ const seenRowIds = new Set;
4301
+ for (const row of rows) {
4302
+ if (typeof row !== "object" || row === null || Array.isArray(row)) {
4303
+ throw refuse("each row must be an object ({ id, title, file })");
4304
+ }
4305
+ for (const field of ["id", "title", "file"]) {
4306
+ if (typeof row[field] !== "string" || row[field].trim() === "") {
4307
+ throw refuse(`each row.${field} must be a non-empty string`);
4308
+ }
4309
+ }
4310
+ if ("status" in row) {
4311
+ throw refuse(`row ${JSON.stringify(row.id)} supplies a status \u2014 rows are always written status "Todo"; ` + "a state transition is requested through the lifecycle seams, never at registration");
4312
+ }
4313
+ if (seenRowIds.has(row.id)) {
4314
+ throw refuse(`duplicate row id ${JSON.stringify(row.id)} \u2014 plan row ids are unique per workflow`);
4315
+ }
4316
+ seenRowIds.add(row.id);
4317
+ }
4318
+ const startedAt = options.startedAt ?? new Date().toISOString();
4319
+ if (!isCloseTimestamp(startedAt)) {
4320
+ throw refuse("options.startedAt must be a valid YYYY-MM-DD date or RFC3339 timestamp");
4321
+ }
4322
+ const harnessDir = resolve6(options.harnessDir);
4323
+ const statusPath = join6(harnessDir, "status.json");
4324
+ const workflowDir = join6(harnessDir, "workflows", workflowId);
4325
+ const snapshotPath = join6(workflowDir, WORKFLOW_SNAPSHOT_FILE);
4326
+ const store = getArtifactStore();
4327
+ const snapshot = {
4328
+ schema_version: 1,
4329
+ id: workflowId,
4330
+ type: "iteration",
4331
+ status: "running",
4332
+ started_at: startedAt,
4333
+ updated_at: startedAt.slice(0, 10),
4334
+ compass_ref: options.compassRef,
4335
+ branch: { base: options.branch.base, integration: options.branch.integration, target: options.branch.target },
4336
+ plans: rows.map((r) => ({
4337
+ id: r.id,
4338
+ title: r.title,
4339
+ file: r.file,
4340
+ status: "Todo",
4341
+ metadata: {
4342
+ iteration_refs: [options.compassRef],
4343
+ spec_integration_branch: options.branch.integration,
4344
+ merge_target: options.branch.integration
4345
+ }
4346
+ }))
4347
+ };
4348
+ if (options.project !== undefined)
4349
+ snapshot.project = options.project;
4350
+ const entry = {
4351
+ id: workflowId,
4352
+ type: "iteration",
4353
+ started_at: snapshot.started_at,
4354
+ dir: `workflows/${workflowId}`
4355
+ };
4356
+ const entryGate = validateWorkflowEntry(entry);
4357
+ if (!entryGate.ok) {
4358
+ throw new Error(`refusing to register invalid workflow entry: ${entryGate.violations.map((v) => v.message).join("; ")}`);
4359
+ }
4360
+ return withStatusWriteLock(statusPath, async () => {
4361
+ const rootDoc = readJson(statusPath);
4362
+ const workflows = Array.isArray(rootDoc.workflows) ? rootDoc.workflows : [];
4363
+ if (workflows.some((candidate) => isPlainObject2(candidate) && candidate.id === workflowId)) {
4364
+ throw new Error(`refusing to register workflow ${JSON.stringify(workflowId)}: it is already registered (root entry in ${statusPath}) \u2014 registration is create-only; ` + "remove that workflow before registering again");
4365
+ }
4366
+ if (existsSync4(snapshotPath)) {
4367
+ const existing = readWorkflowSnapshot(workflowDir);
4368
+ if (existing.snapshot.id !== workflowId || iterationWorkflowRegistrationIdentity(existing.snapshot) !== iterationWorkflowRegistrationIdentity(snapshot)) {
4369
+ throw new Error(`refusing to register workflow ${JSON.stringify(workflowId)}: snapshot ${snapshotPath} already exists ` + "with a different registration identity \u2014 remove that workflow or register under a different id");
4370
+ }
4371
+ const recoveryEntry = {
4372
+ id: workflowId,
4373
+ type: "iteration",
4374
+ started_at: existing.snapshot.started_at,
4375
+ dir: `workflows/${workflowId}`
4376
+ };
4377
+ const recoveryGate = validateWorkflowEntry(recoveryEntry);
4378
+ if (!recoveryGate.ok) {
4379
+ throw new Error(`refusing to register invalid workflow entry: ${recoveryGate.violations.map((v) => v.message).join("; ")}`);
4380
+ }
4381
+ await registerWorkflowEntryLocked(statusPath, recoveryEntry);
4382
+ return { workflowId, snapshotPath, recovered: true };
4383
+ }
4384
+ let createdVersion;
4385
+ try {
4386
+ await writeWorkflowSnapshot(snapshot, workflowDir, { createOnly: true });
4387
+ createdVersion = readArtifactBytes(snapshotPath)?.version;
4388
+ await registerWorkflowEntryLocked(statusPath, entry);
4389
+ } catch (error) {
4390
+ if (createdVersion !== undefined) {
4391
+ await withStatusWriteLock(snapshotPath, async () => {
4392
+ const current = readArtifactBytes(snapshotPath);
4393
+ if (current === undefined || current.version !== createdVersion)
4394
+ return;
4395
+ const remove = store.delete?.bind(store);
4396
+ if (remove !== undefined) {
4397
+ await withProtectedWrite(snapshotPath, "delete", () => remove({ kind: "snapshot", key: workflowId }));
4398
+ }
4399
+ });
4400
+ }
4401
+ try {
4402
+ if (readdirSync2(workflowDir).length === 0) {
4403
+ rmdirSync2(workflowDir);
4404
+ }
4405
+ } catch {}
4406
+ throw error;
4407
+ }
4408
+ return { workflowId, snapshotPath, recovered: false };
4409
+ });
4410
+ }
4259
4411
  var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
4260
4412
  function rowPlanIds(row) {
4261
4413
  if (!isPlainObject2(row))
@@ -7611,6 +7763,176 @@ function slugify(title) {
7611
7763
  }
7612
7764
  var escapeCell = (value) => value.replace(/\|/g, "\\|");
7613
7765
  var truncate = (value, max) => value.length > max ? `${value.slice(0, max)}\u2026` : value;
7766
+ var collapseEvidenceWs = (value) => value.replace(/\s*[\r\n]\s*/g, " ");
7767
+ var evidenceText = (item) => typeof item === "string" ? item : `${item.file}${item.line !== undefined ? `:${item.line}` : ""} \u2014 ${item.description}`;
7768
+ var hasEnrichedMetadata = (finding) => finding.fingerprint !== undefined || finding.trace !== undefined || finding.severity !== undefined || finding.evidence.some((item) => typeof item !== "string");
7769
+ var AUDIT_FINGERPRINT_RE = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]*(?![\s\S])/;
7770
+ var AUDIT_SEVERITY_ORDER = { informational: 0, low: 1, medium: 2, high: 3, critical: 4 };
7771
+ var DEFAULT_IGNORABLE_RE = /[\u00AD\u034F\u061C\u115F\u1160\u17B4\u17B5\u180B-\u180F\u200B-\u200F\u202A-\u202E\u2060-\u206F\u3164\uFE00-\uFE0F\uFEFF\uFFA0\uFFF0-\uFFF8\u{1BCA0}-\u{1BCA3}\u{1D173}-\u{1D17A}\u{E0000}-\u{E0FFF}]/u;
7772
+ var LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
7773
+ var isPlainObject9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7774
+ function isVisibleText(value) {
7775
+ if (LONE_SURROGATE_RE.test(value))
7776
+ return false;
7777
+ for (const ch of value) {
7778
+ if (!/\p{White_Space}/u.test(ch) && !DEFAULT_IGNORABLE_RE.test(ch))
7779
+ return true;
7780
+ }
7781
+ return false;
7782
+ }
7783
+ function safeAuditPath(value) {
7784
+ if (typeof value !== "string")
7785
+ return false;
7786
+ if (value === "")
7787
+ return false;
7788
+ if (value.includes("\\"))
7789
+ return false;
7790
+ if (/[\u0000-\u001F\u007F-\u009F]/.test(value))
7791
+ return false;
7792
+ if (LONE_SURROGATE_RE.test(value))
7793
+ return false;
7794
+ if (value.startsWith("/"))
7795
+ return false;
7796
+ if (/^[A-Za-z]:/.test(value))
7797
+ return false;
7798
+ for (const segment of value.split("/")) {
7799
+ if (segment === "" || segment === "." || segment === "..")
7800
+ return false;
7801
+ if (segment.endsWith(".") || segment.endsWith(" "))
7802
+ return false;
7803
+ }
7804
+ return true;
7805
+ }
7806
+ function validateAuditFindingGates(findings) {
7807
+ const violations = [];
7808
+ const seen = new Map;
7809
+ let previousFingerprint;
7810
+ if (!Array.isArray(findings)) {
7811
+ violations.push(violation10("high", "audit.finding.shape", "findings \u2014 audit.finding.shape"));
7812
+ return { ok: false, violations };
7813
+ }
7814
+ findings.forEach((finding, index) => {
7815
+ const at = (field) => `findings[${index}].${field}`;
7816
+ const push = (code, field) => {
7817
+ violations.push(violation10("high", code, `${at(field)} \u2014 ${code}`));
7818
+ };
7819
+ if (!isPlainObject9(finding)) {
7820
+ violations.push(violation10("high", "audit.finding.shape", `findings[${index}] \u2014 audit.finding.shape`));
7821
+ return;
7822
+ }
7823
+ if (finding.fingerprint !== undefined) {
7824
+ const fingerprint = finding.fingerprint;
7825
+ if (typeof fingerprint !== "string" || !AUDIT_FINGERPRINT_RE.test(fingerprint))
7826
+ push("audit.finding.fingerprint.grammar", "fingerprint");
7827
+ else if (redactSecrets(fingerprint).text !== fingerprint)
7828
+ push("audit.finding.fingerprint.secret", "fingerprint");
7829
+ else {
7830
+ const firstAt = seen.get(fingerprint);
7831
+ if (firstAt !== undefined)
7832
+ push("audit.finding.fingerprint.duplicate", "fingerprint");
7833
+ else
7834
+ seen.set(fingerprint, index);
7835
+ if (previousFingerprint !== undefined && fingerprint < previousFingerprint) {
7836
+ push("audit.finding.fingerprint.order", "fingerprint");
7837
+ }
7838
+ previousFingerprint = fingerprint;
7839
+ }
7840
+ }
7841
+ if (finding.severity !== undefined) {
7842
+ if (!isPlainObject9(finding.severity)) {
7843
+ push("audit.finding.severity.shape", "severity");
7844
+ } else {
7845
+ const { likelihood, impact, overall } = finding.severity;
7846
+ const rankOf = (r) => AUDIT_SEVERITY_ORDER[r];
7847
+ for (const [field, value] of [
7848
+ ["likelihood", likelihood],
7849
+ ["impact", impact],
7850
+ ["overall", overall]
7851
+ ]) {
7852
+ if (rankOf(value) === undefined)
7853
+ push("audit.finding.severity.rank", `severity.${field}`);
7854
+ }
7855
+ const impactRank = rankOf(impact);
7856
+ const overallRank = rankOf(overall);
7857
+ if (impactRank !== undefined && overallRank !== undefined && overallRank > impactRank) {
7858
+ push("audit.finding.severity.overall-exceeds-impact", "severity.overall");
7859
+ }
7860
+ }
7861
+ }
7862
+ const textViolation = (field, value) => {
7863
+ if (value === undefined)
7864
+ return;
7865
+ if (typeof value !== "string")
7866
+ push("audit.finding.text.type", field);
7867
+ else if (LONE_SURROGATE_RE.test(value))
7868
+ push("audit.finding.text.surrogate", field);
7869
+ else if (!isVisibleText(value))
7870
+ push("audit.finding.text.invisible", field);
7871
+ };
7872
+ if (finding.trace !== undefined) {
7873
+ if (!Array.isArray(finding.trace))
7874
+ push("audit.finding.trace.shape", "trace");
7875
+ else if (finding.trace.length === 0)
7876
+ push("audit.finding.trace.empty", "trace");
7877
+ else {
7878
+ const kinds = finding.trace.map((s) => isPlainObject9(s) ? s.kind : undefined);
7879
+ const topologyOk = finding.trace.length === 1 ? kinds[0] === "entrypoint" || kinds[0] === "sink" : kinds[0] === "entrypoint" && kinds[kinds.length - 1] === "sink" && kinds.slice(1, -1).every((k) => k === "propagation");
7880
+ if (!topologyOk)
7881
+ push("audit.finding.trace.topology", "trace");
7882
+ finding.trace.forEach((step, stepIndex) => {
7883
+ const stepAt = `trace[${stepIndex}]`;
7884
+ if (!isPlainObject9(step)) {
7885
+ push("audit.finding.trace.shape", stepAt);
7886
+ return;
7887
+ }
7888
+ if (typeof step.line !== "number" || !Number.isSafeInteger(step.line) || step.line <= 0) {
7889
+ push("audit.finding.trace.line", `${stepAt}.line`);
7890
+ }
7891
+ const stepFile = step.file;
7892
+ if (typeof stepFile !== "string" || !safeAuditPath(stepFile))
7893
+ push("audit.finding.path.unsafe", `${stepAt}.file`);
7894
+ else if (redactSecrets(stepFile).text !== stepFile)
7895
+ push("audit.finding.path.secret", `${stepAt}.file`);
7896
+ if (step.scope === undefined)
7897
+ push("audit.finding.trace.shape", `${stepAt}.scope`);
7898
+ else
7899
+ textViolation(`${stepAt}.scope`, step.scope);
7900
+ if (step.description === undefined)
7901
+ push("audit.finding.trace.shape", `${stepAt}.description`);
7902
+ else
7903
+ textViolation(`${stepAt}.description`, step.description);
7904
+ });
7905
+ }
7906
+ }
7907
+ if (!Array.isArray(finding.evidence))
7908
+ push("audit.finding.evidence.shape", "evidence");
7909
+ else
7910
+ finding.evidence.forEach((item, itemIndex) => {
7911
+ if (typeof item === "string") {
7912
+ textViolation(`evidence[${itemIndex}]`, item);
7913
+ return;
7914
+ }
7915
+ if (!isPlainObject9(item)) {
7916
+ push("audit.finding.evidence.shape", `evidence[${itemIndex}]`);
7917
+ return;
7918
+ }
7919
+ const itemFile = item.file;
7920
+ if (typeof itemFile !== "string" || !safeAuditPath(itemFile))
7921
+ push("audit.finding.path.unsafe", `evidence[${itemIndex}].file`);
7922
+ else if (redactSecrets(itemFile).text !== itemFile)
7923
+ push("audit.finding.path.secret", `evidence[${itemIndex}].file`);
7924
+ if (item.line !== undefined && (typeof item.line !== "number" || !Number.isSafeInteger(item.line) || item.line <= 0)) {
7925
+ push("audit.finding.evidence.line", `evidence[${itemIndex}].line`);
7926
+ }
7927
+ textViolation(`evidence[${itemIndex}].description`, item.description);
7928
+ });
7929
+ textViolation("title", finding.title);
7930
+ textViolation("impact", finding.impact);
7931
+ textViolation("fixSketch", finding.fixSketch);
7932
+ textViolation("verification", finding.verification);
7933
+ });
7934
+ return { ok: violations.length === 0, violations };
7935
+ }
7614
7936
  function renderPlanFile(finding, plannedAt) {
7615
7937
  const sections = [
7616
7938
  `# ${finding.title}`,
@@ -7619,15 +7941,22 @@ function renderPlanFile(finding, plannedAt) {
7619
7941
  `- **Priority**: ${finding.priority}`,
7620
7942
  `- **Effort**: ${finding.effort}`,
7621
7943
  `- **Risk**: ${finding.risk}`,
7944
+ ...finding.confidence !== "MED" || hasEnrichedMetadata(finding) ? [`- **Confidence**: ${finding.confidence}`] : [],
7945
+ ...finding.fingerprint !== undefined ? [`- **Fingerprint**: ${finding.fingerprint}`] : [],
7946
+ ...finding.severity !== undefined ? [`- **Likelihood**: ${finding.severity.likelihood}`, `- **Severity impact**: ${finding.severity.impact}`, `- **Severity**: ${finding.severity.overall}`] : [],
7622
7947
  `- **Depends on**: ${finding.dependsOn ?? "none"}`,
7623
7948
  `- **Category**: ${finding.category}`,
7949
+ ...finding.evidence.length > 0 ? [`- **Evidence**: ${collapseEvidenceWs(evidenceText(finding.evidence[0]))}`] : [],
7624
7950
  `- **Planned at**: commit \`${plannedAt.commit}\`, ${plannedAt.date}`,
7625
7951
  "",
7626
7952
  "## Impact",
7627
7953
  finding.impact
7628
7954
  ];
7629
7955
  if (finding.evidence.length > 0) {
7630
- sections.push("", "## Evidence", ...finding.evidence.map((e) => `- ${e}`));
7956
+ sections.push("", "## Evidence", ...finding.evidence.map((item) => `- ${evidenceText(item)}`));
7957
+ }
7958
+ if (finding.trace !== undefined) {
7959
+ sections.push("", "## Trace", "", "| Kind | Location | Scope / Description |", "|------|----------|---------------------|", ...finding.trace.map((step) => `| ${escapeCell(step.kind)} | ${escapeCell(`${step.file}:${step.line}`)} | ${escapeCell(`${step.scope} \u2014 ${step.description}`).replace(/\r\n|\r|\n/g, "\\n")} |`));
7631
7960
  }
7632
7961
  if (finding.fixSketch !== undefined) {
7633
7962
  sections.push("", "## Fix sketch", finding.fixSketch);
@@ -7647,7 +7976,8 @@ function redactFinding(finding) {
7647
7976
  ...finding,
7648
7977
  title: redactText(finding.title),
7649
7978
  impact: redactText(finding.impact),
7650
- evidence: finding.evidence.map(redactText),
7979
+ evidence: finding.evidence.map((item) => typeof item === "string" ? redactText(item) : { ...item, description: redactText(item.description) }),
7980
+ ...finding.trace !== undefined ? { trace: finding.trace.map((step) => ({ ...step, scope: redactText(step.scope), description: redactText(step.description) })) } : {},
7651
7981
  ...finding.fixSketch !== undefined ? { fixSketch: redactText(finding.fixSketch) } : {},
7652
7982
  ...finding.verification !== undefined ? { verification: redactText(finding.verification) } : {}
7653
7983
  };
@@ -7669,7 +7999,10 @@ function extractSecurityDispositionSections(text) {
7669
7999
  }
7670
8000
  function renderIndex(params) {
7671
8001
  const { date, repoName, repoShortSha, rows, rejected, needsVerification, hardeningChecked } = params;
7672
- const findingsRows = rows.map((r) => `| ${r.num} | ${escapeCell(r.title)} | ${r.category} | ${escapeCell(truncate(r.impact, 80))} | ${r.effort} | ${r.risk} | ${r.confidence} | ${escapeCell(truncate(r.evidence, 80))} |`).join(`
8002
+ const showFingerprint = rows.some((r) => r.fingerprint !== undefined);
8003
+ const showSeverity = rows.some((r) => r.likelihood !== undefined || r.severityImpact !== undefined || r.severity !== undefined);
8004
+ const cell = (value) => escapeCell(value ?? "\u2014");
8005
+ const findingsRows = rows.map((r) => `| ${r.num} | ${escapeCell(r.title)} | ${r.category} | ${escapeCell(truncate(r.impact, 80))} | ${r.effort} | ${r.risk} | ${r.confidence} | ${escapeCell(truncate(r.evidence, 80))}` + (showFingerprint ? ` | ${cell(r.fingerprint)}` : "") + (showSeverity ? ` | ${cell(r.likelihood)} | ${cell(r.severityImpact)} | ${cell(r.severity)}` : "") + " |").join(`
7673
8006
  `);
7674
8007
  const directionRows = rows.filter((r) => r.category === "direction").map((r) => `- ${escapeCell(r.title)} \u2014 ${escapeCell(truncate(r.impact, 120))}`).join(`
7675
8008
  `);
@@ -7682,8 +8015,8 @@ function renderIndex(params) {
7682
8015
  "",
7683
8016
  "## Findings",
7684
8017
  "",
7685
- "| # | Finding | Category | Impact | Effort | Risk | Confidence | Evidence |",
7686
- "|---|---------|----------|--------|--------|------|------------|----------|",
8018
+ "| # | Finding | Category | Impact | Effort | Risk | Confidence | Evidence" + (showFingerprint ? " | Fingerprint" : "") + (showSeverity ? " | Likelihood | Severity impact | Severity" : "") + " |",
8019
+ "|---|---------|----------|--------|--------|------|------------|----------" + (showFingerprint ? "|------------" : "") + (showSeverity ? "|------------|-----------------|----------" : "") + "|",
7687
8020
  findingsRows
7688
8021
  ];
7689
8022
  if (directionRows !== "") {
@@ -7707,6 +8040,11 @@ function renderIndex(params) {
7707
8040
  function scaffoldAuditPlan(outDir, findings, options = {}) {
7708
8041
  const date = options.date ?? new Date().toISOString().slice(0, 10);
7709
8042
  const plannedAt = options.plannedAt ?? { commit: options.repoShortSha ?? "unknown", date };
8043
+ const gate2 = validateAuditFindingGates(findings);
8044
+ if (!gate2.ok) {
8045
+ const first = gate2.violations[0];
8046
+ throw new TypeError(`invalid audit findings \u2014 ${first.code}: ${first.message}`);
8047
+ }
7710
8048
  mkdirSync8(outDir, { recursive: true });
7711
8049
  const existingReadme = join16(outDir, "README.md");
7712
8050
  const carried = existsSync12(existingReadme) ? extractSecurityDispositionSections(readFileSync11(existingReadme, "utf8")) : { needsVerification: [], hardeningChecked: [] };
@@ -7741,10 +8079,14 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7741
8079
  impact: "see plan file",
7742
8080
  effort: fields.get("Effort") ?? "\u2014",
7743
8081
  risk: fields.get("Risk") ?? "\u2014",
7744
- confidence: "\u2014",
8082
+ confidence: fields.get("Confidence") ?? "\u2014",
7745
8083
  evidence: fields.get("Evidence") ?? "\u2014",
7746
8084
  priority: fields.get("Priority") ?? "\u2014",
7747
- dependsOn: fields.get("Depends on") ?? "\u2014"
8085
+ dependsOn: fields.get("Depends on") ?? "\u2014",
8086
+ fingerprint: fields.get("Fingerprint"),
8087
+ likelihood: fields.get("Likelihood"),
8088
+ severityImpact: fields.get("Severity impact"),
8089
+ severity: fields.get("Severity")
7748
8090
  };
7749
8091
  });
7750
8092
  const byNum = new Map(rows.map((r) => [r.num, r]));
@@ -7759,9 +8101,13 @@ function scaffoldAuditPlan(outDir, findings, options = {}) {
7759
8101
  row.effort = finding.effort;
7760
8102
  row.risk = finding.risk;
7761
8103
  row.confidence = finding.confidence;
7762
- row.evidence = finding.evidence[0] ?? "";
8104
+ row.evidence = finding.evidence.length > 0 ? collapseEvidenceWs(evidenceText(finding.evidence[0])) : "";
7763
8105
  row.priority = finding.priority;
7764
8106
  row.dependsOn = finding.dependsOn ?? "none";
8107
+ row.fingerprint = finding.fingerprint;
8108
+ row.likelihood = finding.severity?.likelihood;
8109
+ row.severityImpact = finding.severity?.impact;
8110
+ row.severity = finding.severity?.overall;
7765
8111
  }
7766
8112
  });
7767
8113
  const needsVerificationLines = options.needsVerification !== undefined ? options.needsVerification.map((nv) => `- ${escapeCell(redactText(nv.lead))}: ${escapeCell(redactText(nv.how))}${nv.evidence ? ` (${escapeCell(redactText(nv.evidence))})` : ""}`) : carried.needsVerification;
@@ -8886,7 +9232,7 @@ must-fix=${mustFix} should-fix=${shouldFix} nit=${nit} unverified=${unverified}`
8886
9232
  var REVIEW_SCHEMA_ID = "mstar.review/v1";
8887
9233
  var INSPECTOR_VERDICTS = ["comment", "request_changes", "approve"];
8888
9234
  var INSPECTOR_SEVERITIES = ["critical", "warning", "suggestion", "info"];
8889
- function isPlainObject9(value) {
9235
+ function isPlainObject10(value) {
8890
9236
  return typeof value === "object" && value !== null && !Array.isArray(value);
8891
9237
  }
8892
9238
  var TALLY_COUNT_KEYS = ["mustFix", "shouldFix", "nit", "unverified"];
@@ -8897,7 +9243,7 @@ function checkProvidedTallyShape(tally, violations) {
8897
9243
  if (typeof tally.scorePct !== "number" || !Number.isInteger(tally.scorePct) || tally.scorePct < 0 || tally.scorePct > 100) {
8898
9244
  violations.push(violation15("high", "review.tally-malformed", `tally.scorePct must be an integer in [0, 100] - got ${String(tally.scorePct)}`));
8899
9245
  }
8900
- if (!isPlainObject9(tally.tally)) {
9246
+ if (!isPlainObject10(tally.tally)) {
8901
9247
  violations.push(violation15("high", "review.tally-malformed", "tally.tally must be an object carrying the four class counts"));
8902
9248
  } else {
8903
9249
  for (const key of TALLY_COUNT_KEYS) {
@@ -8913,7 +9259,7 @@ function checkProvidedTallyShape(tally, violations) {
8913
9259
  }
8914
9260
  function validateMstarReviewV1(doc) {
8915
9261
  const violations = [];
8916
- if (!isPlainObject9(doc)) {
9262
+ if (!isPlainObject10(doc)) {
8917
9263
  return {
8918
9264
  ok: false,
8919
9265
  violations: [violation15("high", "review.not-object", "review document must be a JSON object")]
@@ -8940,7 +9286,7 @@ function validateMstarReviewV1(doc) {
8940
9286
  violations.push(violation15("high", "review.findings-not-array", "findings must be an array"));
8941
9287
  } else {
8942
9288
  doc.findings.forEach((finding, index) => {
8943
- if (!isPlainObject9(finding)) {
9289
+ if (!isPlainObject10(finding)) {
8944
9290
  violations.push(violation15("high", "review.invalid-finding", `findings[${index}] must be an object`));
8945
9291
  return;
8946
9292
  }
@@ -8980,7 +9326,7 @@ function validateMstarReviewV1(doc) {
8980
9326
  });
8981
9327
  }
8982
9328
  if (doc.tally !== undefined) {
8983
- if (!isPlainObject9(doc.tally)) {
9329
+ if (!isPlainObject10(doc.tally)) {
8984
9330
  violations.push(violation15("high", "review.invalid-tally", "tally must be a PrTallyResult object"));
8985
9331
  } else {
8986
9332
  checkProvidedTallyShape(doc.tally, violations);
@@ -8990,7 +9336,7 @@ function validateMstarReviewV1(doc) {
8990
9336
  }
8991
9337
  }
8992
9338
  if (doc.target !== undefined) {
8993
- if (!isPlainObject9(doc.target)) {
9339
+ if (!isPlainObject10(doc.target)) {
8994
9340
  violations.push(violation15("high", "review.invalid-target", "target must be an object"));
8995
9341
  } else {
8996
9342
  if (doc.target.owner !== undefined && typeof doc.target.owner !== "string") {
@@ -19255,7 +19601,7 @@ function usageError(message) {
19255
19601
  function gateError(message) {
19256
19602
  return new SddScriptError2(message, 1);
19257
19603
  }
19258
- function isPlainObject10(value) {
19604
+ function isPlainObject11(value) {
19259
19605
  return typeof value === "object" && value !== null && !Array.isArray(value);
19260
19606
  }
19261
19607
  function isIdLike2(value) {
@@ -19339,7 +19685,7 @@ function validateArgvUsage(argv) {
19339
19685
  }
19340
19686
  }
19341
19687
  function validateCoverageUsage(coverage) {
19342
- if (!isPlainObject10(coverage))
19688
+ if (!isPlainObject11(coverage))
19343
19689
  throw usageError("evidence capture request.coverage must be a JSON object");
19344
19690
  const acIds = coverage.acIds;
19345
19691
  if (!Array.isArray(acIds) || acIds.length === 0 || acIds.length > MAX_AC_IDS2) {
@@ -19369,7 +19715,7 @@ function validateInputSpecsUsage(inputs) {
19369
19715
  const seen = new Set;
19370
19716
  const paths = [];
19371
19717
  for (const spec of inputs) {
19372
- if (!isPlainObject10(spec))
19718
+ if (!isPlainObject11(spec))
19373
19719
  throw usageError("evidence capture request.inputs entries must be JSON objects");
19374
19720
  if (!isInputSpecPath2(spec.path)) {
19375
19721
  throw usageError(`evidence capture request.inputs path must be a nonempty POSIX repo-relative path without absolute, backslash, dot, dot-dot or glob components; got ${JSON.stringify(spec.path ?? null)}`);
@@ -19397,7 +19743,7 @@ function validateInputSpecsUsage(inputs) {
19397
19743
  return inputs;
19398
19744
  }
19399
19745
  function validateRequestUsage(request) {
19400
- if (!isPlainObject10(request))
19746
+ if (!isPlainObject11(request))
19401
19747
  throw usageError("evidence capture request must be a JSON object");
19402
19748
  for (const key of Object.keys(request)) {
19403
19749
  if (!REQUEST_KEYS.includes(key)) {
@@ -19405,7 +19751,7 @@ function validateRequestUsage(request) {
19405
19751
  }
19406
19752
  }
19407
19753
  const context = request.context;
19408
- if (!isPlainObject10(context))
19754
+ if (!isPlainObject11(context))
19409
19755
  throw usageError("evidence capture request.context must be a JSON object");
19410
19756
  if (typeof context.planId !== "string" || context.planId.length === 0 || !SAFE_COMPONENT_RE.test(context.planId)) {
19411
19757
  throw usageError("evidence capture request.context.planId must be a single safe path component");
@@ -19457,7 +19803,7 @@ function validateCollectorOptions(options) {
19457
19803
  throw fail(`environmentKeys must be unique members of ${ENVIRONMENT_KEYS2.join("/")}`);
19458
19804
  }
19459
19805
  const limits = options.limits;
19460
- if (!isPlainObject10(limits))
19806
+ if (!isPlainObject11(limits))
19461
19807
  throw fail("limits must be a JSON object");
19462
19808
  const ceilings = [
19463
19809
  ["timeoutMs", TIMEOUT_MIN_MS2, TIMEOUT_MAX_MS2],
@@ -20430,7 +20776,7 @@ function loadJsonFileUsage(pathValue, what) {
20430
20776
  } catch (error) {
20431
20777
  throw usageError(`${what} file is not valid JSON: ${pathValue} (${error.message})`);
20432
20778
  }
20433
- if (!isPlainObject10(doc))
20779
+ if (!isPlainObject11(doc))
20434
20780
  throw usageError(`${what} file must contain a JSON object: ${pathValue}`);
20435
20781
  return doc;
20436
20782
  }
@@ -20499,10 +20845,10 @@ async function runEvidenceVerify(invocation) {
20499
20845
  }
20500
20846
  return ioFailureAssessment(`evidence record unreadable: ${error.message}`);
20501
20847
  }
20502
- if (isPlainObject10(record)) {
20848
+ if (isPlainObject11(record)) {
20503
20849
  const request = record.request;
20504
- const context = isPlainObject10(request) ? request.context : null;
20505
- const controlRoot = isPlainObject10(context) && typeof context.controlHarnessRoot === "string" ? context.controlHarnessRoot : null;
20850
+ const context = isPlainObject11(request) ? request.context : null;
20851
+ const controlRoot = isPlainObject11(context) && typeof context.controlHarnessRoot === "string" ? context.controlHarnessRoot : null;
20506
20852
  if (controlRoot !== null && dirname10(dirname10(canonicalSddDir)) !== controlRoot) {
20507
20853
  throw usageError(`${VERIFY_USAGE}
20508
20854
  --sdd-dir ${canonicalSddDir} is not under the canonical control root recorded in the record context (${controlRoot}); a relocated or copied evidence bundle is refused`);
@@ -21295,7 +21641,7 @@ function describeType(value) {
21295
21641
  return "array";
21296
21642
  return typeof value;
21297
21643
  }
21298
- function isPlainObject11(value) {
21644
+ function isPlainObject13(value) {
21299
21645
  return typeof value === "object" && value !== null && !Array.isArray(value);
21300
21646
  }
21301
21647
  function parseScalar3(raw) {
@@ -21339,7 +21685,7 @@ function isValidMcpUrl(raw) {
21339
21685
  return true;
21340
21686
  }
21341
21687
  function validateManifest(manifest, errors2, warnings) {
21342
- if (!isPlainObject11(manifest)) {
21688
+ if (!isPlainObject13(manifest)) {
21343
21689
  errors2.push("plugin.json: manifest must be a JSON object");
21344
21690
  return;
21345
21691
  }
@@ -21375,7 +21721,7 @@ function validateManifest(manifest, errors2, warnings) {
21375
21721
  }
21376
21722
  }
21377
21723
  if (doc.author !== undefined) {
21378
- if (!isPlainObject11(doc.author)) {
21724
+ if (!isPlainObject13(doc.author)) {
21379
21725
  errors2.push('plugin.json: "author" must be an object with optional string fields name/email/url');
21380
21726
  } else {
21381
21727
  const author = doc.author;
@@ -21398,11 +21744,11 @@ function validateManifest(manifest, errors2, warnings) {
21398
21744
  }
21399
21745
  }
21400
21746
  if (doc.extensions !== undefined) {
21401
- if (!isPlainObject11(doc.extensions)) {
21747
+ if (!isPlainObject13(doc.extensions)) {
21402
21748
  warnings.push('plugin.json: "extensions" is not an object \u2014 ignored');
21403
21749
  } else {
21404
21750
  for (const [namespace, value] of Object.entries(doc.extensions)) {
21405
- if (!isPlainObject11(value)) {
21751
+ if (!isPlainObject13(value)) {
21406
21752
  warnings.push(`plugin.json: "extensions.${namespace}" is not an object \u2014 ignored`);
21407
21753
  }
21408
21754
  }
@@ -21411,7 +21757,7 @@ function validateManifest(manifest, errors2, warnings) {
21411
21757
  }
21412
21758
  function validateMcpServer(name, entry, errors2) {
21413
21759
  const prefix = `mcp.json: mcpServers.${name}`;
21414
- if (!isPlainObject11(entry)) {
21760
+ if (!isPlainObject13(entry)) {
21415
21761
  errors2.push(`${prefix} must be an object`);
21416
21762
  return;
21417
21763
  }
@@ -21445,7 +21791,7 @@ function validateMcpServer(name, entry, errors2) {
21445
21791
  }
21446
21792
  }
21447
21793
  if (server.env !== undefined) {
21448
- if (!isPlainObject11(server.env)) {
21794
+ if (!isPlainObject13(server.env)) {
21449
21795
  errors2.push(`${prefix}: "env" must be an object of strings`);
21450
21796
  } else {
21451
21797
  for (const [key, value] of Object.entries(server.env)) {
@@ -21484,7 +21830,7 @@ function validateMcpServer(name, entry, errors2) {
21484
21830
  errors2.push(`${prefix}: "url" must be an absolute http(s) URL without user info or fragment; non-loopback endpoints must use https`);
21485
21831
  }
21486
21832
  if (server.headers !== undefined) {
21487
- if (!isPlainObject11(server.headers)) {
21833
+ if (!isPlainObject13(server.headers)) {
21488
21834
  errors2.push(`${prefix}: "headers" must be an object of strings`);
21489
21835
  } else {
21490
21836
  const seen = new Set;
@@ -21521,7 +21867,7 @@ function validateMcp(root, manifestSchema, errors2) {
21521
21867
  errors2.push(`mcp.json: ${error.message}`);
21522
21868
  return;
21523
21869
  }
21524
- if (!isPlainObject11(parsed)) {
21870
+ if (!isPlainObject13(parsed)) {
21525
21871
  errors2.push("mcp.json: configuration must be a JSON object");
21526
21872
  return;
21527
21873
  }
@@ -21544,7 +21890,7 @@ function validateMcp(root, manifestSchema, errors2) {
21544
21890
  }
21545
21891
  }
21546
21892
  const servers = doc.mcpServers;
21547
- if (!isPlainObject11(servers)) {
21893
+ if (!isPlainObject13(servers)) {
21548
21894
  errors2.push('mcp.json: "mcpServers" is required and must be an object');
21549
21895
  return;
21550
21896
  }
@@ -21645,7 +21991,7 @@ function validateAgentPlugin(root) {
21645
21991
  return { ok: false, errors: errors2, warnings };
21646
21992
  }
21647
21993
  validateManifest(manifest, errors2, warnings);
21648
- const manifestSchema = isPlainObject11(manifest) ? manifest["$schema"] : undefined;
21994
+ const manifestSchema = isPlainObject13(manifest) ? manifest["$schema"] : undefined;
21649
21995
  validateMcp(root, manifestSchema, errors2);
21650
21996
  validateSkills(root, errors2, warnings);
21651
21997
  return { ok: errors2.length === 0, errors: errors2, warnings };
@@ -24791,7 +25137,7 @@ sddCommand.command("exec").description("Run an argv child bound to a resolved SD
24791
25137
  }
24792
25138
  });
24793
25139
  registerSddEvidenceCommands(sddCommand);
24794
- var iterationCommand = program2.command("iteration").description("iteration phase-gate + push-cadence checks (engine-backed)");
25140
+ var iterationCommand = program2.command("iteration").description("iteration phase-gate + push-cadence checks and workflow registration (engine-backed)");
24795
25141
  function printChecklist(label, gate3) {
24796
25142
  if (gate3.ok) {
24797
25143
  console.log(import_picocolors4.default.green(`${label}: OK`));
@@ -24866,6 +25212,61 @@ iterationCommand.command("push-cadence").description("\xA75.1a push-cadence prob
24866
25212
  }
24867
25213
  process.exitCode = 1;
24868
25214
  });
25215
+ iterationCommand.command("register").exitOverride().description("Register an iteration workflow (seam S1 sibling of `workflow register`, engine-backed): " + "create-only `type: iteration` snapshot + {HARNESS_DIR}/status.json root entry under one lock. " + "Records the compass ref, the three branch anchors (--branch-base/--branch-integration/--branch-target) " + "and Todo plan rows (--row <json>, repeatable {id,title,file} \u2014 registration never authorizes implementation). " + "Re-running after a crash between snapshot creation and registration recovers: the existing snapshot " + "bytes are kept and only the root entry is written. Exit 0 success, 1 engine/IO refusal (no partial " + "activation), 2 usage").option("--workflow <id>", "Workflow id (single safe path component)").option("--compass-ref <path>", "Harness-relative compass ref recorded on the snapshot (e.g. iterations/<id>/delivery-compass.md)").option("--branch-base <branch>", "Iteration base branch anchor").option("--branch-integration <branch>", "Iteration integration branch anchor").option("--branch-target <branch>", "Iteration target branch anchor").option("--row <json>", "Plan row JSON object {id,title,file} \u2014 repeatable, order preserved", collectEntries, []).option("--project <id>", "Project register id recorded on the snapshot").option("--started-at <timestamp>", "Registration timestamp (YYYY-MM-DD or RFC3339; default: now)").option("--harness <path>", "Harness dir override (default: resolved control {HARNESS_DIR})").action(async (options, command) => {
25216
+ try {
25217
+ const usage = "usage: iteration register --workflow <id> --compass-ref <path> --branch-base <branch> " + "--branch-integration <branch> --branch-target <branch> --row <json> [--row <json> ...] " + "[--project <id>] [--started-at <ts>] [--harness <dir>]";
25218
+ if (command.args.length > 0) {
25219
+ throw new SddScriptError(`unexpected argument(s): ${command.args.join(", ")}
25220
+ ${usage}`, 2);
25221
+ }
25222
+ const missing = [
25223
+ ["--workflow", options.workflow],
25224
+ ["--compass-ref", options.compassRef],
25225
+ ["--branch-base", options.branchBase],
25226
+ ["--branch-integration", options.branchIntegration],
25227
+ ["--branch-target", options.branchTarget]
25228
+ ].filter(([, value]) => value === undefined || value.trim() === "").map(([flag]) => flag);
25229
+ const rowsRaw = options.row ?? [];
25230
+ if (rowsRaw.length === 0)
25231
+ missing.push("--row");
25232
+ if (missing.length > 0) {
25233
+ throw new SddScriptError(`missing required option(s): ${missing.join(", ")}
25234
+ ${usage}`, 2);
25235
+ }
25236
+ const rows = rowsRaw.map((raw, index) => {
25237
+ let parsed;
25238
+ try {
25239
+ parsed = JSON.parse(raw);
25240
+ } catch (error) {
25241
+ throw new SddScriptError(`--row[${index}] is not valid JSON: ${error.message}
25242
+ ${usage}`, 2);
25243
+ }
25244
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
25245
+ throw new SddScriptError(`--row[${index}] must be a JSON object {id,title,file} \u2014 got ${JSON.stringify(raw)}
25246
+ ${usage}`, 2);
25247
+ }
25248
+ return parsed;
25249
+ });
25250
+ assertWorkflowId(options.workflow);
25251
+ const harnessDir = resolveProcessHarnessDir3(options.harness);
25252
+ if (!harnessDir) {
25253
+ throw new Error(`harness dir not found from ${process.cwd()} \u2014 pass --harness <path>`);
25254
+ }
25255
+ setArtifactStore(createFsStore(harnessDir));
25256
+ const result = await registerIterationWorkflow(options.workflow, {
25257
+ harnessDir,
25258
+ compassRef: options.compassRef,
25259
+ branch: { base: options.branchBase, integration: options.branchIntegration, target: options.branchTarget },
25260
+ rows,
25261
+ ...options.project !== undefined ? { project: options.project } : {},
25262
+ ...options.startedAt !== undefined ? { startedAt: options.startedAt } : {}
25263
+ });
25264
+ console.log(import_picocolors4.default.green(result.recovered ? `iteration register: OK \u2014 ${result.workflowId} recovered (registration completed for the existing snapshot; its bytes were preserved)` : `iteration register: OK \u2014 ${result.workflowId} registered`));
25265
+ console.log(` snapshot: ${result.snapshotPath}`);
25266
+ } catch (error) {
25267
+ failScript(error, "iteration register");
25268
+ }
25269
+ });
24869
25270
  var dispatchCommand = program2.command("dispatch").description("Assignment field + default-branch gate checks (engine-backed)");
24870
25271
  dispatchCommand.command("validate").description("Validate an Assignment markdown file: required header fields + exactly-one branch form, " + "then the default-protected-branch gate (exit 1 on violations, 2 on usage)").argument("[assignment-file]", "Assignment markdown file").option("--branch <branch>", "Gate branch context (default: derived from the Assignment's own branch forms, then $MSTAR_WORKING_BRANCH)").action((assignmentFile, options) => {
24871
25272
  try {
@@ -25220,34 +25621,117 @@ function cleanupEvidenceBases(snapshots) {
25220
25621
  }
25221
25622
  function cleanupProbeMerged(mainRoot, bases) {
25222
25623
  const merged = {};
25223
- for (const base of bases) {
25224
- try {
25225
- merged[base] = gitSync(["branch", "--merged", base, "--format=%(refname:short)"], mainRoot).split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "");
25226
- } catch {
25227
- console.error(import_picocolors4.default.yellow(`worktree cleanup: note: merged-evidence base ${JSON.stringify(base)} does not resolve \u2014 candidates against it refuse as unmerged`));
25624
+ const listsByOid = new Map;
25625
+ const failedOids = new Set;
25626
+ for (const { base, oid } of bases.resolved) {
25627
+ let list = listsByOid.get(oid);
25628
+ if (list === undefined && !failedOids.has(oid)) {
25629
+ try {
25630
+ list = gitSync(["branch", "--merged", oid, "--format=%(refname:short)"], mainRoot).split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "");
25631
+ listsByOid.set(oid, list);
25632
+ } catch (error) {
25633
+ failedOids.add(oid);
25634
+ console.error(import_picocolors4.default.yellow(`worktree cleanup: note: merged-evidence base ${JSON.stringify(base)} membership probe failed (${cleanupGitMessage(error)}) \u2014 candidates against it refuse as unmerged`));
25635
+ }
25228
25636
  }
25637
+ if (list !== undefined)
25638
+ merged[base] = list;
25229
25639
  }
25230
25640
  return merged;
25231
25641
  }
25232
- function cleanupIsAncestor(tip, base, mainRoot) {
25233
- try {
25234
- execFileSync11("git", ["merge-base", "--is-ancestor", tip, base], { cwd: mainRoot, stdio: ["ignore", "ignore", "ignore"] });
25235
- return true;
25236
- } catch (error) {
25237
- return error.status === 1 ? false : null;
25642
+ function cleanupResolveBases(mainRoot, bases) {
25643
+ const resolved = [];
25644
+ const unresolved = [];
25645
+ for (const base of new Set(bases)) {
25646
+ try {
25647
+ const oid = gitSync(["rev-parse", "--verify", "--quiet", `${base}^{commit}`], mainRoot).trim();
25648
+ resolved.push({ base, oid });
25649
+ } catch (error) {
25650
+ unresolved.push({ base, detail: cleanupGitMessage(error) });
25651
+ console.error(import_picocolors4.default.yellow(`worktree cleanup: note: merged-evidence base ${JSON.stringify(base)} does not resolve \u2014 candidates against it refuse as unmerged`));
25652
+ }
25238
25653
  }
25654
+ return { resolved, unresolved };
25239
25655
  }
25240
- function cleanupProbeRemoteEvidence(mainRoot, remoteBranches, bases) {
25656
+ function cleanupProbeRemoteEvidence(mainRoot, candidates, bases, options) {
25657
+ if (!options.remoteRequested || candidates.length === 0)
25658
+ return [];
25659
+ const oidByBase = new Map(bases.resolved.map((entry) => [entry.base, entry.oid]));
25660
+ const unresolvedBases = new Set(bases.unresolved.map((entry) => entry.base));
25241
25661
  const evidence = [];
25242
- for (const remote of remoteBranches) {
25243
- for (const base of bases) {
25244
- const ancestor = cleanupIsAncestor(remote.tip, base, mainRoot);
25245
- if (ancestor === null) {
25246
- console.error(import_picocolors4.default.yellow(`worktree cleanup: note: ancestry of ${remote.branch} against ${JSON.stringify(base)} is indeterminate \u2014 no evidence row recorded (candidates refuse)`));
25247
- continue;
25662
+ const summaries = new Map;
25663
+ const record = (candidate, ancestor, detail) => {
25664
+ if (ancestor !== null) {
25665
+ evidence.push({ branch: candidate.branch, tip: candidate.tip, base: candidate.base, ancestor, prMerged: null });
25666
+ }
25667
+ if (ancestor !== true) {
25668
+ const summary = summaries.get(candidate.branch) ?? { notAncestor: 0, indeterminate: 0 };
25669
+ if (ancestor === false)
25670
+ summary.notAncestor++;
25671
+ else
25672
+ summary.indeterminate++;
25673
+ summaries.set(candidate.branch, summary);
25674
+ if (options.verbose) {
25675
+ console.error(import_picocolors4.default.yellow(`worktree cleanup: note: ancestry of ${candidate.branch} against ${JSON.stringify(candidate.base)}: ${detail}`));
25676
+ }
25677
+ }
25678
+ };
25679
+ const sweep = (mode, baseOid) => {
25680
+ try {
25681
+ const rows = new Map;
25682
+ for (const line of gitSync(["for-each-ref", mode, baseOid, "--format=%(refname)%09%(objectname)", "refs/remotes/origin"], mainRoot).split(/\r?\n/)) {
25683
+ if (line.trim() === "")
25684
+ continue;
25685
+ const tab = line.indexOf("\t");
25686
+ rows.set(line.slice(0, tab), line.slice(tab + 1));
25687
+ }
25688
+ return rows;
25689
+ } catch {
25690
+ return null;
25691
+ }
25692
+ };
25693
+ const byBaseOid = new Map;
25694
+ for (const candidate of candidates) {
25695
+ const baseOid = oidByBase.get(candidate.base);
25696
+ if (baseOid === undefined || unresolvedBases.has(candidate.base)) {
25697
+ record(candidate, null, "owner base does not resolve \u2014 no evidence row recorded (candidates refuse)");
25698
+ continue;
25699
+ }
25700
+ const group = byBaseOid.get(baseOid) ?? [];
25701
+ group.push(candidate);
25702
+ byBaseOid.set(baseOid, group);
25703
+ }
25704
+ for (const [baseOid, group] of byBaseOid) {
25705
+ const positive = sweep("--merged", baseOid);
25706
+ const positiveFailed = positive === null;
25707
+ const residual = [];
25708
+ for (const candidate of group) {
25709
+ const attested = !positiveFailed && positive.get(`refs/remotes/origin/${candidate.branch}`) === candidate.tip;
25710
+ if (attested) {
25711
+ record(candidate, true, "ancestor");
25712
+ } else {
25713
+ residual.push(candidate);
25248
25714
  }
25249
- evidence.push({ branch: remote.branch, tip: remote.tip, base, ancestor, prMerged: null });
25250
25715
  }
25716
+ if (residual.length === 0)
25717
+ continue;
25718
+ const negative = positiveFailed ? null : sweep("--no-merged", baseOid);
25719
+ for (const candidate of residual) {
25720
+ if (negative !== null && negative.get(`refs/remotes/origin/${candidate.branch}`) === candidate.tip) {
25721
+ record(candidate, false, "not an ancestor");
25722
+ } else {
25723
+ const detail = positiveFailed ? "positive membership sweep failed \u2014 no evidence row recorded (candidates refuse)" : "observed tip is not attested by either membership sweep \u2014 no evidence row recorded (candidates refuse)";
25724
+ record(candidate, null, detail);
25725
+ }
25726
+ }
25727
+ }
25728
+ for (const [branch, summary] of summaries) {
25729
+ const parts = [];
25730
+ if (summary.notAncestor > 0)
25731
+ parts.push(`not-an-ancestor ${summary.notAncestor}`);
25732
+ if (summary.indeterminate > 0)
25733
+ parts.push(`indeterminate ${summary.indeterminate}`);
25734
+ console.error(import_picocolors4.default.yellow(`worktree cleanup: note: remote ${branch}: ${parts.join(", ")}`));
25251
25735
  }
25252
25736
  return evidence;
25253
25737
  }
@@ -25291,6 +25775,7 @@ function cleanupProbe(input) {
25291
25775
  tip: entry.tip
25292
25776
  }));
25293
25777
  const evidenceBases = cleanupEvidenceBases(snapshots);
25778
+ const resolvedBases = cleanupResolveBases(input.mainRoot, evidenceBases);
25294
25779
  return {
25295
25780
  selected,
25296
25781
  snapshots,
@@ -25299,15 +25784,67 @@ function cleanupProbe(input) {
25299
25784
  defaultBranch: cleanupProbeDefaultBranch(input.mainRoot, worktrees[0]?.branch ?? null),
25300
25785
  localBranches,
25301
25786
  remoteBranches,
25302
- mergedLocalBranches: cleanupProbeMerged(input.mainRoot, evidenceBases),
25303
- remoteEvidence: cleanupProbeRemoteEvidence(input.mainRoot, remoteBranches, evidenceBases)
25787
+ mainRoot: input.mainRoot,
25788
+ resolvedBases,
25789
+ mergedLocalBranches: cleanupProbeMerged(input.mainRoot, resolvedBases)
25304
25790
  };
25305
25791
  }
25306
- function cleanupBuildFacts(probe, scope, remoteSelected) {
25792
+ function cleanupWorktreeCandidate(worktree, scope, snapshots) {
25793
+ if (scope.asserted.size > 0 && !scope.asserted.has(cleanupPathKey(worktree.path)))
25794
+ return false;
25795
+ const claims = cleanupWorktreeClaims(worktree.path, snapshots);
25796
+ if (claims.length > 0)
25797
+ return scope.allWorkflows || claims.some((claim) => claim.workflowId === scope.workflowId);
25798
+ if (scope.allWorkflows)
25799
+ return true;
25800
+ const checkedOut = worktree.branch ?? "";
25801
+ if (checkedOut === "")
25802
+ return false;
25803
+ return cleanupBranchClaims(checkedOut, snapshots).some((claim) => claim.workflowId === scope.workflowId);
25804
+ }
25805
+ function cleanupBranchCandidate(claims, scope) {
25806
+ if (!scope.allWorkflows && !claims.some((claim) => claim.workflowId === scope.workflowId))
25807
+ return false;
25808
+ if (scope.asserted.size === 0)
25809
+ return true;
25810
+ const ownerKeys = new Set(scope.assertedOwners.map((owner) => JSON.stringify(owner)));
25811
+ return claims.some((claim) => ownerKeys.has(JSON.stringify(claim)));
25812
+ }
25813
+ function cleanupResolveScope(probe, request) {
25814
+ const assertedOwners = [];
25815
+ for (const key of request.asserted) {
25816
+ const worktree = probe.worktrees.find((candidate) => cleanupPathKey(candidate.path) === key);
25817
+ if (worktree === undefined) {
25818
+ console.error(import_picocolors4.default.yellow(`worktree cleanup: note: --worktree ${key} does not match an inventoried worktree \u2014 no target is fabricated for it`));
25819
+ continue;
25820
+ }
25821
+ if (!cleanupWorktreeCandidate(worktree, request, probe.snapshots)) {
25822
+ console.error(import_picocolors4.default.yellow(`worktree cleanup: note: --worktree ${key} is outside workflow ${request.workflowId}'s candidate scope \u2014 select its actual --workflow or rerun with --all-workflows --worktree to inspect it under the same guards`));
25823
+ continue;
25824
+ }
25825
+ let attribution = cleanupDistinctOwner(cleanupWorktreeClaims(worktree.path, probe.snapshots));
25826
+ if (attribution.owner === null && !attribution.ambiguous) {
25827
+ const checkedOut = worktree.branch ?? "";
25828
+ if (checkedOut !== "")
25829
+ attribution = cleanupDistinctOwner(cleanupBranchClaims(checkedOut, probe.snapshots));
25830
+ }
25831
+ if (attribution.owner !== null)
25832
+ assertedOwners.push(attribution.owner);
25833
+ }
25834
+ return { ...request, scoped: !request.allWorkflows, assertedOwners };
25835
+ }
25836
+ function cleanupBuildFacts(probe, scope, options) {
25837
+ const ownerBase = (owner) => {
25838
+ const ownerDoc = probe.snapshots.find((doc) => doc.id === owner.workflowId);
25839
+ if (ownerDoc === undefined)
25840
+ return;
25841
+ const base = owner.planId !== undefined && ownerDoc.type === "iteration" ? ownerDoc.branch?.integration : ownerDoc.branch?.target;
25842
+ return typeof base === "string" && base !== "" ? base : undefined;
25843
+ };
25307
25844
  const targets = [];
25308
25845
  const notes = new Set;
25309
25846
  for (const worktree of probe.worktrees) {
25310
- if (scope.scoped && !scope.asserted.has(cleanupPathKey(worktree.path)))
25847
+ if (!cleanupWorktreeCandidate(worktree, scope, probe.snapshots))
25311
25848
  continue;
25312
25849
  let attribution = cleanupDistinctOwner(cleanupWorktreeClaims(worktree.path, probe.snapshots));
25313
25850
  if (attribution.owner === null && !attribution.ambiguous && scope.asserted.has(cleanupPathKey(worktree.path))) {
@@ -25321,19 +25858,31 @@ function cleanupBuildFacts(probe, scope, remoteSelected) {
25321
25858
  targets.push({ kind: "worktree", ref: worktree.path, branch: worktree.branch ?? "", tip: worktree.tip, owner: attribution.owner });
25322
25859
  }
25323
25860
  for (const local of probe.localBranches) {
25324
- const attribution = cleanupDistinctOwner(cleanupBranchClaims(local.branch, probe.snapshots));
25861
+ const claims = cleanupBranchClaims(local.branch, probe.snapshots);
25862
+ if (!cleanupBranchCandidate(claims, scope))
25863
+ continue;
25864
+ const attribution = cleanupDistinctOwner(claims);
25325
25865
  if (attribution.ambiguous) {
25326
25866
  notes.add(`branch ${local.branch} is claimed by more than one snapshot row \u2014 treated as unowned (refuses)`);
25327
25867
  }
25328
25868
  targets.push({ kind: "local-branch", ref: local.branch, branch: local.branch, tip: local.tip, owner: attribution.owner });
25329
25869
  }
25330
- if (remoteSelected) {
25870
+ const remoteCandidates = [];
25871
+ if (options.remoteRequested) {
25331
25872
  for (const remote of probe.remoteBranches) {
25332
- const attribution = cleanupDistinctOwner(cleanupBranchClaims(remote.branch, probe.snapshots));
25873
+ const claims = cleanupBranchClaims(remote.branch, probe.snapshots);
25874
+ if (!cleanupBranchCandidate(claims, scope))
25875
+ continue;
25876
+ const attribution = cleanupDistinctOwner(claims);
25333
25877
  if (attribution.ambiguous) {
25334
25878
  notes.add(`remote branch ${remote.branch} is claimed by more than one snapshot row \u2014 treated as unowned (refuses)`);
25335
25879
  }
25336
25880
  targets.push({ kind: "remote-branch", ref: `origin/${remote.branch}`, branch: remote.branch, tip: remote.tip, owner: attribution.owner });
25881
+ if (attribution.owner !== null) {
25882
+ const base = ownerBase(attribution.owner);
25883
+ if (base !== undefined)
25884
+ remoteCandidates.push({ branch: remote.branch, tip: remote.tip, base });
25885
+ }
25337
25886
  }
25338
25887
  }
25339
25888
  for (const note of notes)
@@ -25350,17 +25899,14 @@ function cleanupBuildFacts(probe, scope, remoteSelected) {
25350
25899
  snapshots: probe.snapshots,
25351
25900
  defaultBranch: probe.defaultBranch,
25352
25901
  mergedLocalBranches: probe.mergedLocalBranches,
25353
- remoteEvidence: probe.remoteEvidence
25902
+ remoteEvidence: cleanupProbeRemoteEvidence(probe.mainRoot, remoteCandidates, probe.resolvedBases, options)
25354
25903
  };
25355
25904
  const branchBase = new Map;
25356
25905
  for (const target of targets) {
25357
25906
  if (target.kind !== "local-branch" || target.owner === null)
25358
25907
  continue;
25359
- const ownerDoc = probe.snapshots.find((doc) => doc.id === target.owner.workflowId);
25360
- if (ownerDoc === undefined)
25361
- continue;
25362
- const base = target.owner.planId !== undefined && ownerDoc.type === "iteration" ? ownerDoc.branch?.integration : ownerDoc.branch?.target;
25363
- if (typeof base === "string" && base !== "")
25908
+ const base = ownerBase(target.owner);
25909
+ if (base !== undefined)
25364
25910
  branchBase.set(target.ref, base);
25365
25911
  }
25366
25912
  return { facts, branchBase };
@@ -25382,10 +25928,10 @@ function cleanupBranchDeletionCwd(base, probe, mainRoot) {
25382
25928
  const host = probe.worktrees.find((worktree) => worktree.branch === base);
25383
25929
  return host?.path ?? mainRoot;
25384
25930
  }
25385
- worktreeCommand.command("cleanup").description("Plan (and with --apply execute) guarded worktree/branch cleanup for a workflow: merged-evidence-only branch deletion with " + "active-lease / checked-out / foreign / dirty / non-terminal refusals; dry-run by default (no fetch/prune/write), prints " + "`verdict | kind | ref | reason` (exit 0 valid dry-run / successful removals, 1 probe/mutation failure, 2 usage)").option("--workflow <id>", "Workflow id whose snapshot drives ownership and protected refs (required)").option("--harness <path>", "Harness dir override (default: process-harness discovery from the verified main worktree)").option("--apply", "Execute current remove rows: git worktree remove (never force; evidence-base hosts deferred) \u2192 re-probe/re-plan \u2192 git branch -d (never -D) from the evidence-base checkout \u2192 remote compare-and-delete \u2192 deferred integration worktree removal \u2192 re-probe/re-plan newly released local branches").option("--remote", "Include remote-branch candidates (refs/remotes/origin) with expected-OID compare-and-delete").option("--worktree <path>", "Limit worktree candidates to this path (repeatable); also asserts ownership for a released-lease worktree matched to its recorded branch", (value, previous) => [...previous, value], []).option("--ignore-unreadable-snapshots", "Operator assertion: judge candidates against the readable snapshots only even when a sibling snapshot cannot be parsed at all (its declarations are unknown, so removals are otherwise withheld as cleanup.refuse.unreadable-snapshot)").action((options) => {
25931
+ worktreeCommand.command("cleanup").description("Plan (and with --apply execute) guarded worktree/branch cleanup for a workflow: merged-evidence-only branch deletion with " + "active-lease / checked-out / foreign / dirty / non-terminal refusals; dry-run by default (no fetch/prune/write), prints " + "`verdict | kind | ref | reason` (exit 0 valid dry-run / successful removals, 1 probe/mutation failure, 2 usage). " + "By default candidates come from the selected workflow's recorded claims; --all-workflows sweeps everything.").option("--workflow <id>", "Workflow id whose snapshot drives ownership and protected refs (required); without --all-workflows, candidates are limited to this workflow's recorded claims").option("--harness <path>", "Harness dir override (default: process-harness discovery from the verified main worktree)").option("--apply", "Execute current remove rows: git worktree remove (never force; evidence-base hosts deferred) \u2192 re-probe/re-plan \u2192 git branch -d (never -D) from the evidence-base checkout \u2192 remote compare-and-delete \u2192 deferred integration worktree removal \u2192 re-probe/re-plan newly released local branches").option("--remote", "Include remote-branch candidates (refs/remotes/origin) with expected-OID compare-and-delete").option("--worktree <path>", "Limit worktree candidates to this path (repeatable); also narrows branch candidates to the asserted worktrees' exact recorded owners, and asserts ownership for a released-lease worktree matched to its recorded branch", (value, previous) => [...previous, value], []).option("--all-workflows", "Include candidates from all workflows and unrecorded refs; --worktree still narrows by exact owner").option("--verbose", "Print per-pair ancestry diagnostics; no change to candidates or decisions").option("--ignore-unreadable-snapshots", "Operator assertion: judge candidates against the readable snapshots only even when a sibling snapshot cannot be parsed at all (its declarations are unknown, so removals are otherwise withheld as cleanup.refuse.unreadable-snapshot)").action((options) => {
25386
25932
  try {
25387
25933
  if (!options.workflow) {
25388
- throw new SddScriptError("usage: worktree cleanup --workflow <id> [--harness <path>] [--apply] [--remote] [--worktree <path>] [--ignore-unreadable-snapshots]", 2);
25934
+ throw new SddScriptError("usage: worktree cleanup --workflow <id> [--harness <path>] [--apply] [--remote] [--worktree <path>] [--all-workflows] [--verbose] [--ignore-unreadable-snapshots]", 2);
25389
25935
  }
25390
25936
  const main = readMainWorktree();
25391
25937
  if (main === null)
@@ -25395,8 +25941,9 @@ worktreeCommand.command("cleanup").description("Plan (and with --apply execute)
25395
25941
  throw new Error("harness directory not found");
25396
25942
  const snapshotPath = resolveSnapshotPath(options.workflow, harnessDir);
25397
25943
  const workflowRoot = resolveWorkflowDir(harnessDir, { harnessDir });
25398
- const scope = {
25399
- scoped: (options.worktree?.length ?? 0) > 0,
25944
+ const scopeRequest = {
25945
+ workflowId: options.workflow,
25946
+ allWorkflows: options.allWorkflows === true,
25400
25947
  asserted: new Set((options.worktree ?? []).map((candidate) => cleanupPathKey(candidate)))
25401
25948
  };
25402
25949
  const probeInput = {
@@ -25406,8 +25953,12 @@ worktreeCommand.command("cleanup").description("Plan (and with --apply execute)
25406
25953
  workflowId: options.workflow
25407
25954
  };
25408
25955
  const ignoreUnreadableSiblings = options.ignoreUnreadableSnapshots === true;
25956
+ const evidenceOptions = { remoteRequested: options.remote === true, verbose: options.verbose === true };
25409
25957
  const probe1 = cleanupProbe(probeInput);
25410
- const built1 = cleanupBuildFacts(probe1, scope, options.remote === true);
25958
+ const scope = cleanupResolveScope(probe1, scopeRequest);
25959
+ const scopeOmitted = probe1.worktrees.filter((worktree) => !cleanupWorktreeCandidate(worktree, scope, probe1.snapshots)).length + probe1.localBranches.filter((local) => !cleanupBranchCandidate(cleanupBranchClaims(local.branch, probe1.snapshots), scope)).length + (evidenceOptions.remoteRequested ? probe1.remoteBranches.filter((remote) => !cleanupBranchCandidate(cleanupBranchClaims(remote.branch, probe1.snapshots), scope)).length : 0);
25960
+ console.error(import_picocolors4.default.yellow(`worktree cleanup: scope ${scope.scoped ? `workflow ${options.workflow}` : "all workflows"} \u2014 asserted paths: ${scope.asserted.size}, candidates omitted: ${scopeOmitted}; rerun with --all-workflows${evidenceOptions.remoteRequested ? " --remote" : ""} for the full sweep`));
25961
+ const built1 = cleanupBuildFacts(probe1, scope, evidenceOptions);
25411
25962
  const plan1 = cleanupGuardUnreadableSiblings(planWorktreeCleanup(probe1.selected, built1.facts), probe1, ignoreUnreadableSiblings);
25412
25963
  cleanupPrintPlan(`worktree cleanup (workflow ${options.workflow}): plan`, plan1);
25413
25964
  if (options.apply !== true)
@@ -25440,7 +25991,7 @@ worktreeCommand.command("cleanup").description("Plan (and with --apply execute)
25440
25991
  }
25441
25992
  }
25442
25993
  const probe2 = cleanupProbe(probeInput);
25443
- const built2 = cleanupBuildFacts(probe2, scope, options.remote === true);
25994
+ const built2 = cleanupBuildFacts(probe2, scope, evidenceOptions);
25444
25995
  const plan2 = cleanupGuardUnreadableSiblings(planWorktreeCleanup(probe2.selected, built2.facts), probe2, ignoreUnreadableSiblings);
25445
25996
  cleanupPrintPlan(`worktree cleanup (workflow ${options.workflow}): post-removal re-plan`, plan2);
25446
25997
  for (const decision of plan2) {
@@ -25490,7 +26041,7 @@ worktreeCommand.command("cleanup").description("Plan (and with --apply execute)
25490
26041
  }
25491
26042
  if (releasedBranches.size > 0) {
25492
26043
  const probe3 = cleanupProbe(probeInput);
25493
- const built3 = cleanupBuildFacts(probe3, scope, options.remote === true);
26044
+ const built3 = cleanupBuildFacts(probe3, scope, evidenceOptions);
25494
26045
  const plan3 = cleanupGuardUnreadableSiblings(planWorktreeCleanup(probe3.selected, built3.facts), probe3, ignoreUnreadableSiblings).filter((decision) => decision.kind === "local-branch" && releasedBranches.has(decision.ref));
25495
26046
  cleanupPrintPlan(`worktree cleanup (workflow ${options.workflow}): post-deferred-removal re-plan`, plan3);
25496
26047
  for (const decision of plan3) {
@@ -25824,16 +26375,113 @@ function parseAuditScaffoldInput(text) {
25824
26375
  throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].dependsOn must be "none", "plans/NNN-*.md", or a plan number NNN`, 2);
25825
26376
  }
25826
26377
  const dependsOn = rawDependsOn === undefined ? undefined : /^\d{3}$/.test(rawDependsOn) ? `plans/${rawDependsOn}-*.md` : rawDependsOn;
26378
+ const confidence = finding.confidence === undefined ? "MED" : finding.confidence;
26379
+ if (typeof confidence !== "string" || AUDIT_CONFIDENCES.find((c) => c === confidence) === undefined) {
26380
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].confidence must be one of ${AUDIT_CONFIDENCES.join("|")}`, 2);
26381
+ }
26382
+ const rawEvidence = finding.evidence;
26383
+ if (rawEvidence !== undefined && !Array.isArray(rawEvidence)) {
26384
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence must be an array of strings or {file, line?, description} objects`, 2);
26385
+ }
26386
+ const evidence = (rawEvidence ?? []).map((item, itemIndex) => {
26387
+ if (typeof item === "string") {
26388
+ if (item.trim() === "") {
26389
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence[${itemIndex}] must be a non-empty string or a {file, line?, description} object`, 2);
26390
+ }
26391
+ return item;
26392
+ }
26393
+ if (typeof item !== "object" || item === null || Array.isArray(item)) {
26394
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence[${itemIndex}] must be a non-empty string or a {file, line?, description} object`, 2);
26395
+ }
26396
+ const loc = item;
26397
+ if (typeof loc.file !== "string" || loc.file === "") {
26398
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence[${itemIndex}].file is required and must be a repository-relative path`, 2);
26399
+ }
26400
+ if (loc.line !== undefined && (typeof loc.line !== "number" || !Number.isSafeInteger(loc.line) || loc.line <= 0)) {
26401
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence[${itemIndex}].line must be a positive integer when present`, 2);
26402
+ }
26403
+ if (typeof loc.description !== "string" || loc.description.trim() === "") {
26404
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence[${itemIndex}].description must be a non-empty string`, 2);
26405
+ }
26406
+ return {
26407
+ file: loc.file,
26408
+ ...loc.line !== undefined ? { line: loc.line } : {},
26409
+ description: loc.description
26410
+ };
26411
+ });
26412
+ const rawFingerprint = finding.fingerprint;
26413
+ if (rawFingerprint !== undefined && (typeof rawFingerprint !== "string" || rawFingerprint === "")) {
26414
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].fingerprint must be a non-empty string when present`, 2);
26415
+ }
26416
+ const rawTrace = finding.trace;
26417
+ if (rawTrace !== undefined && !Array.isArray(rawTrace)) {
26418
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace must be an array of {kind, file, line, scope, description} objects`, 2);
26419
+ }
26420
+ const trace = rawTrace === undefined ? undefined : rawTrace.map((step, stepIndex) => {
26421
+ if (typeof step !== "object" || step === null || Array.isArray(step)) {
26422
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}] must be a {kind, file, line, scope, description} object`, 2);
26423
+ }
26424
+ const s = step;
26425
+ if (!AUDIT_TRACE_KINDS.find((k) => k === s.kind)) {
26426
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}].kind must be one of ${AUDIT_TRACE_KINDS.join("|")}`, 2);
26427
+ }
26428
+ if (typeof s.file !== "string" || s.file === "") {
26429
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}].file is required and must be a repository-relative path`, 2);
26430
+ }
26431
+ if (typeof s.line !== "number" || !Number.isSafeInteger(s.line) || s.line <= 0) {
26432
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}].line must be a positive integer`, 2);
26433
+ }
26434
+ if (typeof s.scope !== "string" || s.scope.trim() === "") {
26435
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}].scope must be a non-empty string`, 2);
26436
+ }
26437
+ if (typeof s.description !== "string" || s.description.trim() === "") {
26438
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}].description must be a non-empty string`, 2);
26439
+ }
26440
+ return { kind: s.kind, file: s.file, line: s.line, scope: s.scope, description: s.description };
26441
+ });
26442
+ const rawSeverity = finding.severity;
26443
+ if (rawSeverity !== undefined) {
26444
+ if (typeof rawSeverity !== "object" || rawSeverity === null || Array.isArray(rawSeverity)) {
26445
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].severity must be a {likelihood, impact, overall} object`, 2);
26446
+ }
26447
+ const sev = rawSeverity;
26448
+ for (const field of ["likelihood", "impact", "overall"]) {
26449
+ if (!AUDIT_SEVERITY_RANKS.find((r) => r === sev[field])) {
26450
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].severity.${field} must be one of ${AUDIT_SEVERITY_RANKS.join("|")}`, 2);
26451
+ }
26452
+ }
26453
+ }
26454
+ const severity = rawSeverity === undefined ? undefined : {
26455
+ likelihood: rawSeverity.likelihood,
26456
+ impact: rawSeverity.impact,
26457
+ overall: rawSeverity.overall
26458
+ };
26459
+ const freeText = (field) => {
26460
+ const raw2 = finding[field];
26461
+ if (raw2 === undefined)
26462
+ return;
26463
+ if (typeof raw2 !== "string" || raw2.trim() === "") {
26464
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].${field} must be a non-empty string`, 2);
26465
+ }
26466
+ return raw2.trim();
26467
+ };
26468
+ const fixSketch = freeText("fixSketch");
26469
+ const verification = freeText("verification");
25827
26470
  return {
25828
26471
  title,
25829
26472
  category,
25830
26473
  impact,
25831
26474
  effort,
25832
26475
  risk,
25833
- confidence: "MED",
25834
- evidence: [],
26476
+ confidence,
26477
+ evidence,
25835
26478
  priority,
25836
- dependsOn
26479
+ ...fixSketch !== undefined ? { fixSketch } : {},
26480
+ ...verification !== undefined ? { verification } : {},
26481
+ ...dependsOn !== undefined ? { dependsOn } : {},
26482
+ ...rawFingerprint !== undefined ? { fingerprint: rawFingerprint } : {},
26483
+ ...trace !== undefined ? { trace } : {},
26484
+ ...severity !== undefined ? { severity } : {}
25837
26485
  };
25838
26486
  });
25839
26487
  return { findings, needsVerification: parseNeedsVerification(needsVerificationRaw), hardeningChecked: parseHardeningChecked(hardeningCheckedRaw) };
@@ -25912,13 +26560,21 @@ auditCommand.command("scaffold").description("Scaffold an audit-<date>/ plan dir
25912
26560
  const outDir = options.dir !== undefined ? resolveCliPath(options.dir) : resolveCliPath(`audit-${date}`);
25913
26561
  const input = parseAuditScaffoldInput(fs12.readFileSync(abs, "utf8"));
25914
26562
  const sha = resolveAuditShortSha(process.cwd(), options.sha);
25915
- const result = scaffoldAuditPlan(outDir, input.findings, {
25916
- date,
25917
- repoName: options.repo,
25918
- repoShortSha: sha,
25919
- needsVerification: input.needsVerification,
25920
- hardeningChecked: input.hardeningChecked
25921
- });
26563
+ let result;
26564
+ try {
26565
+ result = scaffoldAuditPlan(outDir, input.findings, {
26566
+ date,
26567
+ repoName: options.repo,
26568
+ repoShortSha: sha,
26569
+ needsVerification: input.needsVerification,
26570
+ hardeningChecked: input.hardeningChecked
26571
+ });
26572
+ } catch (error) {
26573
+ if (error instanceof TypeError && error.message.includes("audit.finding.")) {
26574
+ throw new SddScriptError(error.message, 2);
26575
+ }
26576
+ throw error;
26577
+ }
25922
26578
  const count = result.files.length;
25923
26579
  console.log(import_picocolors4.default.green(`audit scaffold: OK \u2014 ${count} plan file${count === 1 ? "" : "s"} in ${result.outDir}`));
25924
26580
  for (const file of result.files)
@@ -26061,6 +26717,8 @@ var AUDIT_PRIORITY_LOOKUP = lookupTable(AUDIT_PRIORITIES);
26061
26717
  var AUDIT_EFFORT_LOOKUP = lookupTable(AUDIT_EFFORTS);
26062
26718
  var AUDIT_RISK_LOOKUP = lookupTable(AUDIT_RISKS);
26063
26719
  var AUDIT_CATEGORY_LOOKUP = lookupTable(AUDIT_CATEGORIES);
26720
+ var AUDIT_TRACE_KINDS = ["entrypoint", "propagation", "sink"];
26721
+ var AUDIT_SEVERITY_RANKS = ["informational", "low", "medium", "high", "critical"];
26064
26722
  var HOST_SIGNALS = [
26065
26723
  "subagent_type",
26066
26724
  "question",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mstar-harness/cli",
3
- "version": "3.10.3",
3
+ "version": "3.11.0",
4
4
  "description": "Morning Star harness CLI — installer bootstrap + mstar workflow verbs (path/status/lease/sdd/iteration/dispatch/worktree/lint/design-md/audit/compound/host/skill).",
5
5
  "license": "MIT",
6
6
  "repository": {