@mstar-harness/cli 3.10.3 → 3.11.1

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 +800 -102
  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") {
@@ -16172,8 +16518,8 @@ function reportedBranchesOf(row) {
16172
16518
  function snapshotPathOf(harnessRoot, workflowId) {
16173
16519
  return join202(resolveWorkflowDir2(harnessRoot, { harnessDir: harnessRoot }), workflowId, SNAPSHOT_FILE22);
16174
16520
  }
16175
- function sessionFilePath(harnessRoot, workflowId, sessionId) {
16176
- return join202(resolveWorkflowDir2(harnessRoot, { harnessDir: harnessRoot }), workflowId, SESSION_DIR, `${sessionId}.json`);
16521
+ function sessionFilePath(harnessRoot, workflowId, role, sessionId) {
16522
+ return join202(resolveWorkflowDir2(harnessRoot, { harnessDir: harnessRoot }), workflowId, SESSION_DIR, `${role}-${sessionId}.json`);
16177
16523
  }
16178
16524
  function localStore2(harnessRoot) {
16179
16525
  let store;
@@ -16334,6 +16680,22 @@ function safePlanId(planId, where) {
16334
16680
  }
16335
16681
  return planId;
16336
16682
  }
16683
+ var SESSION_ID_MAX_LENGTH = 128;
16684
+ function safeSessionId(value) {
16685
+ if (value === undefined)
16686
+ return;
16687
+ if (typeof value !== "string")
16688
+ throw invalidInput2("sessionId must be a string");
16689
+ if (value.length > SESSION_ID_MAX_LENGTH) {
16690
+ throw new CoordinationError2("coordination.invalid-session-id", `session id is longer than ${SESSION_ID_MAX_LENGTH} characters: ${JSON.stringify(value)}`, { session_id: value, max_length: SESSION_ID_MAX_LENGTH });
16691
+ }
16692
+ try {
16693
+ assertSafePathComponent2(value, "session id");
16694
+ } catch (error) {
16695
+ throw new CoordinationError2("coordination.invalid-session-id", `session id ${JSON.stringify(value)} is not a safe path component: ${errorMessage2(error)}`, { session_id: value });
16696
+ }
16697
+ return value;
16698
+ }
16337
16699
  function readSnapshot2(dir) {
16338
16700
  const snapshotPath = join202(dir, SNAPSHOT_FILE22);
16339
16701
  if (!existsSync152(snapshotPath)) {
@@ -16517,7 +16879,7 @@ function readSessionEnvelope2(sessionPath) {
16517
16879
  return session;
16518
16880
  }
16519
16881
  function createSessionEnvelope(session) {
16520
- const path2 = sessionFilePath(session.harness_root, session.workflow_id, session.session_id);
16882
+ const path2 = sessionFilePath(session.harness_root, session.workflow_id, session.role, session.session_id);
16521
16883
  mkdirSync92(dirname122(path2), { recursive: true });
16522
16884
  try {
16523
16885
  writeFileSync72(path2, `${JSON.stringify(session, null, 2)}
@@ -16822,7 +17184,7 @@ function assertCoordinatorResidency(cwd, snapshot) {
16822
17184
  }
16823
17185
  return main;
16824
17186
  }
16825
- async function bindCoordinatorSession(cwd, workflowId, harnessDir) {
17187
+ async function bindCoordinatorSession(cwd, workflowId, harnessDir, sessionId) {
16826
17188
  const harnessRoot = requireProcessRoot(cwd, harnessDir);
16827
17189
  safePlanId(workflowId, "workflowId");
16828
17190
  const snapshotPath = snapshotPathOf(harnessRoot, workflowId);
@@ -16831,7 +17193,7 @@ async function bindCoordinatorSession(cwd, workflowId, harnessDir) {
16831
17193
  const session = {
16832
17194
  schema_version: 1,
16833
17195
  role: "coordinator",
16834
- session_id: randomUUID22(),
17196
+ session_id: sessionId ?? randomUUID22(),
16835
17197
  workflow_id: workflowId,
16836
17198
  harness_root: harnessRoot
16837
17199
  };
@@ -16871,7 +17233,7 @@ function requireProcessRoot(cwd, harnessDir) {
16871
17233
  }
16872
17234
  return root;
16873
17235
  }
16874
- async function bindPlanSessionForPlan(scope) {
17236
+ async function bindPlanSessionForPlan(scope, sessionId) {
16875
17237
  const { harnessRoot, workflowId, planId } = scope;
16876
17238
  const snapshotPath = snapshotPathOf(harnessRoot, workflowId);
16877
17239
  assertSnapshotPath2(harnessRoot, workflowId, snapshotPath);
@@ -16894,7 +17256,7 @@ async function bindPlanSessionForPlan(scope) {
16894
17256
  const session = {
16895
17257
  schema_version: 1,
16896
17258
  role: "plan-pm",
16897
- session_id: randomUUID22(),
17259
+ session_id: sessionId ?? randomUUID22(),
16898
17260
  workflow_id: workflowId,
16899
17261
  plan_id: planId,
16900
17262
  harness_root: harnessRoot
@@ -16961,19 +17323,21 @@ async function bindPlanSession(input) {
16961
17323
  return resumeBoundSession(input.resumePath);
16962
17324
  }
16963
17325
  if ("coordinator" in input) {
16964
- assertExactKeys2(input, ["coordinator", "workflowId", "harnessDir", "cwd"], "bind coordinator input");
17326
+ assertExactKeys2(input, ["coordinator", "workflowId", "harnessDir", "cwd", "sessionId"], "bind coordinator input");
16965
17327
  if (input.coordinator !== true)
16966
17328
  throw invalidInput2("`coordinator` is only meaningful as true");
16967
17329
  if (!isNonEmptyString2(input.workflowId))
16968
17330
  throw invalidInput2("workflowId is required");
16969
17331
  requireCwd(input.cwd);
16970
- return bindCoordinatorSession(input.cwd, input.workflowId, input.harnessDir);
17332
+ const sessionId2 = safeSessionId(input.sessionId);
17333
+ return bindCoordinatorSession(input.cwd, input.workflowId, input.harnessDir, sessionId2);
16971
17334
  }
16972
- assertExactKeys2(input, ["scope", "cwd"], "bind plan input");
17335
+ assertExactKeys2(input, ["scope", "cwd", "sessionId"], "bind plan input");
16973
17336
  if (!isPlainObject22(input.scope))
16974
17337
  throw invalidInput2("a plan bind requires a scope");
16975
17338
  requireCwd(input.cwd);
16976
- return bindPlanSessionForPlan(await resolvePlanScope(input.scope, input.cwd));
17339
+ const sessionId = safeSessionId(input.sessionId);
17340
+ return bindPlanSessionForPlan(await resolvePlanScope(input.scope, input.cwd), sessionId);
16977
17341
  }
16978
17342
  function requireCwd(cwd) {
16979
17343
  if (!isNonEmptyString2(cwd) || !isAbsolute122(cwd))
@@ -19255,7 +19619,7 @@ function usageError(message) {
19255
19619
  function gateError(message) {
19256
19620
  return new SddScriptError2(message, 1);
19257
19621
  }
19258
- function isPlainObject10(value) {
19622
+ function isPlainObject11(value) {
19259
19623
  return typeof value === "object" && value !== null && !Array.isArray(value);
19260
19624
  }
19261
19625
  function isIdLike2(value) {
@@ -19339,7 +19703,7 @@ function validateArgvUsage(argv) {
19339
19703
  }
19340
19704
  }
19341
19705
  function validateCoverageUsage(coverage) {
19342
- if (!isPlainObject10(coverage))
19706
+ if (!isPlainObject11(coverage))
19343
19707
  throw usageError("evidence capture request.coverage must be a JSON object");
19344
19708
  const acIds = coverage.acIds;
19345
19709
  if (!Array.isArray(acIds) || acIds.length === 0 || acIds.length > MAX_AC_IDS2) {
@@ -19369,7 +19733,7 @@ function validateInputSpecsUsage(inputs) {
19369
19733
  const seen = new Set;
19370
19734
  const paths = [];
19371
19735
  for (const spec of inputs) {
19372
- if (!isPlainObject10(spec))
19736
+ if (!isPlainObject11(spec))
19373
19737
  throw usageError("evidence capture request.inputs entries must be JSON objects");
19374
19738
  if (!isInputSpecPath2(spec.path)) {
19375
19739
  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 +19761,7 @@ function validateInputSpecsUsage(inputs) {
19397
19761
  return inputs;
19398
19762
  }
19399
19763
  function validateRequestUsage(request) {
19400
- if (!isPlainObject10(request))
19764
+ if (!isPlainObject11(request))
19401
19765
  throw usageError("evidence capture request must be a JSON object");
19402
19766
  for (const key of Object.keys(request)) {
19403
19767
  if (!REQUEST_KEYS.includes(key)) {
@@ -19405,7 +19769,7 @@ function validateRequestUsage(request) {
19405
19769
  }
19406
19770
  }
19407
19771
  const context = request.context;
19408
- if (!isPlainObject10(context))
19772
+ if (!isPlainObject11(context))
19409
19773
  throw usageError("evidence capture request.context must be a JSON object");
19410
19774
  if (typeof context.planId !== "string" || context.planId.length === 0 || !SAFE_COMPONENT_RE.test(context.planId)) {
19411
19775
  throw usageError("evidence capture request.context.planId must be a single safe path component");
@@ -19457,7 +19821,7 @@ function validateCollectorOptions(options) {
19457
19821
  throw fail(`environmentKeys must be unique members of ${ENVIRONMENT_KEYS2.join("/")}`);
19458
19822
  }
19459
19823
  const limits = options.limits;
19460
- if (!isPlainObject10(limits))
19824
+ if (!isPlainObject11(limits))
19461
19825
  throw fail("limits must be a JSON object");
19462
19826
  const ceilings = [
19463
19827
  ["timeoutMs", TIMEOUT_MIN_MS2, TIMEOUT_MAX_MS2],
@@ -20430,7 +20794,7 @@ function loadJsonFileUsage(pathValue, what) {
20430
20794
  } catch (error) {
20431
20795
  throw usageError(`${what} file is not valid JSON: ${pathValue} (${error.message})`);
20432
20796
  }
20433
- if (!isPlainObject10(doc))
20797
+ if (!isPlainObject11(doc))
20434
20798
  throw usageError(`${what} file must contain a JSON object: ${pathValue}`);
20435
20799
  return doc;
20436
20800
  }
@@ -20499,10 +20863,10 @@ async function runEvidenceVerify(invocation) {
20499
20863
  }
20500
20864
  return ioFailureAssessment(`evidence record unreadable: ${error.message}`);
20501
20865
  }
20502
- if (isPlainObject10(record)) {
20866
+ if (isPlainObject11(record)) {
20503
20867
  const request = record.request;
20504
- const context = isPlainObject10(request) ? request.context : null;
20505
- const controlRoot = isPlainObject10(context) && typeof context.controlHarnessRoot === "string" ? context.controlHarnessRoot : null;
20868
+ const context = isPlainObject11(request) ? request.context : null;
20869
+ const controlRoot = isPlainObject11(context) && typeof context.controlHarnessRoot === "string" ? context.controlHarnessRoot : null;
20506
20870
  if (controlRoot !== null && dirname10(dirname10(canonicalSddDir)) !== controlRoot) {
20507
20871
  throw usageError(`${VERIFY_USAGE}
20508
20872
  --sdd-dir ${canonicalSddDir} is not under the canonical control root recorded in the record context (${controlRoot}); a relocated or copied evidence bundle is refused`);
@@ -20895,6 +21259,16 @@ function handoffMismatch(verb, planId, live, named) {
20895
21259
  details: { plan_id: planId, expected: live, actual: named }
20896
21260
  });
20897
21261
  }
21262
+ var SESSION_ID_ENV = "MSTAR_HOST_SESSION_ID";
21263
+ function sessionIdOf(options) {
21264
+ const flag = options.sessionId;
21265
+ if (flag !== undefined)
21266
+ return flag;
21267
+ const injected = process.env[SESSION_ID_ENV];
21268
+ if (injected === undefined || injected.trim() === "")
21269
+ return;
21270
+ return injected.trim();
21271
+ }
20898
21272
  function bindInputOf(options) {
20899
21273
  const coordinator = options.coordinator === true;
20900
21274
  const workflow = options.workflow;
@@ -20912,20 +21286,22 @@ function bindInputOf(options) {
20912
21286
  resume !== undefined
20913
21287
  ].filter(Boolean).length;
20914
21288
  if (families !== 1) {
20915
- throw new SddScriptError2(`usage: plan bind --coordinator --workflow <id> [--harness <absolute-path>] [--json]
20916
- ` + ` plan bind --assignment <absolute-md-path> [--json]
20917
- ` + ` plan bind --workflow <id> --plan <id> [--harness <absolute-path>] [--json]
21289
+ throw new SddScriptError2(`usage: plan bind --coordinator --workflow <id> [--harness <absolute-path>] [--session-id <id>] [--json]
21290
+ ` + ` plan bind --assignment <absolute-md-path> [--session-id <id>] [--json]
21291
+ ` + ` plan bind --workflow <id> --plan <id> [--harness <absolute-path>] [--session-id <id>] [--json]
20918
21292
  ` + " plan bind --resume <absolute-session-json-path> [--json]", 2);
20919
21293
  }
20920
21294
  const cwd = process.cwd();
20921
21295
  if (coordinator) {
20922
21296
  if (plan !== undefined || assignment !== undefined || resume !== undefined) {
20923
- throw new SddScriptError2("plan bind --coordinator accepts only --workflow (plus optional --harness)", 2);
21297
+ throw new SddScriptError2("plan bind --coordinator accepts only --workflow (plus optional --harness and --session-id)", 2);
20924
21298
  }
21299
+ const sessionId2 = sessionIdOf(options);
20925
21300
  return {
20926
21301
  coordinator: true,
20927
21302
  workflowId: requireFlag(workflow, "--workflow", "bind", "workflow-id"),
20928
21303
  ...harness !== undefined ? { harnessDir: harness } : {},
21304
+ ...sessionId2 !== undefined ? { sessionId: sessionId2 } : {},
20929
21305
  cwd
20930
21306
  };
20931
21307
  }
@@ -20933,23 +21309,33 @@ function bindInputOf(options) {
20933
21309
  if (workflow !== undefined || plan !== undefined || harness !== undefined) {
20934
21310
  throw new SddScriptError2("plan bind --assignment accepts no --workflow/--plan/--harness (the Assignment pins the workflow and harness)", 2);
20935
21311
  }
20936
- return { scope: { assignmentPath: requireAbsolutePath(assignment, "--assignment", "bind", "md-path") }, cwd };
21312
+ const sessionId2 = sessionIdOf(options);
21313
+ return {
21314
+ scope: { assignmentPath: requireAbsolutePath(assignment, "--assignment", "bind", "md-path") },
21315
+ ...sessionId2 !== undefined ? { sessionId: sessionId2 } : {},
21316
+ cwd
21317
+ };
20937
21318
  }
20938
21319
  if (resume !== undefined) {
20939
21320
  if (harness !== undefined) {
20940
21321
  throw new SddScriptError2("plan bind --resume accepts no --harness (the session envelope pins the harness root)", 2);
20941
21322
  }
21323
+ if (options.sessionId !== undefined) {
21324
+ throw new SddScriptError2("plan bind --resume accepts no --session-id (a resumed session never re-identifies)", 2);
21325
+ }
20942
21326
  return { resumePath: requireAbsolutePath(resume, "--resume", "bind", "session-json-path"), cwd };
20943
21327
  }
20944
21328
  if (workflow === undefined || plan === undefined) {
20945
21329
  throw new SddScriptError2("plan bind --workflow requires --plan <id> (the workflow+plan address form)", 2);
20946
21330
  }
21331
+ const sessionId = sessionIdOf(options);
20947
21332
  return {
20948
21333
  scope: {
20949
21334
  workflowId: requireFlag(workflow, "--workflow", "bind", "workflow-id"),
20950
21335
  planId: requireFlag(plan, "--plan", "bind", "plan-id"),
20951
21336
  ...harness !== undefined ? { harnessDir: harness } : {}
20952
21337
  },
21338
+ ...sessionId !== undefined ? { sessionId } : {},
20953
21339
  cwd
20954
21340
  };
20955
21341
  }
@@ -20962,7 +21348,7 @@ function harnessOverrideOf(input) {
20962
21348
  }
20963
21349
  function registerPlanCommands(program2) {
20964
21350
  const plan = program2.command("plan").description("Scoped plan coordination: bind a plan or coordinator session, read its view, and run the row transitions " + "(engine-backed; JSON on stdout with --json, diagnostics on stderr; exit 0 ok/no-op, 1 scope/ownership/" + "revision/state/Git refusal, 2 usage)").exitOverride();
20965
- plan.command("bind").description("Bind the scoped session for one plan \u2014 fresh `--workflow/--plan` or `--assignment` claim (both addresses resolve " + "the same prepared row), fresh `--coordinator` bootstrap, or explicit `--resume` of an existing session file " + "(read-only: no ownership change, no takeover)").option("--coordinator", "Trusted local coordinator bootstrap (requires --workflow; one per workflow)").option("--workflow <id>", "Workflow id").option("--plan <id>", "Plan id (workflow+plan address form)").option("--assignment <path>", "Absolute path of the pinned prepared Assignment").option("--resume <path>", "Absolute path of an existing session JSON envelope").option("--harness <path>", "Absolute harness dir override (default: resolved control root)").option("--json", "Machine-readable JSON on stdout").action(async (options) => runVerb("bind", options, { workflow_id: options.workflow, plan_id: options.plan }, async (json) => {
21351
+ plan.command("bind").description("Bind the scoped session for one plan \u2014 fresh `--workflow/--plan` or `--assignment` claim (both addresses resolve " + "the same prepared row), fresh `--coordinator` bootstrap, or explicit `--resume` of an existing session file " + "(read-only: no ownership change, no takeover). A fresh bind adopts `--session-id`, else the injected " + "MSTAR_HOST_SESSION_ID, else a generated id; `--resume` takes none").option("--coordinator", "Trusted local coordinator bootstrap (requires --workflow; one per workflow)").option("--workflow <id>", "Workflow id").option("--plan <id>", "Plan id (workflow+plan address form)").option("--assignment <path>", "Absolute path of the pinned prepared Assignment").option("--resume <path>", "Absolute path of an existing session JSON envelope").option("--harness <path>", "Absolute harness dir override (default: resolved control root)").option("--session-id <id>", `Session id the fresh bind adopts (default: $${SESSION_ID_ENV}, else generated)`).option("--json", "Machine-readable JSON on stdout").action(async (options) => runVerb("bind", options, { workflow_id: options.workflow, plan_id: options.plan }, async (json) => {
20966
21352
  const input = bindInputOf(options);
20967
21353
  pinProcessRoot(harnessOverrideOf(input));
20968
21354
  await printSuccess("bind", await bindPlanSession(input), json);
@@ -21295,7 +21681,7 @@ function describeType(value) {
21295
21681
  return "array";
21296
21682
  return typeof value;
21297
21683
  }
21298
- function isPlainObject11(value) {
21684
+ function isPlainObject13(value) {
21299
21685
  return typeof value === "object" && value !== null && !Array.isArray(value);
21300
21686
  }
21301
21687
  function parseScalar3(raw) {
@@ -21339,7 +21725,7 @@ function isValidMcpUrl(raw) {
21339
21725
  return true;
21340
21726
  }
21341
21727
  function validateManifest(manifest, errors2, warnings) {
21342
- if (!isPlainObject11(manifest)) {
21728
+ if (!isPlainObject13(manifest)) {
21343
21729
  errors2.push("plugin.json: manifest must be a JSON object");
21344
21730
  return;
21345
21731
  }
@@ -21375,7 +21761,7 @@ function validateManifest(manifest, errors2, warnings) {
21375
21761
  }
21376
21762
  }
21377
21763
  if (doc.author !== undefined) {
21378
- if (!isPlainObject11(doc.author)) {
21764
+ if (!isPlainObject13(doc.author)) {
21379
21765
  errors2.push('plugin.json: "author" must be an object with optional string fields name/email/url');
21380
21766
  } else {
21381
21767
  const author = doc.author;
@@ -21398,11 +21784,11 @@ function validateManifest(manifest, errors2, warnings) {
21398
21784
  }
21399
21785
  }
21400
21786
  if (doc.extensions !== undefined) {
21401
- if (!isPlainObject11(doc.extensions)) {
21787
+ if (!isPlainObject13(doc.extensions)) {
21402
21788
  warnings.push('plugin.json: "extensions" is not an object \u2014 ignored');
21403
21789
  } else {
21404
21790
  for (const [namespace, value] of Object.entries(doc.extensions)) {
21405
- if (!isPlainObject11(value)) {
21791
+ if (!isPlainObject13(value)) {
21406
21792
  warnings.push(`plugin.json: "extensions.${namespace}" is not an object \u2014 ignored`);
21407
21793
  }
21408
21794
  }
@@ -21411,7 +21797,7 @@ function validateManifest(manifest, errors2, warnings) {
21411
21797
  }
21412
21798
  function validateMcpServer(name, entry, errors2) {
21413
21799
  const prefix = `mcp.json: mcpServers.${name}`;
21414
- if (!isPlainObject11(entry)) {
21800
+ if (!isPlainObject13(entry)) {
21415
21801
  errors2.push(`${prefix} must be an object`);
21416
21802
  return;
21417
21803
  }
@@ -21445,7 +21831,7 @@ function validateMcpServer(name, entry, errors2) {
21445
21831
  }
21446
21832
  }
21447
21833
  if (server.env !== undefined) {
21448
- if (!isPlainObject11(server.env)) {
21834
+ if (!isPlainObject13(server.env)) {
21449
21835
  errors2.push(`${prefix}: "env" must be an object of strings`);
21450
21836
  } else {
21451
21837
  for (const [key, value] of Object.entries(server.env)) {
@@ -21484,7 +21870,7 @@ function validateMcpServer(name, entry, errors2) {
21484
21870
  errors2.push(`${prefix}: "url" must be an absolute http(s) URL without user info or fragment; non-loopback endpoints must use https`);
21485
21871
  }
21486
21872
  if (server.headers !== undefined) {
21487
- if (!isPlainObject11(server.headers)) {
21873
+ if (!isPlainObject13(server.headers)) {
21488
21874
  errors2.push(`${prefix}: "headers" must be an object of strings`);
21489
21875
  } else {
21490
21876
  const seen = new Set;
@@ -21521,7 +21907,7 @@ function validateMcp(root, manifestSchema, errors2) {
21521
21907
  errors2.push(`mcp.json: ${error.message}`);
21522
21908
  return;
21523
21909
  }
21524
- if (!isPlainObject11(parsed)) {
21910
+ if (!isPlainObject13(parsed)) {
21525
21911
  errors2.push("mcp.json: configuration must be a JSON object");
21526
21912
  return;
21527
21913
  }
@@ -21544,7 +21930,7 @@ function validateMcp(root, manifestSchema, errors2) {
21544
21930
  }
21545
21931
  }
21546
21932
  const servers = doc.mcpServers;
21547
- if (!isPlainObject11(servers)) {
21933
+ if (!isPlainObject13(servers)) {
21548
21934
  errors2.push('mcp.json: "mcpServers" is required and must be an object');
21549
21935
  return;
21550
21936
  }
@@ -21645,7 +22031,7 @@ function validateAgentPlugin(root) {
21645
22031
  return { ok: false, errors: errors2, warnings };
21646
22032
  }
21647
22033
  validateManifest(manifest, errors2, warnings);
21648
- const manifestSchema = isPlainObject11(manifest) ? manifest["$schema"] : undefined;
22034
+ const manifestSchema = isPlainObject13(manifest) ? manifest["$schema"] : undefined;
21649
22035
  validateMcp(root, manifestSchema, errors2);
21650
22036
  validateSkills(root, errors2, warnings);
21651
22037
  return { ok: errors2.length === 0, errors: errors2, warnings };
@@ -24791,7 +25177,7 @@ sddCommand.command("exec").description("Run an argv child bound to a resolved SD
24791
25177
  }
24792
25178
  });
24793
25179
  registerSddEvidenceCommands(sddCommand);
24794
- var iterationCommand = program2.command("iteration").description("iteration phase-gate + push-cadence checks (engine-backed)");
25180
+ var iterationCommand = program2.command("iteration").description("iteration phase-gate + push-cadence checks and workflow registration (engine-backed)");
24795
25181
  function printChecklist(label, gate3) {
24796
25182
  if (gate3.ok) {
24797
25183
  console.log(import_picocolors4.default.green(`${label}: OK`));
@@ -24866,6 +25252,61 @@ iterationCommand.command("push-cadence").description("\xA75.1a push-cadence prob
24866
25252
  }
24867
25253
  process.exitCode = 1;
24868
25254
  });
25255
+ 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) => {
25256
+ try {
25257
+ 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>]";
25258
+ if (command.args.length > 0) {
25259
+ throw new SddScriptError(`unexpected argument(s): ${command.args.join(", ")}
25260
+ ${usage}`, 2);
25261
+ }
25262
+ const missing = [
25263
+ ["--workflow", options.workflow],
25264
+ ["--compass-ref", options.compassRef],
25265
+ ["--branch-base", options.branchBase],
25266
+ ["--branch-integration", options.branchIntegration],
25267
+ ["--branch-target", options.branchTarget]
25268
+ ].filter(([, value]) => value === undefined || value.trim() === "").map(([flag]) => flag);
25269
+ const rowsRaw = options.row ?? [];
25270
+ if (rowsRaw.length === 0)
25271
+ missing.push("--row");
25272
+ if (missing.length > 0) {
25273
+ throw new SddScriptError(`missing required option(s): ${missing.join(", ")}
25274
+ ${usage}`, 2);
25275
+ }
25276
+ const rows = rowsRaw.map((raw, index) => {
25277
+ let parsed;
25278
+ try {
25279
+ parsed = JSON.parse(raw);
25280
+ } catch (error) {
25281
+ throw new SddScriptError(`--row[${index}] is not valid JSON: ${error.message}
25282
+ ${usage}`, 2);
25283
+ }
25284
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
25285
+ throw new SddScriptError(`--row[${index}] must be a JSON object {id,title,file} \u2014 got ${JSON.stringify(raw)}
25286
+ ${usage}`, 2);
25287
+ }
25288
+ return parsed;
25289
+ });
25290
+ assertWorkflowId(options.workflow);
25291
+ const harnessDir = resolveProcessHarnessDir3(options.harness);
25292
+ if (!harnessDir) {
25293
+ throw new Error(`harness dir not found from ${process.cwd()} \u2014 pass --harness <path>`);
25294
+ }
25295
+ setArtifactStore(createFsStore(harnessDir));
25296
+ const result = await registerIterationWorkflow(options.workflow, {
25297
+ harnessDir,
25298
+ compassRef: options.compassRef,
25299
+ branch: { base: options.branchBase, integration: options.branchIntegration, target: options.branchTarget },
25300
+ rows,
25301
+ ...options.project !== undefined ? { project: options.project } : {},
25302
+ ...options.startedAt !== undefined ? { startedAt: options.startedAt } : {}
25303
+ });
25304
+ 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`));
25305
+ console.log(` snapshot: ${result.snapshotPath}`);
25306
+ } catch (error) {
25307
+ failScript(error, "iteration register");
25308
+ }
25309
+ });
24869
25310
  var dispatchCommand = program2.command("dispatch").description("Assignment field + default-branch gate checks (engine-backed)");
24870
25311
  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
25312
  try {
@@ -25220,35 +25661,118 @@ function cleanupEvidenceBases(snapshots) {
25220
25661
  }
25221
25662
  function cleanupProbeMerged(mainRoot, bases) {
25222
25663
  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`));
25664
+ const listsByOid = new Map;
25665
+ const failedOids = new Set;
25666
+ for (const { base, oid } of bases.resolved) {
25667
+ let list = listsByOid.get(oid);
25668
+ if (list === undefined && !failedOids.has(oid)) {
25669
+ try {
25670
+ list = gitSync(["branch", "--merged", oid, "--format=%(refname:short)"], mainRoot).split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "");
25671
+ listsByOid.set(oid, list);
25672
+ } catch (error) {
25673
+ failedOids.add(oid);
25674
+ 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`));
25675
+ }
25228
25676
  }
25677
+ if (list !== undefined)
25678
+ merged[base] = list;
25229
25679
  }
25230
25680
  return merged;
25231
25681
  }
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;
25682
+ function cleanupResolveBases(mainRoot, bases) {
25683
+ const resolved = [];
25684
+ const unresolved = [];
25685
+ for (const base of new Set(bases)) {
25686
+ try {
25687
+ const oid = gitSync(["rev-parse", "--verify", "--quiet", `${base}^{commit}`], mainRoot).trim();
25688
+ resolved.push({ base, oid });
25689
+ } catch (error) {
25690
+ unresolved.push({ base, detail: cleanupGitMessage(error) });
25691
+ 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`));
25692
+ }
25238
25693
  }
25694
+ return { resolved, unresolved };
25239
25695
  }
25240
- function cleanupProbeRemoteEvidence(mainRoot, remoteBranches, bases) {
25696
+ function cleanupProbeRemoteEvidence(mainRoot, candidates, bases, options) {
25697
+ if (!options.remoteRequested || candidates.length === 0)
25698
+ return [];
25699
+ const oidByBase = new Map(bases.resolved.map((entry) => [entry.base, entry.oid]));
25700
+ const unresolvedBases = new Set(bases.unresolved.map((entry) => entry.base));
25241
25701
  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;
25702
+ const summaries = new Map;
25703
+ const record = (candidate, ancestor, detail) => {
25704
+ if (ancestor !== null) {
25705
+ evidence.push({ branch: candidate.branch, tip: candidate.tip, base: candidate.base, ancestor, prMerged: null });
25706
+ }
25707
+ if (ancestor !== true) {
25708
+ const summary = summaries.get(candidate.branch) ?? { notAncestor: 0, indeterminate: 0 };
25709
+ if (ancestor === false)
25710
+ summary.notAncestor++;
25711
+ else
25712
+ summary.indeterminate++;
25713
+ summaries.set(candidate.branch, summary);
25714
+ if (options.verbose) {
25715
+ console.error(import_picocolors4.default.yellow(`worktree cleanup: note: ancestry of ${candidate.branch} against ${JSON.stringify(candidate.base)}: ${detail}`));
25716
+ }
25717
+ }
25718
+ };
25719
+ const sweep = (mode, baseOid) => {
25720
+ try {
25721
+ const rows = new Map;
25722
+ for (const line of gitSync(["for-each-ref", mode, baseOid, "--format=%(refname)%09%(objectname)", "refs/remotes/origin"], mainRoot).split(/\r?\n/)) {
25723
+ if (line.trim() === "")
25724
+ continue;
25725
+ const tab = line.indexOf("\t");
25726
+ rows.set(line.slice(0, tab), line.slice(tab + 1));
25727
+ }
25728
+ return rows;
25729
+ } catch {
25730
+ return null;
25731
+ }
25732
+ };
25733
+ const byBaseOid = new Map;
25734
+ for (const candidate of candidates) {
25735
+ const baseOid = oidByBase.get(candidate.base);
25736
+ if (baseOid === undefined || unresolvedBases.has(candidate.base)) {
25737
+ record(candidate, null, "owner base does not resolve \u2014 no evidence row recorded (candidates refuse)");
25738
+ continue;
25739
+ }
25740
+ const group = byBaseOid.get(baseOid) ?? [];
25741
+ group.push(candidate);
25742
+ byBaseOid.set(baseOid, group);
25743
+ }
25744
+ for (const [baseOid, group] of byBaseOid) {
25745
+ const positive = sweep("--merged", baseOid);
25746
+ const positiveFailed = positive === null;
25747
+ const residual = [];
25748
+ for (const candidate of group) {
25749
+ const attested = !positiveFailed && positive.get(`refs/remotes/origin/${candidate.branch}`) === candidate.tip;
25750
+ if (attested) {
25751
+ record(candidate, true, "ancestor");
25752
+ } else {
25753
+ residual.push(candidate);
25754
+ }
25755
+ }
25756
+ if (residual.length === 0)
25757
+ continue;
25758
+ const negative = positiveFailed ? null : sweep("--no-merged", baseOid);
25759
+ for (const candidate of residual) {
25760
+ if (negative !== null && negative.get(`refs/remotes/origin/${candidate.branch}`) === candidate.tip) {
25761
+ record(candidate, false, "not an ancestor");
25762
+ } else {
25763
+ 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)";
25764
+ record(candidate, null, detail);
25248
25765
  }
25249
- evidence.push({ branch: remote.branch, tip: remote.tip, base, ancestor, prMerged: null });
25250
25766
  }
25251
25767
  }
25768
+ for (const [branch, summary] of summaries) {
25769
+ const parts = [];
25770
+ if (summary.notAncestor > 0)
25771
+ parts.push(`not-an-ancestor ${summary.notAncestor}`);
25772
+ if (summary.indeterminate > 0)
25773
+ parts.push(`indeterminate ${summary.indeterminate}`);
25774
+ console.error(import_picocolors4.default.yellow(`worktree cleanup: note: remote ${branch}: ${parts.join(", ")}`));
25775
+ }
25252
25776
  return evidence;
25253
25777
  }
25254
25778
  function cleanupProbe(input) {
@@ -25291,6 +25815,7 @@ function cleanupProbe(input) {
25291
25815
  tip: entry.tip
25292
25816
  }));
25293
25817
  const evidenceBases = cleanupEvidenceBases(snapshots);
25818
+ const resolvedBases = cleanupResolveBases(input.mainRoot, evidenceBases);
25294
25819
  return {
25295
25820
  selected,
25296
25821
  snapshots,
@@ -25299,15 +25824,67 @@ function cleanupProbe(input) {
25299
25824
  defaultBranch: cleanupProbeDefaultBranch(input.mainRoot, worktrees[0]?.branch ?? null),
25300
25825
  localBranches,
25301
25826
  remoteBranches,
25302
- mergedLocalBranches: cleanupProbeMerged(input.mainRoot, evidenceBases),
25303
- remoteEvidence: cleanupProbeRemoteEvidence(input.mainRoot, remoteBranches, evidenceBases)
25827
+ mainRoot: input.mainRoot,
25828
+ resolvedBases,
25829
+ mergedLocalBranches: cleanupProbeMerged(input.mainRoot, resolvedBases)
25304
25830
  };
25305
25831
  }
25306
- function cleanupBuildFacts(probe, scope, remoteSelected) {
25832
+ function cleanupWorktreeCandidate(worktree, scope, snapshots) {
25833
+ if (scope.asserted.size > 0 && !scope.asserted.has(cleanupPathKey(worktree.path)))
25834
+ return false;
25835
+ const claims = cleanupWorktreeClaims(worktree.path, snapshots);
25836
+ if (claims.length > 0)
25837
+ return scope.allWorkflows || claims.some((claim) => claim.workflowId === scope.workflowId);
25838
+ if (scope.allWorkflows)
25839
+ return true;
25840
+ const checkedOut = worktree.branch ?? "";
25841
+ if (checkedOut === "")
25842
+ return false;
25843
+ return cleanupBranchClaims(checkedOut, snapshots).some((claim) => claim.workflowId === scope.workflowId);
25844
+ }
25845
+ function cleanupBranchCandidate(claims, scope) {
25846
+ if (!scope.allWorkflows && !claims.some((claim) => claim.workflowId === scope.workflowId))
25847
+ return false;
25848
+ if (scope.asserted.size === 0)
25849
+ return true;
25850
+ const ownerKeys = new Set(scope.assertedOwners.map((owner) => JSON.stringify(owner)));
25851
+ return claims.some((claim) => ownerKeys.has(JSON.stringify(claim)));
25852
+ }
25853
+ function cleanupResolveScope(probe, request) {
25854
+ const assertedOwners = [];
25855
+ for (const key of request.asserted) {
25856
+ const worktree = probe.worktrees.find((candidate) => cleanupPathKey(candidate.path) === key);
25857
+ if (worktree === undefined) {
25858
+ console.error(import_picocolors4.default.yellow(`worktree cleanup: note: --worktree ${key} does not match an inventoried worktree \u2014 no target is fabricated for it`));
25859
+ continue;
25860
+ }
25861
+ if (!cleanupWorktreeCandidate(worktree, request, probe.snapshots)) {
25862
+ 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`));
25863
+ continue;
25864
+ }
25865
+ let attribution = cleanupDistinctOwner(cleanupWorktreeClaims(worktree.path, probe.snapshots));
25866
+ if (attribution.owner === null && !attribution.ambiguous) {
25867
+ const checkedOut = worktree.branch ?? "";
25868
+ if (checkedOut !== "")
25869
+ attribution = cleanupDistinctOwner(cleanupBranchClaims(checkedOut, probe.snapshots));
25870
+ }
25871
+ if (attribution.owner !== null)
25872
+ assertedOwners.push(attribution.owner);
25873
+ }
25874
+ return { ...request, scoped: !request.allWorkflows, assertedOwners };
25875
+ }
25876
+ function cleanupBuildFacts(probe, scope, options) {
25877
+ const ownerBase = (owner) => {
25878
+ const ownerDoc = probe.snapshots.find((doc) => doc.id === owner.workflowId);
25879
+ if (ownerDoc === undefined)
25880
+ return;
25881
+ const base = owner.planId !== undefined && ownerDoc.type === "iteration" ? ownerDoc.branch?.integration : ownerDoc.branch?.target;
25882
+ return typeof base === "string" && base !== "" ? base : undefined;
25883
+ };
25307
25884
  const targets = [];
25308
25885
  const notes = new Set;
25309
25886
  for (const worktree of probe.worktrees) {
25310
- if (scope.scoped && !scope.asserted.has(cleanupPathKey(worktree.path)))
25887
+ if (!cleanupWorktreeCandidate(worktree, scope, probe.snapshots))
25311
25888
  continue;
25312
25889
  let attribution = cleanupDistinctOwner(cleanupWorktreeClaims(worktree.path, probe.snapshots));
25313
25890
  if (attribution.owner === null && !attribution.ambiguous && scope.asserted.has(cleanupPathKey(worktree.path))) {
@@ -25321,19 +25898,31 @@ function cleanupBuildFacts(probe, scope, remoteSelected) {
25321
25898
  targets.push({ kind: "worktree", ref: worktree.path, branch: worktree.branch ?? "", tip: worktree.tip, owner: attribution.owner });
25322
25899
  }
25323
25900
  for (const local of probe.localBranches) {
25324
- const attribution = cleanupDistinctOwner(cleanupBranchClaims(local.branch, probe.snapshots));
25901
+ const claims = cleanupBranchClaims(local.branch, probe.snapshots);
25902
+ if (!cleanupBranchCandidate(claims, scope))
25903
+ continue;
25904
+ const attribution = cleanupDistinctOwner(claims);
25325
25905
  if (attribution.ambiguous) {
25326
25906
  notes.add(`branch ${local.branch} is claimed by more than one snapshot row \u2014 treated as unowned (refuses)`);
25327
25907
  }
25328
25908
  targets.push({ kind: "local-branch", ref: local.branch, branch: local.branch, tip: local.tip, owner: attribution.owner });
25329
25909
  }
25330
- if (remoteSelected) {
25910
+ const remoteCandidates = [];
25911
+ if (options.remoteRequested) {
25331
25912
  for (const remote of probe.remoteBranches) {
25332
- const attribution = cleanupDistinctOwner(cleanupBranchClaims(remote.branch, probe.snapshots));
25913
+ const claims = cleanupBranchClaims(remote.branch, probe.snapshots);
25914
+ if (!cleanupBranchCandidate(claims, scope))
25915
+ continue;
25916
+ const attribution = cleanupDistinctOwner(claims);
25333
25917
  if (attribution.ambiguous) {
25334
25918
  notes.add(`remote branch ${remote.branch} is claimed by more than one snapshot row \u2014 treated as unowned (refuses)`);
25335
25919
  }
25336
25920
  targets.push({ kind: "remote-branch", ref: `origin/${remote.branch}`, branch: remote.branch, tip: remote.tip, owner: attribution.owner });
25921
+ if (attribution.owner !== null) {
25922
+ const base = ownerBase(attribution.owner);
25923
+ if (base !== undefined)
25924
+ remoteCandidates.push({ branch: remote.branch, tip: remote.tip, base });
25925
+ }
25337
25926
  }
25338
25927
  }
25339
25928
  for (const note of notes)
@@ -25350,17 +25939,14 @@ function cleanupBuildFacts(probe, scope, remoteSelected) {
25350
25939
  snapshots: probe.snapshots,
25351
25940
  defaultBranch: probe.defaultBranch,
25352
25941
  mergedLocalBranches: probe.mergedLocalBranches,
25353
- remoteEvidence: probe.remoteEvidence
25942
+ remoteEvidence: cleanupProbeRemoteEvidence(probe.mainRoot, remoteCandidates, probe.resolvedBases, options)
25354
25943
  };
25355
25944
  const branchBase = new Map;
25356
25945
  for (const target of targets) {
25357
25946
  if (target.kind !== "local-branch" || target.owner === null)
25358
25947
  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 !== "")
25948
+ const base = ownerBase(target.owner);
25949
+ if (base !== undefined)
25364
25950
  branchBase.set(target.ref, base);
25365
25951
  }
25366
25952
  return { facts, branchBase };
@@ -25382,10 +25968,10 @@ function cleanupBranchDeletionCwd(base, probe, mainRoot) {
25382
25968
  const host = probe.worktrees.find((worktree) => worktree.branch === base);
25383
25969
  return host?.path ?? mainRoot;
25384
25970
  }
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) => {
25971
+ 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
25972
  try {
25387
25973
  if (!options.workflow) {
25388
- throw new SddScriptError("usage: worktree cleanup --workflow <id> [--harness <path>] [--apply] [--remote] [--worktree <path>] [--ignore-unreadable-snapshots]", 2);
25974
+ throw new SddScriptError("usage: worktree cleanup --workflow <id> [--harness <path>] [--apply] [--remote] [--worktree <path>] [--all-workflows] [--verbose] [--ignore-unreadable-snapshots]", 2);
25389
25975
  }
25390
25976
  const main = readMainWorktree();
25391
25977
  if (main === null)
@@ -25395,8 +25981,9 @@ worktreeCommand.command("cleanup").description("Plan (and with --apply execute)
25395
25981
  throw new Error("harness directory not found");
25396
25982
  const snapshotPath = resolveSnapshotPath(options.workflow, harnessDir);
25397
25983
  const workflowRoot = resolveWorkflowDir(harnessDir, { harnessDir });
25398
- const scope = {
25399
- scoped: (options.worktree?.length ?? 0) > 0,
25984
+ const scopeRequest = {
25985
+ workflowId: options.workflow,
25986
+ allWorkflows: options.allWorkflows === true,
25400
25987
  asserted: new Set((options.worktree ?? []).map((candidate) => cleanupPathKey(candidate)))
25401
25988
  };
25402
25989
  const probeInput = {
@@ -25406,8 +25993,12 @@ worktreeCommand.command("cleanup").description("Plan (and with --apply execute)
25406
25993
  workflowId: options.workflow
25407
25994
  };
25408
25995
  const ignoreUnreadableSiblings = options.ignoreUnreadableSnapshots === true;
25996
+ const evidenceOptions = { remoteRequested: options.remote === true, verbose: options.verbose === true };
25409
25997
  const probe1 = cleanupProbe(probeInput);
25410
- const built1 = cleanupBuildFacts(probe1, scope, options.remote === true);
25998
+ const scope = cleanupResolveScope(probe1, scopeRequest);
25999
+ 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);
26000
+ 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`));
26001
+ const built1 = cleanupBuildFacts(probe1, scope, evidenceOptions);
25411
26002
  const plan1 = cleanupGuardUnreadableSiblings(planWorktreeCleanup(probe1.selected, built1.facts), probe1, ignoreUnreadableSiblings);
25412
26003
  cleanupPrintPlan(`worktree cleanup (workflow ${options.workflow}): plan`, plan1);
25413
26004
  if (options.apply !== true)
@@ -25440,7 +26031,7 @@ worktreeCommand.command("cleanup").description("Plan (and with --apply execute)
25440
26031
  }
25441
26032
  }
25442
26033
  const probe2 = cleanupProbe(probeInput);
25443
- const built2 = cleanupBuildFacts(probe2, scope, options.remote === true);
26034
+ const built2 = cleanupBuildFacts(probe2, scope, evidenceOptions);
25444
26035
  const plan2 = cleanupGuardUnreadableSiblings(planWorktreeCleanup(probe2.selected, built2.facts), probe2, ignoreUnreadableSiblings);
25445
26036
  cleanupPrintPlan(`worktree cleanup (workflow ${options.workflow}): post-removal re-plan`, plan2);
25446
26037
  for (const decision of plan2) {
@@ -25490,7 +26081,7 @@ worktreeCommand.command("cleanup").description("Plan (and with --apply execute)
25490
26081
  }
25491
26082
  if (releasedBranches.size > 0) {
25492
26083
  const probe3 = cleanupProbe(probeInput);
25493
- const built3 = cleanupBuildFacts(probe3, scope, options.remote === true);
26084
+ const built3 = cleanupBuildFacts(probe3, scope, evidenceOptions);
25494
26085
  const plan3 = cleanupGuardUnreadableSiblings(planWorktreeCleanup(probe3.selected, built3.facts), probe3, ignoreUnreadableSiblings).filter((decision) => decision.kind === "local-branch" && releasedBranches.has(decision.ref));
25495
26086
  cleanupPrintPlan(`worktree cleanup (workflow ${options.workflow}): post-deferred-removal re-plan`, plan3);
25496
26087
  for (const decision of plan3) {
@@ -25824,16 +26415,113 @@ function parseAuditScaffoldInput(text) {
25824
26415
  throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].dependsOn must be "none", "plans/NNN-*.md", or a plan number NNN`, 2);
25825
26416
  }
25826
26417
  const dependsOn = rawDependsOn === undefined ? undefined : /^\d{3}$/.test(rawDependsOn) ? `plans/${rawDependsOn}-*.md` : rawDependsOn;
26418
+ const confidence = finding.confidence === undefined ? "MED" : finding.confidence;
26419
+ if (typeof confidence !== "string" || AUDIT_CONFIDENCES.find((c) => c === confidence) === undefined) {
26420
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].confidence must be one of ${AUDIT_CONFIDENCES.join("|")}`, 2);
26421
+ }
26422
+ const rawEvidence = finding.evidence;
26423
+ if (rawEvidence !== undefined && !Array.isArray(rawEvidence)) {
26424
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence must be an array of strings or {file, line?, description} objects`, 2);
26425
+ }
26426
+ const evidence = (rawEvidence ?? []).map((item, itemIndex) => {
26427
+ if (typeof item === "string") {
26428
+ if (item.trim() === "") {
26429
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence[${itemIndex}] must be a non-empty string or a {file, line?, description} object`, 2);
26430
+ }
26431
+ return item;
26432
+ }
26433
+ if (typeof item !== "object" || item === null || Array.isArray(item)) {
26434
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence[${itemIndex}] must be a non-empty string or a {file, line?, description} object`, 2);
26435
+ }
26436
+ const loc = item;
26437
+ if (typeof loc.file !== "string" || loc.file === "") {
26438
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence[${itemIndex}].file is required and must be a repository-relative path`, 2);
26439
+ }
26440
+ if (loc.line !== undefined && (typeof loc.line !== "number" || !Number.isSafeInteger(loc.line) || loc.line <= 0)) {
26441
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence[${itemIndex}].line must be a positive integer when present`, 2);
26442
+ }
26443
+ if (typeof loc.description !== "string" || loc.description.trim() === "") {
26444
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].evidence[${itemIndex}].description must be a non-empty string`, 2);
26445
+ }
26446
+ return {
26447
+ file: loc.file,
26448
+ ...loc.line !== undefined ? { line: loc.line } : {},
26449
+ description: loc.description
26450
+ };
26451
+ });
26452
+ const rawFingerprint = finding.fingerprint;
26453
+ if (rawFingerprint !== undefined && (typeof rawFingerprint !== "string" || rawFingerprint === "")) {
26454
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].fingerprint must be a non-empty string when present`, 2);
26455
+ }
26456
+ const rawTrace = finding.trace;
26457
+ if (rawTrace !== undefined && !Array.isArray(rawTrace)) {
26458
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace must be an array of {kind, file, line, scope, description} objects`, 2);
26459
+ }
26460
+ const trace = rawTrace === undefined ? undefined : rawTrace.map((step, stepIndex) => {
26461
+ if (typeof step !== "object" || step === null || Array.isArray(step)) {
26462
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}] must be a {kind, file, line, scope, description} object`, 2);
26463
+ }
26464
+ const s = step;
26465
+ if (!AUDIT_TRACE_KINDS.find((k) => k === s.kind)) {
26466
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}].kind must be one of ${AUDIT_TRACE_KINDS.join("|")}`, 2);
26467
+ }
26468
+ if (typeof s.file !== "string" || s.file === "") {
26469
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}].file is required and must be a repository-relative path`, 2);
26470
+ }
26471
+ if (typeof s.line !== "number" || !Number.isSafeInteger(s.line) || s.line <= 0) {
26472
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}].line must be a positive integer`, 2);
26473
+ }
26474
+ if (typeof s.scope !== "string" || s.scope.trim() === "") {
26475
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}].scope must be a non-empty string`, 2);
26476
+ }
26477
+ if (typeof s.description !== "string" || s.description.trim() === "") {
26478
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].trace[${stepIndex}].description must be a non-empty string`, 2);
26479
+ }
26480
+ return { kind: s.kind, file: s.file, line: s.line, scope: s.scope, description: s.description };
26481
+ });
26482
+ const rawSeverity = finding.severity;
26483
+ if (rawSeverity !== undefined) {
26484
+ if (typeof rawSeverity !== "object" || rawSeverity === null || Array.isArray(rawSeverity)) {
26485
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].severity must be a {likelihood, impact, overall} object`, 2);
26486
+ }
26487
+ const sev = rawSeverity;
26488
+ for (const field of ["likelihood", "impact", "overall"]) {
26489
+ if (!AUDIT_SEVERITY_RANKS.find((r) => r === sev[field])) {
26490
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].severity.${field} must be one of ${AUDIT_SEVERITY_RANKS.join("|")}`, 2);
26491
+ }
26492
+ }
26493
+ }
26494
+ const severity = rawSeverity === undefined ? undefined : {
26495
+ likelihood: rawSeverity.likelihood,
26496
+ impact: rawSeverity.impact,
26497
+ overall: rawSeverity.overall
26498
+ };
26499
+ const freeText = (field) => {
26500
+ const raw2 = finding[field];
26501
+ if (raw2 === undefined)
26502
+ return;
26503
+ if (typeof raw2 !== "string" || raw2.trim() === "") {
26504
+ throw new SddScriptError(`usage: audit scaffold \u2014 findings[${index}].${field} must be a non-empty string`, 2);
26505
+ }
26506
+ return raw2.trim();
26507
+ };
26508
+ const fixSketch = freeText("fixSketch");
26509
+ const verification = freeText("verification");
25827
26510
  return {
25828
26511
  title,
25829
26512
  category,
25830
26513
  impact,
25831
26514
  effort,
25832
26515
  risk,
25833
- confidence: "MED",
25834
- evidence: [],
26516
+ confidence,
26517
+ evidence,
25835
26518
  priority,
25836
- dependsOn
26519
+ ...fixSketch !== undefined ? { fixSketch } : {},
26520
+ ...verification !== undefined ? { verification } : {},
26521
+ ...dependsOn !== undefined ? { dependsOn } : {},
26522
+ ...rawFingerprint !== undefined ? { fingerprint: rawFingerprint } : {},
26523
+ ...trace !== undefined ? { trace } : {},
26524
+ ...severity !== undefined ? { severity } : {}
25837
26525
  };
25838
26526
  });
25839
26527
  return { findings, needsVerification: parseNeedsVerification(needsVerificationRaw), hardeningChecked: parseHardeningChecked(hardeningCheckedRaw) };
@@ -25912,13 +26600,21 @@ auditCommand.command("scaffold").description("Scaffold an audit-<date>/ plan dir
25912
26600
  const outDir = options.dir !== undefined ? resolveCliPath(options.dir) : resolveCliPath(`audit-${date}`);
25913
26601
  const input = parseAuditScaffoldInput(fs12.readFileSync(abs, "utf8"));
25914
26602
  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
- });
26603
+ let result;
26604
+ try {
26605
+ result = scaffoldAuditPlan(outDir, input.findings, {
26606
+ date,
26607
+ repoName: options.repo,
26608
+ repoShortSha: sha,
26609
+ needsVerification: input.needsVerification,
26610
+ hardeningChecked: input.hardeningChecked
26611
+ });
26612
+ } catch (error) {
26613
+ if (error instanceof TypeError && error.message.includes("audit.finding.")) {
26614
+ throw new SddScriptError(error.message, 2);
26615
+ }
26616
+ throw error;
26617
+ }
25922
26618
  const count = result.files.length;
25923
26619
  console.log(import_picocolors4.default.green(`audit scaffold: OK \u2014 ${count} plan file${count === 1 ? "" : "s"} in ${result.outDir}`));
25924
26620
  for (const file of result.files)
@@ -26061,6 +26757,8 @@ var AUDIT_PRIORITY_LOOKUP = lookupTable(AUDIT_PRIORITIES);
26061
26757
  var AUDIT_EFFORT_LOOKUP = lookupTable(AUDIT_EFFORTS);
26062
26758
  var AUDIT_RISK_LOOKUP = lookupTable(AUDIT_RISKS);
26063
26759
  var AUDIT_CATEGORY_LOOKUP = lookupTable(AUDIT_CATEGORIES);
26760
+ var AUDIT_TRACE_KINDS = ["entrypoint", "propagation", "sink"];
26761
+ var AUDIT_SEVERITY_RANKS = ["informational", "low", "medium", "high", "critical"];
26064
26762
  var HOST_SIGNALS = [
26065
26763
  "subagent_type",
26066
26764
  "question",