@erzhe/harness-kit 0.5.1 → 0.6.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.
@@ -6733,7 +6733,7 @@ var require_log = __commonJS({
6733
6733
  if (logLevel === "debug")
6734
6734
  console.log(...messages);
6735
6735
  }
6736
- function warn2(logLevel, warning) {
6736
+ function warn3(logLevel, warning) {
6737
6737
  if (logLevel === "debug" || logLevel === "warn") {
6738
6738
  if (typeof node_process.emitWarning === "function")
6739
6739
  node_process.emitWarning(warning);
@@ -6742,7 +6742,7 @@ var require_log = __commonJS({
6742
6742
  }
6743
6743
  }
6744
6744
  exports2.debug = debug;
6745
- exports2.warn = warn2;
6745
+ exports2.warn = warn3;
6746
6746
  }
6747
6747
  });
6748
6748
 
@@ -16943,41 +16943,41 @@ var require_queue = __commonJS({
16943
16943
  queue.drained = drained;
16944
16944
  return queue;
16945
16945
  function push(value) {
16946
- var p = new Promise(function(resolve11, reject) {
16946
+ var p = new Promise(function(resolve12, reject) {
16947
16947
  pushCb(value, function(err2, result) {
16948
16948
  if (err2) {
16949
16949
  reject(err2);
16950
16950
  return;
16951
16951
  }
16952
- resolve11(result);
16952
+ resolve12(result);
16953
16953
  });
16954
16954
  });
16955
16955
  p.catch(noop);
16956
16956
  return p;
16957
16957
  }
16958
16958
  function unshift(value) {
16959
- var p = new Promise(function(resolve11, reject) {
16959
+ var p = new Promise(function(resolve12, reject) {
16960
16960
  unshiftCb(value, function(err2, result) {
16961
16961
  if (err2) {
16962
16962
  reject(err2);
16963
16963
  return;
16964
16964
  }
16965
- resolve11(result);
16965
+ resolve12(result);
16966
16966
  });
16967
16967
  });
16968
16968
  p.catch(noop);
16969
16969
  return p;
16970
16970
  }
16971
16971
  function drained() {
16972
- var p = new Promise(function(resolve11) {
16972
+ var p = new Promise(function(resolve12) {
16973
16973
  process.nextTick(function() {
16974
16974
  if (queue.idle()) {
16975
- resolve11();
16975
+ resolve12();
16976
16976
  } else {
16977
16977
  var previousDrain = queue.drain;
16978
16978
  queue.drain = function() {
16979
16979
  if (typeof previousDrain === "function") previousDrain();
16980
- resolve11();
16980
+ resolve12();
16981
16981
  queue.drain = previousDrain;
16982
16982
  };
16983
16983
  }
@@ -17463,9 +17463,9 @@ var require_stream3 = __commonJS({
17463
17463
  });
17464
17464
  }
17465
17465
  _getStat(filepath) {
17466
- return new Promise((resolve11, reject) => {
17466
+ return new Promise((resolve12, reject) => {
17467
17467
  this._stat(filepath, this._fsStatSettings, (error, stats) => {
17468
- return error === null ? resolve11(stats) : reject(error);
17468
+ return error === null ? resolve12(stats) : reject(error);
17469
17469
  });
17470
17470
  });
17471
17471
  }
@@ -17489,10 +17489,10 @@ var require_async5 = __commonJS({
17489
17489
  this._readerStream = new stream_1.default(this._settings);
17490
17490
  }
17491
17491
  dynamic(root, options) {
17492
- return new Promise((resolve11, reject) => {
17492
+ return new Promise((resolve12, reject) => {
17493
17493
  this._walkAsync(root, options, (error, entries) => {
17494
17494
  if (error === null) {
17495
- resolve11(entries);
17495
+ resolve12(entries);
17496
17496
  } else {
17497
17497
  reject(error);
17498
17498
  }
@@ -17502,10 +17502,10 @@ var require_async5 = __commonJS({
17502
17502
  async static(patterns, options) {
17503
17503
  const entries = [];
17504
17504
  const stream = this._readerStream.static(patterns, options);
17505
- return new Promise((resolve11, reject) => {
17505
+ return new Promise((resolve12, reject) => {
17506
17506
  stream.once("error", reject);
17507
17507
  stream.on("data", (entry) => entries.push(entry));
17508
- stream.once("end", () => resolve11(entries));
17508
+ stream.once("end", () => resolve12(entries));
17509
17509
  });
17510
17510
  }
17511
17511
  };
@@ -18180,12 +18180,12 @@ var {
18180
18180
  } = import_index.default;
18181
18181
 
18182
18182
  // src/cli.ts
18183
- var import_node_path18 = require("node:path");
18183
+ var import_node_path19 = require("node:path");
18184
18184
 
18185
18185
  // package.json
18186
18186
  var package_default = {
18187
18187
  name: "@erzhe/harness-kit",
18188
- version: "0.5.1",
18188
+ version: "0.6.0",
18189
18189
  type: "module",
18190
18190
  description: "AI-friendly repo harness: a manifest.yaml single source of truth that generates AGENTS.md / CLAUDE.md / Cursor rules and enforces invariants, contracts and drift via `harness-kit verify`.",
18191
18191
  keywords: [
@@ -19235,16 +19235,20 @@ function renderAgentsMd(m) {
19235
19235
  L.push("2. Find your change-type in `.agents/routing.md` and read the files it points to. Do NOT full-repo grep and guess.");
19236
19236
  else L.push("2. Read the relevant files before editing. Do NOT full-repo grep and guess.");
19237
19237
  if ((m.modules ?? []).some((mod) => (mod.owns?.length ?? 0) > 0) || m.validation)
19238
- L.push(" If lifecycle hooks are not active, record the task-start commit before editing so committed work can later be checked with `run-checks --base <sha>`.");
19238
+ L.push(" Prefer `harness-kit task start` before editing so committed work stays in the deliver scope.");
19239
19239
  L.push("");
19240
19240
  const hasImpactMap = (m.modules ?? []).some((mod) => (mod.owns?.length ?? 0) > 0) || !!m.validation;
19241
19241
  L.push("Before you finish:");
19242
- if (hasImpactMap)
19242
+ if (hasImpactMap) {
19243
+ L.push(
19244
+ "3. Run `harness-kit deliver` (impact-driven checks + verify + stamp). Only `status=accepted` (or clean `no-change`) means the task is done. If `needs-work`, fix and re-run \u2014 do not claim completion without an accepted stamp."
19245
+ );
19243
19246
  L.push(
19244
- "3. Run `harness-kit run-checks` to verify THIS change (impact-driven) and `harness-kit verify` for drift/invariants. Treat blocking gaps as unfinished work \u2014 close them; only eligible coverage gaps may be waived with a scoped reason."
19247
+ " Optional: `harness-kit task start` before editing so later commits stay in scope; without it, deliver falls back to the current worktree git diff vs HEAD."
19245
19248
  );
19246
- else
19247
- L.push("3. Run `harness-kit verify`. It enforces the invariants below and classifies anything it cannot check automatically.");
19249
+ } else {
19250
+ L.push("3. Run `harness-kit deliver` (or at least `harness-kit verify`). Do not claim completion without a passing stamp/verify.");
19251
+ }
19248
19252
  L.push(
19249
19253
  "4. Read `NEXT ACTIONS` (or JSON `nextActions`): complete every `required | agent` action automatically before finishing; ask the user only for a `required | human` decision. Defer `recommended` maintenance during unrelated product work."
19250
19254
  );
@@ -21036,45 +21040,58 @@ function unsafeHookIssue(issue) {
21036
21040
  function hookActions(hooks) {
21037
21041
  if (hooks.state === "active") return [];
21038
21042
  const configured = hooks.configuredAgents.join(",");
21039
- if (hooks.state === "configured" || hooks.configuredAgents.length > 0 && hooks.issues.every(evidenceOnlyIssue)) {
21040
- return [{
21041
- id: "prove-lifecycle-hooks",
21042
- priority: "required",
21043
- owner: "agent",
21044
- when: "before-harness-ready",
21045
- title: "Prove the lifecycle Hook in a fresh Agent session",
21046
- reason: `A complete Hook is configured for ${configured || "the current Agent"}, but no current SessionStart + Stop evidence proves that the host executed it.`,
21047
- commands: ["harness-kit evidence --repo . --json"],
21048
- completion: "A newly created Agent session finishes once and evidence reports hookActive: true."
21049
- }];
21050
- }
21051
21043
  const unsafe = hooks.issues.filter(unsafeHookIssue);
21052
21044
  if (unsafe.length) {
21053
21045
  return [{
21054
21046
  id: "review-lifecycle-hook-conflict",
21055
- priority: "required",
21047
+ priority: "recommended",
21056
21048
  owner: "human",
21057
- when: "before-harness-ready",
21058
- title: "Approve resolution of an existing Hook configuration conflict",
21059
- reason: "Harness found a Hook file or registration it cannot safely replace: " + unsafe.join("; "),
21049
+ when: "harness-maintenance",
21050
+ title: "Optional: resolve Hook configuration conflict for session intercept",
21051
+ reason: "Harness found a Hook file or registration it cannot safely replace: " + unsafe.join("; ") + ". Delivery still works via harness-kit deliver without hooks.",
21060
21052
  commands: [],
21061
- completion: "The user approves one exact proposed change; the Agent then installs safely and proves hookActive: true in a fresh session."
21053
+ completion: "User approves one exact proposed change, or accepts cooperative deliver-only workflow."
21054
+ }];
21055
+ }
21056
+ if (hooks.state === "configured" || hooks.configuredAgents.length > 0 && hooks.issues.every(evidenceOnlyIssue)) {
21057
+ return [{
21058
+ id: "optional-lifecycle-hook-observation",
21059
+ priority: "recommended",
21060
+ owner: "agent",
21061
+ when: "harness-maintenance",
21062
+ title: "Optional: observe lifecycle Hook on a later Stop",
21063
+ reason: `Hooks are configured for ${configured || "the current Agent"} but not yet observed. This does not block delivery \u2014 use harness-kit deliver for task acceptance.`,
21064
+ commands: ["harness-kit deliver --repo .", "harness-kit evidence --repo . --json"],
21065
+ completion: "Deliver stamp is valid; hook observation is optional."
21066
+ }];
21067
+ }
21068
+ if (!hooks.configuredAgents.length) {
21069
+ return [{
21070
+ id: "optional-install-lifecycle-hooks",
21071
+ priority: "recommended",
21072
+ owner: "agent",
21073
+ when: "harness-maintenance",
21074
+ title: "Optional: install Agent Stop intercept for session-level loops",
21075
+ reason: "Without Stop hooks, agents must run harness-kit deliver cooperatively. Install hooks only when the host supports them.",
21076
+ commands: [
21077
+ "harness-kit deliver --repo .",
21078
+ `harness-kit install-hooks --repo . --stop --agents ${configured || "<current-agent>"}`
21079
+ ],
21080
+ completion: "Deliver works without hooks; hooks only add session intercept when the host fires Stop."
21062
21081
  }];
21063
21082
  }
21064
- const agents = configured || "<current-agent>";
21065
21083
  return [{
21066
- id: hooks.configuredAgents.length ? "repair-lifecycle-hooks" : "install-lifecycle-hooks",
21067
- priority: "required",
21084
+ id: "repair-lifecycle-hooks",
21085
+ priority: "recommended",
21068
21086
  owner: "agent",
21069
- when: "before-harness-ready",
21070
- title: hooks.configuredAgents.length ? "Repair the Agent lifecycle Hook" : "Install the Agent lifecycle Hook",
21071
- reason: "Automatic SessionStart + Stop validation is not currently effective. The Agent should handle safe installation without asking the user to choose an implementation.",
21087
+ when: "harness-maintenance",
21088
+ title: "Optional: repair Agent lifecycle Hook configuration",
21089
+ reason: "Hook configuration is incomplete or degraded. Delivery still uses harness-kit deliver.",
21072
21090
  commands: [
21073
- `harness-kit install-hooks --repo . --stop --agents ${agents}`,
21074
- "harness-kit install-hooks --repo . --stop --agents codex --allow-user-dispatcher # linked Codex worktree only",
21075
- "harness-kit evidence --repo . --json # after one fresh Agent session finishes"
21091
+ `harness-kit install-hooks --repo . --stop --agents ${configured}`,
21092
+ "harness-kit deliver --repo ."
21076
21093
  ],
21077
- completion: "A fresh Agent session records both gates and evidence reports hookActive: true."
21094
+ completion: "Hooks install cleanly or the team accepts deliver-only cooperative mode."
21078
21095
  }];
21079
21096
  }
21080
21097
  function evidenceActions(evidence) {
@@ -21084,14 +21101,13 @@ function evidenceActions(evidence) {
21084
21101
  priority: "required",
21085
21102
  owner: "agent",
21086
21103
  when: "before-finish",
21087
- title: "Create delivery evidence for this change",
21088
- reason: "No run-checks + verify evidence exists for the current worktree/session.",
21104
+ title: "Accept this change with harness-kit deliver",
21105
+ reason: "No delivery stamp exists for the current worktree/session.",
21089
21106
  commands: [
21090
- "harness-kit run-checks --repo . --base <task-start-sha>",
21091
- "harness-kit verify --repo .",
21107
+ "harness-kit deliver --repo .",
21092
21108
  "harness-kit evidence --repo . --json"
21093
21109
  ],
21094
- completion: "Evidence reports valid: true for the current code fingerprint."
21110
+ completion: "deliver reports status=accepted (or no-change) and evidence stamp is valid."
21095
21111
  }];
21096
21112
  }
21097
21113
  if (evidence.stale) {
@@ -21100,14 +21116,10 @@ function evidenceActions(evidence) {
21100
21116
  priority: "required",
21101
21117
  owner: "agent",
21102
21118
  when: "before-finish",
21103
- title: "Re-run validation for the current code",
21104
- reason: "The saved green result belongs to an older code fingerprint.",
21105
- commands: [
21106
- "harness-kit run-checks --repo . --base <task-start-sha>",
21107
- "harness-kit verify --repo .",
21108
- "harness-kit evidence --repo . --json"
21109
- ],
21110
- completion: "Evidence is no longer stale and reports valid: true."
21119
+ title: "Re-run deliver for the current code",
21120
+ reason: "The saved green stamp belongs to an older code fingerprint.",
21121
+ commands: ["harness-kit deliver --repo .", "harness-kit evidence --repo . --json"],
21122
+ completion: "Stamp is no longer stale and deliver reports accepted."
21111
21123
  }];
21112
21124
  }
21113
21125
  if (!evidence.runChecksValid) {
@@ -21116,10 +21128,10 @@ function evidenceActions(evidence) {
21116
21128
  priority: "required",
21117
21129
  owner: "agent",
21118
21130
  when: "before-finish",
21119
- title: "Complete the impact-driven checks",
21131
+ title: "Complete impact-driven delivery checks",
21120
21132
  reason: "The selected checks did not produce valid evidence for the current code.",
21121
- commands: ["harness-kit run-checks --repo . --base <task-start-sha>", "harness-kit evidence --repo . --json"],
21122
- completion: "Evidence reports runChecksValid: true for the current code fingerprint."
21133
+ commands: ["harness-kit deliver --repo .", "harness-kit evidence --repo . --json"],
21134
+ completion: "deliver reports accepted and stamp runChecksValid: true."
21123
21135
  }];
21124
21136
  }
21125
21137
  if (!evidence.verifyPassed || !evidence.valid) {
@@ -21128,22 +21140,22 @@ function evidenceActions(evidence) {
21128
21140
  priority: "required",
21129
21141
  owner: "agent",
21130
21142
  when: "before-finish",
21131
- title: "Complete repository verification",
21143
+ title: "Complete delivery verification",
21132
21144
  reason: "Change checks passed, but matching verify evidence is missing or failed.",
21133
- commands: ["harness-kit verify --repo .", "harness-kit evidence --repo . --json"],
21134
- completion: "Evidence reports valid: true for the current code fingerprint."
21145
+ commands: ["harness-kit deliver --repo .", "harness-kit evidence --repo . --json"],
21146
+ completion: "deliver reports accepted and stamp valid: true."
21135
21147
  }];
21136
21148
  }
21137
21149
  return [];
21138
21150
  }
21139
21151
  function buildHarnessGuidance(input) {
21140
21152
  const gapDetails = input.manifest ? declaredVerificationGaps(input.manifest) : [];
21141
- const nextActions = [
21153
+ const nextActions2 = [
21142
21154
  ...input.evidence ? evidenceActions(input.evidence) : [],
21143
21155
  ...input.hooks ? hookActions(input.hooks) : []
21144
21156
  ];
21145
21157
  const improvement = automationAction(gapDetails);
21146
- if (improvement) nextActions.push(improvement);
21158
+ if (improvement) nextActions2.push(improvement);
21147
21159
  return {
21148
21160
  gapDetails,
21149
21161
  gapSummary: {
@@ -21151,7 +21163,7 @@ function buildHarnessGuidance(input) {
21151
21163
  recommended: gapDetails.filter((item) => item.classification === "recommended").length,
21152
21164
  informational: gapDetails.filter((item) => item.classification === "informational").length
21153
21165
  },
21154
- nextActions
21166
+ nextActions: nextActions2
21155
21167
  };
21156
21168
  }
21157
21169
 
@@ -23075,9 +23087,9 @@ function doctorCmd(repo, opts = {}) {
23075
23087
  const hooks = inspectAgentHookStatus(repo);
23076
23088
  const configuredAgents = hooks.configuredAgents.length ? hooks.configuredAgents.join(", ") : "none";
23077
23089
  if (hooks.state === "active") {
23078
- ok(`ACTIVE \u2014 ${hooks.evidenceAgent} produced current run-checks + verify evidence; configured: ${configuredAgents}`);
23090
+ ok(`ACTIVE \u2014 ${hooks.evidenceAgent} observed on Stop; configured: ${configuredAgents} (optional intercept; task gate is deliver)`);
23079
23091
  } else if (hooks.state === "configured") {
23080
- warn(`CONFIGURED \u2014 ${configuredAgents}; start and finish one fresh Agent session to prove the hooks actually execute`);
23092
+ warn(`CONFIGURED \u2014 ${configuredAgents}; optional intercept not yet observed. Task acceptance: harness-kit deliver`);
23081
23093
  } else {
23082
23094
  warn(`DEGRADED \u2014 configured: ${configuredAgents}; ${hooks.issues.join("; ")}`);
23083
23095
  }
@@ -23406,9 +23418,9 @@ verify: FAILED (${manifestErrors.length} manifest problem(s))`);
23406
23418
  emit("info", "\n5) Agent lifecycle hooks");
23407
23419
  const configuredAgents = hooks.configuredAgents.length ? hooks.configuredAgents.join(", ") : "none";
23408
23420
  if (hooks.state === "active")
23409
- emit("ok", `ACTIVE \u2014 ${hooks.evidenceAgent} produced current run-checks + verify evidence; configured: ${configuredAgents}`);
23421
+ emit("ok", `ACTIVE \u2014 ${hooks.evidenceAgent} observed on Stop; configured: ${configuredAgents} (optional intercept; task gate is deliver)`);
23410
23422
  else if (hooks.state === "configured")
23411
- emit("warn", `CONFIGURED \u2014 ${configuredAgents}; a fresh Agent session has not produced current Stop evidence yet`);
23423
+ emit("warn", `CONFIGURED \u2014 ${configuredAgents}; optional intercept not yet observed. Task acceptance: harness-kit deliver`);
23412
23424
  else emit("warn", `DEGRADED \u2014 configured: ${configuredAgents}; ${hooks.issues.join("; ")}`);
23413
23425
  emit("info", "\n6) Declared verification boundaries");
23414
23426
  if (!guidance.gapSummary.total) emit("ok", "no declared verification boundaries");
@@ -23552,8 +23564,9 @@ var META = `<!-- harness-kit check-loop -->
23552
23564
  You are an AI agent implementing a requirement or fixing a bug in the CURRENT repo.
23553
23565
  Follow the loop below. Run every harness-kit command through
23554
23566
  \`npx -y @erzhe/harness-kit@latest <cmd>\` unless a local build is available.
23555
- The lifecycle hook records the SessionStart base, then runs \`run-checks + verify\` whenever you try to finish.
23556
- Use \`evidence\` to inspect the durable final result.
23567
+ Primary finish gate: \`harness-kit deliver\` (scope \u2192 run-checks + verify \u2192 stamp).
23568
+ Optional Stop hooks only check that stamp; they must not demand a new session.
23569
+ Use \`evidence\` to inspect the durable stamp.
23557
23570
 
23558
23571
  ---
23559
23572
 
@@ -23562,6 +23575,131 @@ function checkLoopCmd() {
23562
23575
  return printSkill(SKILL_REL, META);
23563
23576
  }
23564
23577
 
23578
+ // src/delivery.ts
23579
+ var import_node_crypto7 = require("node:crypto");
23580
+ var import_node_fs15 = require("node:fs");
23581
+ var import_node_path15 = require("node:path");
23582
+ function canonicalTarget2(repo) {
23583
+ try {
23584
+ return (0, import_node_fs15.realpathSync)(repo);
23585
+ } catch {
23586
+ return (0, import_node_path15.resolve)(repo);
23587
+ }
23588
+ }
23589
+ function taskStateDir(repo) {
23590
+ return (0, import_node_path15.join)(gitAdminDir(repo), "harness-kit", "task");
23591
+ }
23592
+ function taskPath(repo) {
23593
+ return (0, import_node_path15.join)(taskStateDir(repo), `current-${sha256(canonicalTarget2(repo)).slice(0, 24)}.json`);
23594
+ }
23595
+ function writePrivateJson2(path, value) {
23596
+ (0, import_node_fs15.mkdirSync)((0, import_node_path15.dirname)(path), { recursive: true });
23597
+ const temp = `${path}.${process.pid}.${(0, import_node_crypto7.randomUUID)()}.tmp`;
23598
+ try {
23599
+ (0, import_node_fs15.writeFileSync)(temp, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
23600
+ (0, import_node_fs15.renameSync)(temp, path);
23601
+ (0, import_node_fs15.chmodSync)(path, 384);
23602
+ } catch (error) {
23603
+ try {
23604
+ (0, import_node_fs15.unlinkSync)(temp);
23605
+ } catch {
23606
+ }
23607
+ throw error;
23608
+ }
23609
+ }
23610
+ function readTaskRecord(repoInput) {
23611
+ const repo = gitRoot(repoInput);
23612
+ const raw = readText(taskPath(repo));
23613
+ if (raw === null) return null;
23614
+ try {
23615
+ const value = JSON.parse(raw);
23616
+ if (value?.schema !== "ai-harness/task/v1" || typeof value.baseSha !== "string" || !value.baseSha) return null;
23617
+ return value;
23618
+ } catch {
23619
+ return null;
23620
+ }
23621
+ }
23622
+ function startTaskRecord(args) {
23623
+ const repo = gitRoot(args.repo);
23624
+ const head = collectChanges(repo, "HEAD", { mode: "exact" }).head;
23625
+ const baseSha = args.baseSha ?? head;
23626
+ if (!baseSha) throw new Error("cannot start task: repository has no HEAD commit and no --base was provided");
23627
+ collectChanges(repo, baseSha, { mode: "exact" });
23628
+ const record = {
23629
+ schema: "ai-harness/task/v1",
23630
+ baseSha,
23631
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
23632
+ ...args.note?.trim() ? { note: args.note.trim() } : {},
23633
+ ...args.hostSessionId ? { hostSessionId: args.hostSessionId } : {},
23634
+ ...args.agent ? { agent: args.agent } : {}
23635
+ };
23636
+ writePrivateJson2(taskPath(repo), record);
23637
+ return record;
23638
+ }
23639
+ function resolveChangeScope(repoInput, opts = {}) {
23640
+ const repo = gitRoot(repoInput);
23641
+ if (opts.base !== void 0) {
23642
+ const changes2 = collectChanges(repo, opts.base, { mode: "exact" });
23643
+ return { kind: "explicit-base", base: opts.base, mode: "exact", changes: changes2, task: readTaskRecord(repo) };
23644
+ }
23645
+ const task = readTaskRecord(repo);
23646
+ if (task) {
23647
+ const changes2 = collectChanges(repo, task.baseSha, { mode: "exact" });
23648
+ return { kind: "task", base: task.baseSha, mode: "exact", changes: changes2, task };
23649
+ }
23650
+ const changes = collectChanges(repo, "HEAD", { mode: "exact" });
23651
+ return { kind: "worktree", base: "HEAD", mode: "exact", changes, task: null };
23652
+ }
23653
+ function stampFromEvidence(repo, session) {
23654
+ if (!session?.lastEvidence) {
23655
+ return { status: "missing", found: false, stale: false, valid: false, reason: "no delivery evidence recorded" };
23656
+ }
23657
+ const evidence = session.lastEvidence;
23658
+ const freshness = inspectValidationEvidenceFreshness(repo, evidence);
23659
+ const runChecksValid = (evidence.runChecksStatus !== void 0 ? evidence.runChecksStatus !== "not-verified" : evidence.ok && evidence.status !== "not-verified") && !freshness.stale;
23660
+ const verifyPassed = evidence.verifyPassed === true;
23661
+ const valid = runChecksValid && verifyPassed && !freshness.error;
23662
+ let status;
23663
+ if (freshness.stale || freshness.error) status = "stale";
23664
+ else if (evidence.status === "no-change" && verifyPassed) status = "no-change";
23665
+ else if (valid) status = "accepted";
23666
+ else status = "needs-work";
23667
+ return {
23668
+ status,
23669
+ found: true,
23670
+ fingerprint: evidence.fingerprint,
23671
+ planFingerprint: evidence.planFingerprint,
23672
+ runChecksStatus: evidence.runChecksStatus ?? evidence.status,
23673
+ verifyPassed: evidence.verifyPassed,
23674
+ scopeBase: evidence.resolvedBase ?? evidence.requestedBase,
23675
+ createdAt: evidence.createdAt,
23676
+ session: session.token,
23677
+ stale: freshness.stale || !!freshness.error,
23678
+ valid,
23679
+ reason: freshness.error || void 0
23680
+ };
23681
+ }
23682
+ function inspectDeliveryStamp(repoInput) {
23683
+ const repo = gitRoot(repoInput);
23684
+ try {
23685
+ return stampFromEvidence(repo, readLatestValidationSession(repo));
23686
+ } catch (error) {
23687
+ return {
23688
+ status: "missing",
23689
+ found: false,
23690
+ stale: false,
23691
+ valid: false,
23692
+ reason: `cannot read delivery stamp: ${error.message}`
23693
+ };
23694
+ }
23695
+ }
23696
+ function stampCoversScope(repoInput, scope) {
23697
+ const stamp = inspectDeliveryStamp(repoInput);
23698
+ if (!stamp.found || stamp.stale || !stamp.valid) return false;
23699
+ if (scope.changes.files.length === 0) return stamp.status === "no-change" || stamp.status === "accepted";
23700
+ return stamp.status === "accepted" && stamp.fingerprint === scope.changes.fingerprint;
23701
+ }
23702
+
23565
23703
  // src/commands/evidence.ts
23566
23704
  function safeHookStatus(repo) {
23567
23705
  try {
@@ -23630,6 +23768,7 @@ function evidenceCmd(repo, opts = {}) {
23630
23768
  const valid = runChecksValid && evidence.verifyPassed === true;
23631
23769
  const hookConfigurationCurrent = session.agent !== "manual" && !!session.hookConfigFingerprint && agentHookConfigurationFingerprint(repo, session.agent) === session.hookConfigFingerprint;
23632
23770
  const hookActive = valid && hookConfigurationCurrent;
23771
+ const stamp = inspectDeliveryStamp(repo);
23633
23772
  const guidance = buildHarnessGuidance({
23634
23773
  hooks,
23635
23774
  evidence: { found: true, stale, runChecksValid, verifyPassed: evidence.verifyPassed, valid }
@@ -23638,6 +23777,7 @@ function evidenceCmd(repo, opts = {}) {
23638
23777
  ...body,
23639
23778
  runChecksValid,
23640
23779
  valid,
23780
+ stamp,
23641
23781
  hookActive,
23642
23782
  hookConfigurationCurrent,
23643
23783
  stale,
@@ -23653,16 +23793,16 @@ function evidenceCmd(repo, opts = {}) {
23653
23793
  process.stdout.write(JSON.stringify(result, null, 2) + "\n");
23654
23794
  return valid ? 0 : 1;
23655
23795
  }
23656
- if (valid) ok(evidence.status);
23657
- else if (stale) err("stale evidence \u2014 the change no longer matches this record");
23658
- else if (evidence.verifyPassed !== true) err("delivery evidence incomplete \u2014 matching verify result is missing or failed");
23796
+ if (valid) ok(`stamp: ${stamp.status}`);
23797
+ else if (stale) err("stale stamp \u2014 the change no longer matches this record");
23798
+ else if (evidence.verifyPassed !== true) err("delivery stamp incomplete \u2014 matching verify result is missing or failed");
23659
23799
  else err(evidence.status);
23660
23800
  info(`session: ${session.token}`);
23661
23801
  info(`agent: ${session.agent}`);
23662
- if (session.agent === "manual") warn("manual evidence does not prove that an installed lifecycle hook executed");
23802
+ if (session.agent === "manual") info("stamp source: deliver/manual (not a lifecycle hook proof)");
23663
23803
  info(`base: ${evidence.requestedBase} -> ${evidence.resolvedBase ?? "empty tree"}`);
23664
23804
  info(`fingerprint: ${evidence.fingerprint}`);
23665
- info(`dirty at SessionStart: ${session.initialDirty.length ? session.initialDirty.join(", ") : "(none)"}`);
23805
+ if (session.initialDirty.length) info(`dirty at task/session start: ${session.initialDirty.join(", ")}`);
23666
23806
  if (evidence.verifyPassed !== void 0) info(`verify: ${evidence.verifyPassed ? "passed" : "failed"}`);
23667
23807
  else err("verify: no matching result was recorded");
23668
23808
  if (freshness.error) err(`cannot refresh current validation plan: ${freshness.error}`);
@@ -23676,15 +23816,20 @@ function evidenceCmd(repo, opts = {}) {
23676
23816
  info("errors:");
23677
23817
  for (const message of evidence.errors) err(message);
23678
23818
  }
23819
+ if (hooks.configuredAgents.length) {
23820
+ info(`session intercept: ${hooks.state} (configured: ${hooks.configuredAgents.join(",")})`);
23821
+ } else {
23822
+ info("session intercept: none (cooperative deliver only)");
23823
+ }
23679
23824
  const requiredActions = guidance.nextActions.filter((action) => action.priority === "required");
23680
23825
  printNextActions(requiredActions);
23681
- if (requiredActions.length) warn(`Harness readiness: INCOMPLETE (${requiredActions.length} required action(s) above)`);
23682
- else ok("Harness readiness: READY");
23826
+ if (!valid) warn(`Delivery stamp: NOT READY (${requiredActions.length} required action(s) above)`);
23827
+ else ok("Delivery stamp: READY");
23683
23828
  return valid ? 0 : 1;
23684
23829
  }
23685
23830
 
23686
23831
  // src/commands/hook-event.ts
23687
- var import_node_fs15 = require("node:fs");
23832
+ var import_node_fs16 = require("node:fs");
23688
23833
 
23689
23834
  // src/commands/run-checks.ts
23690
23835
  var import_node_child_process6 = require("node:child_process");
@@ -23699,11 +23844,12 @@ function isWaivableGap(gap2) {
23699
23844
  }
23700
23845
  function runOne(repo, cmd, timeoutMs) {
23701
23846
  const started = Date.now();
23847
+ const timeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.max(1, timeoutMs) : void 0;
23702
23848
  const r = (0, import_node_child_process6.spawnSync)(cmd, {
23703
23849
  cwd: repo,
23704
23850
  shell: true,
23705
23851
  encoding: "utf8",
23706
- timeout: Math.max(1, timeoutMs),
23852
+ ...timeout !== void 0 ? { timeout } : {},
23707
23853
  maxBuffer: 32 * 1024 * 1024
23708
23854
  });
23709
23855
  const out = `${r.stdout ?? ""}${r.stderr ?? ""}${r.error ? `
@@ -23810,9 +23956,9 @@ function fallbackChanges(base) {
23810
23956
  function runChecksCmd(repo, opts) {
23811
23957
  const errors = [];
23812
23958
  let session = null;
23813
- const implicitManualBase = !opts.session && opts.base === void 0;
23959
+ const implicitManualBase = !opts.session && opts.base === void 0 && !opts.allowEmptyAsNoChange;
23814
23960
  let base = opts.base ?? "HEAD";
23815
- let mode = "merge-base";
23961
+ let mode = opts.mode ?? "merge-base";
23816
23962
  if (opts.session) {
23817
23963
  try {
23818
23964
  session = readValidationSession(repo, opts.session);
@@ -23905,19 +24051,20 @@ function runChecksCmd(repo, opts) {
23905
24051
  const skipped = [];
23906
24052
  const checks = [];
23907
24053
  const capabilities = manifest?.capabilities ?? {};
23908
- const checkDeadline = Date.now() + CHECK_BUDGET_MS;
24054
+ const unlimitedBudget = opts.budgetMs === 0;
24055
+ const checkDeadline = unlimitedBudget ? Number.POSITIVE_INFINITY : Date.now() + (opts.budgetMs !== void 0 && opts.budgetMs > 0 ? opts.budgetMs : CHECK_BUDGET_MS);
23909
24056
  if (!errors.length) {
23910
24057
  for (const check of plan.checks) {
23911
24058
  const remainingMs = checkDeadline - Date.now();
23912
- if (remainingMs <= 0) {
23913
- const reason = "run-checks \u7684 7 \u5206\u949F\u603B\u68C0\u67E5\u9884\u7B97\u5DF2\u8017\u5C3D";
24059
+ if (!unlimitedBudget && remainingMs <= 0) {
24060
+ const reason = "run-checks \u7684\u68C0\u67E5\u603B\u9884\u7B97\u5DF2\u8017\u5C3D\uFF1B\u590D\u6742\u4EFB\u52A1\u8BF7\u7528 harness-kit deliver\uFF08\u65E0\u7D27\u603B\u9884\u7B97\uFF09";
23914
24061
  skipped.push({ id: check.id, reason });
23915
24062
  checks.push({ id: check.id, status: "not-run", exitCode: 1, durationMs: 0 });
23916
24063
  plan.gaps.push({
23917
24064
  kind: "selected-check-not-run",
23918
24065
  where: check.id,
23919
24066
  why: reason,
23920
- suggestion: "\u62C6\u5206\u5FEB\u901F\u81EA\u52A8\u95E8\u7981\uFF1B\u8D85\u957F\u9A8C\u8BC1\u653E\u5230 routing/manual GAP \u6216\u72EC\u7ACB CI",
24067
+ suggestion: "\u4F7F\u7528 harness-kit deliver \u505A\u4EFB\u52A1\u9A8C\u6536\uFF0C\u6216\u62C6\u5206\u5FEB\u901F\u81EA\u52A8\u95E8\u7981",
23921
24068
  severity: "blocking"
23922
24069
  });
23923
24070
  continue;
@@ -23936,7 +24083,7 @@ function runChecksCmd(repo, opts) {
23936
24083
  });
23937
24084
  continue;
23938
24085
  }
23939
- const result = runOne(repo, cap.run, remainingMs);
24086
+ const result = runOne(repo, cap.run, unlimitedBudget ? 0 : remainingMs);
23940
24087
  checks.push({ id: check.id, status: result.ok ? "passed" : "failed", exitCode: result.code, durationMs: result.durationMs });
23941
24088
  if (result.ok) passed.push(check.id);
23942
24089
  else failed.push({ id: check.id, cmd: cap.run, code: result.code, logTail: result.logTail, durationMs: result.durationMs });
@@ -23974,6 +24121,152 @@ function runChecksCmd(repo, opts) {
23974
24121
  return report.ok ? 0 : 1;
23975
24122
  }
23976
24123
 
24124
+ // src/commands/deliver.ts
24125
+ function captureStdout(fn) {
24126
+ const chunks = [];
24127
+ const original = process.stdout.write.bind(process.stdout);
24128
+ process.stdout.write = (chunk) => {
24129
+ chunks.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));
24130
+ return true;
24131
+ };
24132
+ let code = 1;
24133
+ try {
24134
+ code = fn();
24135
+ } catch (error) {
24136
+ chunks.push(`command threw: ${error.message}
24137
+ `);
24138
+ } finally {
24139
+ process.stdout.write = original;
24140
+ }
24141
+ return { code, output: chunks.join("") };
24142
+ }
24143
+ function parseRunReport(output) {
24144
+ try {
24145
+ return JSON.parse(output);
24146
+ } catch {
24147
+ return null;
24148
+ }
24149
+ }
24150
+ function nextActions(status, report) {
24151
+ if (status === "accepted" || status === "no-change") return [];
24152
+ const next = [];
24153
+ if (report) {
24154
+ for (const failure of report.failed.slice(0, 5)) {
24155
+ next.push(`fix failing check "${failure.id}": ${failure.cmd}`);
24156
+ }
24157
+ for (const gap2 of report.gaps.filter((g) => g.severity === "blocking").slice(0, 5)) {
24158
+ next.push(gap2.suggestion);
24159
+ }
24160
+ for (const skipped of report.skipped.slice(0, 3)) {
24161
+ next.push(`resolve skipped check ${skipped.id}: ${skipped.reason}`);
24162
+ }
24163
+ }
24164
+ next.push("re-run: harness-kit deliver --repo .");
24165
+ return next;
24166
+ }
24167
+ function reportHuman2(report) {
24168
+ info(`deliver (scope=${report.scope}, base ${report.base}) \u2014 ${report.changed.length} changed file(s)`);
24169
+ if (report.scope === "worktree" && report.status !== "no-change") {
24170
+ info(" using worktree diff vs HEAD (no task base); for committed task range run: harness-kit task start");
24171
+ }
24172
+ if (report.runChecks) {
24173
+ info(` run-checks: ${report.runChecks.status} (${report.runChecks.passed.length} passed, ${report.runChecks.failed.length} failed)`);
24174
+ for (const failure of report.runChecks.failed.slice(0, 5)) {
24175
+ err(`${failure.id}: FAILED (exit ${failure.code}) \u2014 ${failure.cmd}`);
24176
+ for (const line of failure.logTail.split("\n")) if (line) info(` ${line}`);
24177
+ }
24178
+ for (const gap2 of report.runChecks.gaps.filter((g) => g.severity === "blocking").slice(0, 8)) {
24179
+ err(`[${gap2.kind}] ${gap2.where ? `${gap2.where} \u2014 ` : ""}${gap2.why}`);
24180
+ info(` -> ${gap2.suggestion}`);
24181
+ }
24182
+ }
24183
+ if (report.verifyPassed) ok("verify: passed");
24184
+ else err("verify: failed");
24185
+ for (const message of report.errors) err(message);
24186
+ info("");
24187
+ if (report.status === "accepted") ok("deliver: ACCEPTED \u2014 task stamp is valid for this fingerprint");
24188
+ else if (report.status === "no-change") ok("deliver: NO-CHANGE \u2014 no pending worktree changes to accept");
24189
+ else err("deliver: NEEDS-WORK \u2014 fix failures and re-run harness-kit deliver");
24190
+ if (report.next.length) {
24191
+ info("\nNEXT");
24192
+ for (const step of report.next) info(` - ${step}`);
24193
+ }
24194
+ }
24195
+ function deliverCmd(repo, opts = {}) {
24196
+ const errors = [];
24197
+ let scope;
24198
+ try {
24199
+ scope = resolveChangeScope(repo, { base: opts.base });
24200
+ } catch (error) {
24201
+ err(`deliver cannot resolve change scope: ${error.message}`);
24202
+ return 1;
24203
+ }
24204
+ const run = captureStdout(
24205
+ () => runChecksCmd(repo, {
24206
+ base: scope.base,
24207
+ mode: "exact",
24208
+ budgetMs: 0,
24209
+ allowEmptyAsNoChange: true,
24210
+ profile: opts.profile,
24211
+ json: true
24212
+ })
24213
+ );
24214
+ const runReport = parseRunReport(run.output);
24215
+ if (!runReport) errors.push("run-checks did not return valid JSON evidence");
24216
+ const verify = captureStdout(
24217
+ () => verifyCmd(repo, {
24218
+ recordManualEvidence: true,
24219
+ budgetMs: Number(process.env.HARNESS_KIT_DELIVER_VERIFY_BUDGET_MS) || 60 * 60 * 1e3
24220
+ })
24221
+ );
24222
+ const verifyPassed = verify.code === 0;
24223
+ if (!verifyPassed) {
24224
+ const tail = verify.output.trim().split("\n").filter(Boolean).slice(-8);
24225
+ if (tail.length) errors.push(`verify failed: ${tail.join(" | ")}`);
24226
+ else errors.push("verify failed");
24227
+ }
24228
+ let fingerprintError = "";
24229
+ if (runReport?.fingerprint) {
24230
+ try {
24231
+ const current = collectChanges(repo, scope.base, { mode: "exact" });
24232
+ if (current.fingerprint !== runReport.fingerprint) {
24233
+ fingerprintError = "change fingerprint changed during delivery; re-run deliver on a stable tree";
24234
+ errors.push(fingerprintError);
24235
+ }
24236
+ } catch (error) {
24237
+ fingerprintError = `final fingerprint failed: ${error.message}`;
24238
+ errors.push(fingerprintError);
24239
+ }
24240
+ }
24241
+ const runOk = run.code === 0 && !!runReport?.ok;
24242
+ const stable = !fingerprintError;
24243
+ let status;
24244
+ if (runOk && verifyPassed && stable && runReport?.status === "no-change") status = "no-change";
24245
+ else if (runOk && verifyPassed && stable) status = "accepted";
24246
+ else status = "needs-work";
24247
+ const stamp = inspectDeliveryStamp(repo);
24248
+ const report = {
24249
+ schema: "ai-harness/deliver-report/v1",
24250
+ status,
24251
+ ok: status === "accepted" || status === "no-change",
24252
+ scope: scope.kind,
24253
+ base: scope.base,
24254
+ fingerprint: runReport?.fingerprint ?? scope.changes.fingerprint,
24255
+ changed: runReport?.changed ?? scope.changes.files,
24256
+ runChecks: runReport,
24257
+ verifyPassed,
24258
+ stamp,
24259
+ errors,
24260
+ next: nextActions(status, runReport)
24261
+ };
24262
+ if (opts.json) {
24263
+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");
24264
+ } else {
24265
+ reportHuman2(report);
24266
+ }
24267
+ return report.ok ? 0 : 1;
24268
+ }
24269
+
23977
24270
  // src/commands/hook-event.ts
23978
24271
  var MAX_HOOK_VERIFY_BUDGET_MS = 2 * 60 * 1e3;
23979
24272
  function hookVerifyBudgetMs() {
@@ -23981,8 +24274,12 @@ function hookVerifyBudgetMs() {
23981
24274
  if (!Number.isFinite(configured) || configured <= 0) return MAX_HOOK_VERIFY_BUDGET_MS;
23982
24275
  return Math.min(configured, MAX_HOOK_VERIFY_BUDGET_MS);
23983
24276
  }
24277
+ function stopMode() {
24278
+ const raw = (process.env.HARNESS_KIT_STOP_MODE ?? "thin").trim().toLowerCase();
24279
+ return raw === "execute" || raw === "thick" ? "execute" : "thin";
24280
+ }
23984
24281
  function readPayload() {
23985
- const raw = (0, import_node_fs15.readFileSync)(0, "utf8").trim();
24282
+ const raw = (0, import_node_fs16.readFileSync)(0, "utf8").trim();
23986
24283
  if (!raw) return {};
23987
24284
  const value = JSON.parse(raw);
23988
24285
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("hook stdin must be a JSON object");
@@ -23991,7 +24288,7 @@ function readPayload() {
23991
24288
  function sessionId(payload) {
23992
24289
  return payload.session_id ?? payload.conversation_id ?? payload.turn_id ?? null;
23993
24290
  }
23994
- function captureStdout(fn) {
24291
+ function captureStdout2(fn) {
23995
24292
  const chunks = [];
23996
24293
  const original = process.stdout.write.bind(process.stdout);
23997
24294
  process.stdout.write = (chunk) => {
@@ -24025,13 +24322,23 @@ function block(agent, event, reason) {
24025
24322
  process.stderr.write(reason.trimEnd() + "\n");
24026
24323
  return 2;
24027
24324
  }
24028
- function parseRunReport(output) {
24325
+ function parseRunReport2(output) {
24029
24326
  try {
24030
24327
  return JSON.parse(output);
24031
24328
  } catch {
24032
24329
  return null;
24033
24330
  }
24034
24331
  }
24332
+ function deliverBlockMessage(extra = "") {
24333
+ const lines = [
24334
+ "harness-kit: delivery is not verified; continue working before stopping.",
24335
+ "Run: harness-kit deliver --repo .",
24336
+ "Only status=accepted (or no-change with a clean tree) may finish.",
24337
+ "Fix failures from deliver, then finish again."
24338
+ ];
24339
+ if (extra.trim()) lines.splice(1, 0, extra.trim());
24340
+ return lines.join("\n");
24341
+ }
24035
24342
  function failureMessage(report, verifyOutput, token) {
24036
24343
  const lines = ["harness-kit: delivery is not verified; continue working before stopping."];
24037
24344
  if (!report) lines.push("run-checks did not return valid evidence.");
@@ -24055,80 +24362,74 @@ function failureMessage(report, verifyOutput, token) {
24055
24362
  const actionable = outputLines.filter((line) => /\bERR\b|timed out|budget exhausted|verify: FAILED/.test(line));
24056
24363
  lines.push(`- verify: ${(actionable.length ? actionable.slice(-8) : outputLines.slice(-8)).join(" | ")}`);
24057
24364
  }
24058
- lines.push("Fix the failures, then finish again; every Stop attempt is re-checked.");
24365
+ lines.push("Prefer: harness-kit deliver --repo . (then finish again)");
24059
24366
  lines.push(
24060
- `For a genuine non-goal, only an eligible coverage gap may be waived: harness-kit run-checks --repo . --session ${token} --waive <kind> --where <scope> --reason "<why>"`
24367
+ `For a genuine non-goal coverage gap only: harness-kit run-checks --repo . --session ${token} --waive <kind> --where <scope> --reason "<why>"`
24061
24368
  );
24062
24369
  return lines.join("\n");
24063
24370
  }
24064
- function hookEventCmd(repoInput, opts) {
24065
- let payload;
24066
- try {
24067
- payload = readPayload();
24068
- } catch (error) {
24069
- return block(opts.agent, opts.event, `harness-kit hook input invalid: ${error.message}`);
24070
- }
24071
- const id = sessionId(payload);
24072
- if (!id) return block(opts.agent, opts.event, "harness-kit hook input has no session/conversation id");
24073
- let repo;
24371
+ function thinStop(repo, agent) {
24372
+ let scope;
24074
24373
  try {
24075
- repo = gitRoot(repoInput);
24374
+ scope = resolveChangeScope(repo);
24076
24375
  } catch (error) {
24077
- return block(opts.agent, opts.event, `harness-kit cannot resolve repository root: ${error.message}`);
24078
- }
24079
- if (opts.event === "session-start") {
24080
- try {
24081
- const initial = collectChanges(repo, "HEAD", { mode: "exact" });
24082
- startValidationSession({
24083
- repo,
24084
- agent: opts.agent,
24085
- sessionId: id,
24086
- baseSha: initial.head,
24087
- initialFingerprint: initial.fingerprint,
24088
- initialDirty: initial.files,
24089
- hookConfigFingerprint: agentHookConfigurationFingerprint(repo, opts.agent) ?? void 0
24090
- });
24091
- return allow(opts.agent);
24092
- } catch (error) {
24093
- return block(opts.agent, opts.event, `harness-kit could not capture the session baseline: ${error.message}`);
24094
- }
24095
- }
24096
- if (opts.agent === "cursor" && ["aborted", "error"].includes(payload.status ?? "")) return allow(opts.agent);
24097
- const token = validationSessionToken(opts.agent, id);
24376
+ return block(agent, "stop", deliverBlockMessage(`cannot resolve changes: ${error.message}`));
24377
+ }
24378
+ if (scope.changes.files.length === 0) return allow(agent);
24379
+ if (stampCoversScope(repo, scope)) return allow(agent);
24380
+ return block(
24381
+ agent,
24382
+ "stop",
24383
+ deliverBlockMessage(
24384
+ `scope=${scope.kind} base=${scope.base} changed=${scope.changes.files.length} file(s); no matching accepted delivery stamp.`
24385
+ )
24386
+ );
24387
+ }
24388
+ function executeStop(repo, agent, id) {
24389
+ const token = validationSessionToken(agent, id);
24098
24390
  let session;
24099
24391
  try {
24100
24392
  session = readValidationSession(repo, token);
24101
24393
  } catch (error) {
24102
- return block(opts.agent, opts.event, `harness-kit validation session is unreadable: ${error.message}`);
24394
+ return block(agent, "stop", deliverBlockMessage(`validation session unreadable: ${error.message}`));
24103
24395
  }
24104
24396
  if (!session) {
24105
- return block(
24106
- opts.agent,
24107
- opts.event,
24108
- "harness-kit has no SessionStart baseline for this conversation. Start a new agent session after installing hooks; refusing to guess and miss committed changes."
24109
- );
24397
+ const delivered = captureStdout2(() => deliverCmd(repo, { json: true }));
24398
+ if (delivered.code === 0) return allow(agent);
24399
+ let detail = "";
24400
+ try {
24401
+ const body = JSON.parse(delivered.output);
24402
+ detail = `deliver status=${body.status ?? "needs-work"}; ${(body.errors ?? []).slice(0, 3).join("; ")}`;
24403
+ } catch {
24404
+ detail = delivered.output.trim().slice(0, 500);
24405
+ }
24406
+ return block(agent, "stop", deliverBlockMessage(detail));
24110
24407
  }
24111
- if (session.hookConfigFingerprint && agentHookConfigurationFingerprint(repo, opts.agent) !== session.hookConfigFingerprint) {
24408
+ if (session.hookConfigFingerprint && agentHookConfigurationFingerprint(repo, agent) !== session.hookConfigFingerprint) {
24409
+ const delivered = captureStdout2(() => deliverCmd(repo, { json: true }));
24410
+ if (delivered.code === 0) return allow(agent);
24112
24411
  return block(
24113
- opts.agent,
24114
- opts.event,
24115
- "harness-kit project hook configuration changed after SessionStart. Start a new agent session before delivery; refusing to trust evidence from another hook configuration."
24412
+ agent,
24413
+ "stop",
24414
+ deliverBlockMessage(
24415
+ "project hook configuration changed after SessionStart; lifecycle proof was discarded. Run deliver to re-accept the current change."
24416
+ )
24116
24417
  );
24117
24418
  }
24118
24419
  try {
24119
24420
  clearValidationEvidence(repo, session);
24120
24421
  } catch (error) {
24121
- return block(opts.agent, opts.event, `harness-kit could not start a fresh validation attempt: ${error.message}`);
24422
+ return block(agent, "stop", deliverBlockMessage(`could not start a fresh validation attempt: ${error.message}`));
24122
24423
  }
24123
- const run = captureStdout(() => runChecksCmd(repo, { session: token, json: true }));
24124
- const report = parseRunReport(run.output);
24125
- const verify = captureStdout(() => verifyCmd(repo, { budgetMs: hookVerifyBudgetMs(), recordManualEvidence: false }));
24424
+ const run = captureStdout2(() => runChecksCmd(repo, { session: token, json: true, budgetMs: 0 }));
24425
+ const report = parseRunReport2(run.output);
24426
+ const verify = captureStdout2(() => verifyCmd(repo, { budgetMs: hookVerifyBudgetMs(), recordManualEvidence: false }));
24126
24427
  let finalFingerprintError = "";
24127
24428
  if (report?.fingerprint) {
24128
24429
  try {
24129
24430
  const current = collectChanges(repo, session.baseSha ?? EMPTY_TREE_BASE, { mode: "exact" });
24130
24431
  if (current.fingerprint !== report.fingerprint)
24131
- finalFingerprintError = "change fingerprint changed during final verification; rerun both gates on the stable change";
24432
+ finalFingerprintError = "change fingerprint changed during final verification; rerun deliver on the stable change";
24132
24433
  } catch (error) {
24133
24434
  finalFingerprintError = `final fingerprint failed: ${error.message}`;
24134
24435
  }
@@ -24138,21 +24439,69 @@ function hookEventCmd(repoInput, opts) {
24138
24439
  try {
24139
24440
  evidencePersisted = markLatestVerifyResult(repo, token, verifyPassed, report?.fingerprint, report?.planFingerprint);
24140
24441
  } catch (error) {
24141
- return block(opts.agent, opts.event, `harness-kit could not persist the final verify result: ${error.message}`);
24442
+ return block(agent, "stop", deliverBlockMessage(`could not persist verify result: ${error.message}`));
24142
24443
  }
24143
- if (run.code === 0 && report?.ok && verifyPassed && evidencePersisted) return allow(opts.agent);
24444
+ if (run.code === 0 && report?.ok && verifyPassed && evidencePersisted) return allow(agent);
24144
24445
  const verifyDetails = [
24145
24446
  verify.code === 0 ? "" : verify.output.trim(),
24146
24447
  finalFingerprintError,
24147
24448
  evidencePersisted ? "" : "matching final evidence was not persisted; refusing to allow Stop"
24148
24449
  ].filter(Boolean).join("\n");
24149
- return block(opts.agent, opts.event, failureMessage(report, verifyDetails, token));
24450
+ return block(agent, "stop", failureMessage(report, verifyDetails, token));
24451
+ }
24452
+ function hookEventCmd(repoInput, opts) {
24453
+ let payload;
24454
+ try {
24455
+ payload = readPayload();
24456
+ } catch (error) {
24457
+ return block(opts.agent, opts.event, `harness-kit hook input invalid: ${error.message}`);
24458
+ }
24459
+ const id = sessionId(payload);
24460
+ if (!id) return block(opts.agent, opts.event, "harness-kit hook input has no session/conversation id");
24461
+ let repo;
24462
+ try {
24463
+ repo = gitRoot(repoInput);
24464
+ } catch (error) {
24465
+ return block(opts.agent, opts.event, `harness-kit cannot resolve repository root: ${error.message}`);
24466
+ }
24467
+ if (opts.event === "session-start") {
24468
+ try {
24469
+ const initial = collectChanges(repo, "HEAD", { mode: "exact" });
24470
+ startValidationSession({
24471
+ repo,
24472
+ agent: opts.agent,
24473
+ sessionId: id,
24474
+ baseSha: initial.head,
24475
+ initialFingerprint: initial.fingerprint,
24476
+ initialDirty: initial.files,
24477
+ hookConfigFingerprint: agentHookConfigurationFingerprint(repo, opts.agent) ?? void 0
24478
+ });
24479
+ if (initial.head) {
24480
+ try {
24481
+ startTaskRecord({
24482
+ repo,
24483
+ baseSha: initial.head,
24484
+ hostSessionId: id,
24485
+ agent: opts.agent,
24486
+ note: "auto from SessionStart"
24487
+ });
24488
+ } catch {
24489
+ }
24490
+ }
24491
+ return allow(opts.agent);
24492
+ } catch (error) {
24493
+ return block(opts.agent, opts.event, `harness-kit could not capture the session baseline: ${error.message}`);
24494
+ }
24495
+ }
24496
+ if (opts.agent === "cursor" && ["aborted", "error"].includes(payload.status ?? "")) return allow(opts.agent);
24497
+ if (stopMode() === "thin") return thinStop(repo, opts.agent);
24498
+ return executeStop(repo, opts.agent, id);
24150
24499
  }
24151
24500
 
24152
24501
  // src/commands/install-hooks.ts
24153
24502
  var import_node_child_process7 = require("node:child_process");
24154
- var import_node_fs16 = require("node:fs");
24155
- var import_node_path15 = require("node:path");
24503
+ var import_node_fs17 = require("node:fs");
24504
+ var import_node_path16 = require("node:path");
24156
24505
  var MARK = "harness-kit-managed-hook";
24157
24506
  function git2(repo, args) {
24158
24507
  const result = (0, import_node_child_process7.spawnSync)("git", args, { cwd: repo, encoding: "utf8" });
@@ -24194,9 +24543,9 @@ function inspectGitHookScope(repo) {
24194
24543
  }
24195
24544
  ];
24196
24545
  });
24197
- const hooksDir = (0, import_node_path15.resolve)(repo, hooks.stdout.trim());
24198
- const commonDir = (0, import_node_path15.resolve)(repo, common.stdout.trim());
24199
- const gitDir = (0, import_node_path15.resolve)(repo, current.stdout.trim());
24546
+ const hooksDir = (0, import_node_path16.resolve)(repo, hooks.stdout.trim());
24547
+ const commonDir = (0, import_node_path16.resolve)(repo, common.stdout.trim());
24548
+ const gitDir = (0, import_node_path16.resolve)(repo, current.stdout.trim());
24200
24549
  return {
24201
24550
  scope: {
24202
24551
  hooksDir,
@@ -24205,21 +24554,21 @@ function inspectGitHookScope(repo) {
24205
24554
  worktrees,
24206
24555
  hooksPathConfigs,
24207
24556
  hooksPathConfigRaw,
24208
- defaultHooksDirMatches: hooksDir === (0, import_node_path15.join)(commonDir, "hooks")
24557
+ defaultHooksDirMatches: hooksDir === (0, import_node_path16.join)(commonDir, "hooks")
24209
24558
  }
24210
24559
  };
24211
24560
  }
24212
24561
  function hookOwnership(path) {
24213
24562
  try {
24214
- if (!(0, import_node_fs16.lstatSync)(path).isFile()) return "foreign";
24215
- return (0, import_node_fs16.readFileSync)(path, "utf8").includes(MARK) ? "managed" : "foreign";
24563
+ if (!(0, import_node_fs17.lstatSync)(path).isFile()) return "foreign";
24564
+ return (0, import_node_fs17.readFileSync)(path, "utf8").includes(MARK) ? "managed" : "foreign";
24216
24565
  } catch (error) {
24217
24566
  return error.code === "ENOENT" ? "missing" : "foreign";
24218
24567
  }
24219
24568
  }
24220
24569
  function hooksPathReason(scope) {
24221
24570
  if (!scope.hooksPathConfigRaw.length) {
24222
- return scope.defaultHooksDirMatches ? null : `resolved hooks directory does not match ${(0, import_node_path15.join)(scope.commonDir, "hooks")}; core.hooksPath origin is ambiguous`;
24571
+ return scope.defaultHooksDirMatches ? null : `resolved hooks directory does not match ${(0, import_node_path16.join)(scope.commonDir, "hooks")}; core.hooksPath origin is ambiguous`;
24223
24572
  }
24224
24573
  if (scope.hooksPathConfigs.length !== 1 || scope.hooksPathConfigRaw.length !== 1) {
24225
24574
  return `core.hooksPath is ambiguous: ${scope.hooksPathConfigRaw.join("; ")}`;
@@ -24270,7 +24619,7 @@ function installGitHooks(repo, force, allowSharedGitHooks) {
24270
24619
  ["pre-commit", preCommit()],
24271
24620
  ["pre-push", prePush()]
24272
24621
  ];
24273
- const ownership = new Map(targets.map(([name]) => [name, hookOwnership((0, import_node_path15.join)(scope.hooksDir, name))]));
24622
+ const ownership = new Map(targets.map(([name]) => [name, hookOwnership((0, import_node_path16.join)(scope.hooksDir, name))]));
24274
24623
  const reasons = [];
24275
24624
  const configuredPathReason = hooksPathReason(scope);
24276
24625
  if (configuredPathReason) reasons.push(configuredPathReason);
@@ -24293,10 +24642,10 @@ function installGitHooks(repo, force, allowSharedGitHooks) {
24293
24642
  );
24294
24643
  }
24295
24644
  for (const [name, body] of targets) {
24296
- const p = (0, import_node_path15.join)(scope.hooksDir, name);
24645
+ const p = (0, import_node_path16.join)(scope.hooksDir, name);
24297
24646
  const wasManaged = ownership.get(name) === "managed";
24298
24647
  writeText(p, body);
24299
- (0, import_node_fs16.chmodSync)(p, 493);
24648
+ (0, import_node_fs17.chmodSync)(p, 493);
24300
24649
  ok(`${wasManaged ? force ? "refreshed" : "updated" : "installed"} ${name}`);
24301
24650
  }
24302
24651
  info(`
@@ -24409,10 +24758,10 @@ function recordContextReviewCmd(repo, opts) {
24409
24758
  }
24410
24759
 
24411
24760
  // src/commands/prepare-adoption.ts
24412
- var import_node_path16 = require("node:path");
24761
+ var import_node_path17 = require("node:path");
24413
24762
  function prepareAdoptionCmd(repo, opts) {
24414
24763
  if (!opts.output?.trim()) throw new Error("candidate output directory is required");
24415
- const output = (0, import_node_path16.resolve)(opts.output);
24764
+ const output = (0, import_node_path17.resolve)(opts.output);
24416
24765
  const candidate = prepareAdoptionCandidate(repo, output);
24417
24766
  const result = {
24418
24767
  ok: true,
@@ -24430,15 +24779,15 @@ function prepareAdoptionCmd(repo, opts) {
24430
24779
  }
24431
24780
 
24432
24781
  // src/commands/record-adoption-audit.ts
24433
- var import_node_path17 = require("node:path");
24782
+ var import_node_path18 = require("node:path");
24434
24783
  function recordAdoptionAuditCmd(repo, opts) {
24435
24784
  if (!opts.candidate?.trim()) throw new Error("candidate directory is required");
24436
24785
  if (!opts.report?.trim()) throw new Error("audit report path is required");
24437
- const recorded = recordAdoptionAudit(repo, (0, import_node_path17.resolve)(opts.candidate), {
24786
+ const recorded = recordAdoptionAudit(repo, (0, import_node_path18.resolve)(opts.candidate), {
24438
24787
  verdict: opts.verdict,
24439
24788
  reason: opts.reason,
24440
- reportPath: (0, import_node_path17.resolve)(opts.report),
24441
- receiptPath: opts.receipt ? (0, import_node_path17.resolve)(opts.receipt) : void 0
24789
+ reportPath: (0, import_node_path18.resolve)(opts.report),
24790
+ receiptPath: opts.receipt ? (0, import_node_path18.resolve)(opts.receipt) : void 0
24442
24791
  });
24443
24792
  const result = {
24444
24793
  ok: true,
@@ -24547,6 +24896,41 @@ function upgradeCmd(repo, options = {}) {
24547
24896
  return 0;
24548
24897
  }
24549
24898
 
24899
+ // src/commands/task.ts
24900
+ function taskStartCmd(repo, opts = {}) {
24901
+ try {
24902
+ const record = startTaskRecord({ repo, baseSha: opts.base, note: opts.note });
24903
+ if (opts.json) {
24904
+ process.stdout.write(JSON.stringify(record, null, 2) + "\n");
24905
+ } else {
24906
+ ok(`task started at base ${record.baseSha}`);
24907
+ if (record.note) info(`note: ${record.note}`);
24908
+ info("run harness-kit deliver when ready to accept this task's changes");
24909
+ }
24910
+ return 0;
24911
+ } catch (error) {
24912
+ err(`task start failed: ${error.message}`);
24913
+ return 1;
24914
+ }
24915
+ }
24916
+ function taskStatusCmd(repo, opts = {}) {
24917
+ const record = readTaskRecord(repo);
24918
+ if (opts.json) {
24919
+ process.stdout.write(JSON.stringify({ schema: "ai-harness/task-status/v1", found: !!record, task: record }, null, 2) + "\n");
24920
+ return record ? 0 : 1;
24921
+ }
24922
+ if (!record) {
24923
+ err("no active task record for this worktree");
24924
+ info("run: harness-kit task start --repo .");
24925
+ info("without a task base, deliver falls back to worktree diff vs HEAD");
24926
+ return 1;
24927
+ }
24928
+ ok(`active task base ${record.baseSha}`);
24929
+ info(`created: ${record.createdAt}`);
24930
+ if (record.note) info(`note: ${record.note}`);
24931
+ return 0;
24932
+ }
24933
+
24550
24934
  // src/cli.ts
24551
24935
  function guard(fn) {
24552
24936
  try {
@@ -24559,7 +24943,7 @@ function guard(fn) {
24559
24943
  }
24560
24944
  var program2 = new Command();
24561
24945
  program2.name("harness-kit").description("AI-friendly repo harness").version(package_default.version);
24562
- var repoOf = (o) => (0, import_node_path18.resolve)(o.repo ?? process.cwd());
24946
+ var repoOf = (o) => (0, import_node_path19.resolve)(o.repo ?? process.cwd());
24563
24947
  function agentList(value) {
24564
24948
  const agents = value.split(",").map((item) => item.trim()).filter(Boolean);
24565
24949
  const invalid = agents.filter((agent) => !ALL_AGENTS.includes(agent));
@@ -24593,6 +24977,17 @@ program2.command("record-adoption-audit").description("record a declared pass/fa
24593
24977
  program2.command("doctor").description("dev-time health check: completeness, drift, freshness, tech debt").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--details", "show every declared verification boundary and maintenance action", false).action((o) => guard(() => doctorCmd(repoOf(o), { details: o.details })));
24594
24978
  program2.command("verify").description("CI gate: run enforceable invariants + contracts + drift; nonzero on failure").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--json", "machine-readable output", false).option("--details", "show every declared verification boundary and maintenance action", false).action((o) => guard(() => verifyCmd(repoOf(o), { json: o.json, details: o.details })));
24595
24979
  program2.command("plan-checks").description("compute which declared checks THIS change should run (impact-driven, executes nothing)").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--base <ref>", "diff base (default: working tree + untracked vs HEAD)", "HEAD").option("--profile <checkset>", "use a validation.checksets entry instead of per-module checks").option("--json", "machine-readable output", false).action((o) => guard(() => planChecksCmd(repoOf(o), { base: o.base, json: o.json, profile: o.profile })));
24980
+ program2.command("task").description("manage the worktree task base used by deliver (optional; SessionStart also sets it)").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--json", "machine-readable output", false).action((o) => guard(() => taskStatusCmd(repoOf(o), { json: o.json })));
24981
+ program2.command("task-start").description("record task-start base SHA for this worktree so deliver covers later commits").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--base <ref>", "override base (default: current HEAD)").option("--note <text>", "optional task note").option("--json", "machine-readable output", false).action((o) => guard(() => taskStartCmd(repoOf(o), { base: o.base, note: o.note, json: o.json })));
24982
+ program2.command("deliver").description("accept this task change: resolve scope \u2192 run-checks + verify \u2192 stamp (preferred finish gate)").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--base <ref>", "explicit task base (overrides task record)").option("--profile <checkset>", "use a validation.checksets entry instead of per-module checks").option("--json", "machine-readable output", false).action(
24983
+ (o) => guard(
24984
+ () => deliverCmd(repoOf(o), {
24985
+ base: o.base,
24986
+ profile: o.profile,
24987
+ json: o.json
24988
+ })
24989
+ )
24990
+ );
24596
24991
  program2.command("run-checks").description("plan + run resolved checks; record evidence; nonzero on failure/unresolved blocking gap").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--base <ref>", "task-start ref; required for manual proof after task changes were committed").option("--profile <checkset>", "use a validation.checksets entry instead of per-module checks").option("--waive <kind>", "waive one eligible coverage gap for this exact change fingerprint").option("--where <scope>", "exact gap scope; required when a kind matches multiple gaps").option("--reason <text>", "reason recorded with --waive").option("--session <token>", "validation session token (normally supplied by an agent hook)").option("--json", "machine-readable output", false).action(
24597
24992
  (o) => guard(
24598
24993
  () => runChecksCmd(repoOf(o), {
@@ -24606,7 +25001,7 @@ program2.command("run-checks").description("plan + run resolved checks; record e
24606
25001
  })
24607
25002
  )
24608
25003
  );
24609
- program2.command("evidence").description("show the latest durable run-checks evidence for this worktree/session").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--session <token>", "specific validation session token").option("--json", "machine-readable output", false).action((o) => guard(() => evidenceCmd(repoOf(o), { session: o.session, json: o.json })));
25004
+ program2.command("evidence").description("show the latest durable delivery stamp / run-checks evidence for this worktree/session").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--session <token>", "specific validation session token").option("--json", "machine-readable output", false).action((o) => guard(() => evidenceCmd(repoOf(o), { session: o.session, json: o.json })));
24610
25005
  program2.command("record-context-review").description("record an Agent's completed review of one knowledge item or module against its bound sources").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--path <knowledge-path>", "exact knowledge.path from the manifest").option("--module <name>", "exact module name (mutually exclusive with --path)").requiredOption("--reason <text>", "what was reviewed and why the context remains correct").option("--session <token>", "Agent/session identifier to keep with the review evidence").option("--json", "machine-readable output", false).action(
24611
25006
  (o) => guard(
24612
25007
  () => recordContextReviewCmd(repoOf(o), {