@erzhe/harness-kit 0.5.0 → 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.
@@ -5003,11 +5003,11 @@ var require_picomatch = __commonJS({
5003
5003
  return { isMatch: false, output: "" };
5004
5004
  }
5005
5005
  const opts = options || {};
5006
- const format = opts.format || (posix ? utils.toPosixSlashes : null);
5006
+ const format2 = opts.format || (posix ? utils.toPosixSlashes : null);
5007
5007
  let match = input === glob;
5008
- let output = match && format ? format(input) : input;
5008
+ let output = match && format2 ? format2(input) : input;
5009
5009
  if (match === false) {
5010
- output = format ? format(input) : input;
5010
+ output = format2 ? format2(input) : input;
5011
5011
  match = output === glob;
5012
5012
  }
5013
5013
  if (match === false || opts.capture === true) {
@@ -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
 
@@ -7430,14 +7430,14 @@ var require_bool = __commonJS({
7430
7430
  var require_stringifyNumber = __commonJS({
7431
7431
  "node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyNumber.js"(exports2) {
7432
7432
  "use strict";
7433
- function stringifyNumber({ format, minFractionDigits, tag, value }) {
7433
+ function stringifyNumber({ format: format2, minFractionDigits, tag, value }) {
7434
7434
  if (typeof value === "bigint")
7435
7435
  return String(value);
7436
7436
  const num = typeof value === "number" ? value : Number(value);
7437
7437
  if (!isFinite(num))
7438
7438
  return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
7439
7439
  let n = Object.is(value, -0) ? "-0" : JSON.stringify(value);
7440
- if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) {
7440
+ if (!format2 && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) {
7441
7441
  let i = n.indexOf(".");
7442
7442
  if (i < 0) {
7443
7443
  i = n.length;
@@ -12298,7 +12298,7 @@ var require_public_api = __commonJS({
12298
12298
  return docs;
12299
12299
  return Object.assign([], { empty: true }, composer$1.streamInfo());
12300
12300
  }
12301
- function parseDocument(source, options = {}) {
12301
+ function parseDocument2(source, options = {}) {
12302
12302
  const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
12303
12303
  const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
12304
12304
  const composer$1 = new composer.Composer(options);
@@ -12324,7 +12324,7 @@ var require_public_api = __commonJS({
12324
12324
  } else if (options === void 0 && reviver && typeof reviver === "object") {
12325
12325
  options = reviver;
12326
12326
  }
12327
- const doc = parseDocument(src, options);
12327
+ const doc = parseDocument2(src, options);
12328
12328
  if (!doc)
12329
12329
  return null;
12330
12330
  doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning));
@@ -12360,7 +12360,7 @@ var require_public_api = __commonJS({
12360
12360
  }
12361
12361
  exports2.parse = parse;
12362
12362
  exports2.parseAllDocuments = parseAllDocuments;
12363
- exports2.parseDocument = parseDocument;
12363
+ exports2.parseDocument = parseDocument2;
12364
12364
  exports2.stringify = stringify;
12365
12365
  }
12366
12366
  });
@@ -13170,7 +13170,7 @@ var require_fill_range = __commonJS({
13170
13170
  let padded = zeros(startString) || zeros(endString) || zeros(stepString);
13171
13171
  let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
13172
13172
  let toNumber = padded === false && stringify(start, end, options) === false;
13173
- let format = options.transform || transform(toNumber);
13173
+ let format2 = options.transform || transform(toNumber);
13174
13174
  if (options.toRegex && step === 1) {
13175
13175
  return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
13176
13176
  }
@@ -13182,7 +13182,7 @@ var require_fill_range = __commonJS({
13182
13182
  if (options.toRegex === true && step > 1) {
13183
13183
  push(a);
13184
13184
  } else {
13185
- range.push(pad(format(a, index), maxLen, toNumber));
13185
+ range.push(pad(format2(a, index), maxLen, toNumber));
13186
13186
  }
13187
13187
  a = descending ? a - step : a + step;
13188
13188
  index++;
@@ -13196,7 +13196,7 @@ var require_fill_range = __commonJS({
13196
13196
  if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) {
13197
13197
  return invalidRange(start, end, options);
13198
13198
  }
13199
- let format = options.transform || ((val) => String.fromCharCode(val));
13199
+ let format2 = options.transform || ((val) => String.fromCharCode(val));
13200
13200
  let a = `${start}`.charCodeAt(0);
13201
13201
  let b = `${end}`.charCodeAt(0);
13202
13202
  let descending = a > b;
@@ -13208,7 +13208,7 @@ var require_fill_range = __commonJS({
13208
13208
  let range = [];
13209
13209
  let index = 0;
13210
13210
  while (descending ? a >= b : a <= b) {
13211
- range.push(format(a, index));
13211
+ range.push(format2(a, index));
13212
13212
  a = descending ? a - step : a + step;
13213
13213
  index++;
13214
13214
  }
@@ -15459,11 +15459,11 @@ var require_picomatch3 = __commonJS({
15459
15459
  return { isMatch: false, output: "" };
15460
15460
  }
15461
15461
  const opts = options || {};
15462
- const format = opts.format || (posix ? utils.toPosixSlashes : null);
15462
+ const format2 = opts.format || (posix ? utils.toPosixSlashes : null);
15463
15463
  let match = input === glob;
15464
- let output = match && format ? format(input) : input;
15464
+ let output = match && format2 ? format2(input) : input;
15465
15465
  if (match === false) {
15466
- output = format ? format(input) : input;
15466
+ output = format2 ? format2(input) : input;
15467
15467
  match = output === glob;
15468
15468
  }
15469
15469
  if (match === false || opts.capture === true) {
@@ -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.0",
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
  );
@@ -20352,6 +20356,449 @@ function assertManagedFileAdoption(_repo, inspections, adoptExisting) {
20352
20356
  );
20353
20357
  }
20354
20358
 
20359
+ // src/upgrade.ts
20360
+ var import_yaml2 = __toESM(require_dist(), 1);
20361
+
20362
+ // src/git.ts
20363
+ var import_node_child_process3 = require("node:child_process");
20364
+ var import_node_crypto5 = require("node:crypto");
20365
+ var import_node_fs6 = require("node:fs");
20366
+ var import_node_path6 = require("node:path");
20367
+ var GitDiffError = class extends Error {
20368
+ constructor(kind, message) {
20369
+ super(message);
20370
+ this.kind = kind;
20371
+ this.name = "GitDiffError";
20372
+ }
20373
+ kind;
20374
+ };
20375
+ var EMPTY_TREE_BASE = "(empty-tree)";
20376
+ function errorText(error) {
20377
+ const e = error;
20378
+ const stderr = Buffer.isBuffer(e.stderr) ? e.stderr.toString("utf8") : e.stderr;
20379
+ return String(stderr || e.message || error).trim();
20380
+ }
20381
+ function git(repo, args) {
20382
+ try {
20383
+ return (0, import_node_child_process3.execFileSync)("git", args, {
20384
+ cwd: repo,
20385
+ encoding: "utf8",
20386
+ stdio: ["ignore", "pipe", "pipe"],
20387
+ maxBuffer: 32 * 1024 * 1024
20388
+ });
20389
+ } catch (error) {
20390
+ throw new GitDiffError("diff-failed", `git ${args[0] ?? "command"} failed: ${errorText(error)}`);
20391
+ }
20392
+ }
20393
+ function tryCommit(repo, ref) {
20394
+ try {
20395
+ return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], {
20396
+ cwd: repo,
20397
+ encoding: "utf8",
20398
+ stdio: ["ignore", "pipe", "pipe"]
20399
+ }).trim();
20400
+ } catch {
20401
+ return null;
20402
+ }
20403
+ }
20404
+ function gitRoot(repo) {
20405
+ try {
20406
+ return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--show-toplevel"], {
20407
+ cwd: repo,
20408
+ encoding: "utf8",
20409
+ stdio: ["ignore", "pipe", "pipe"]
20410
+ }).trim();
20411
+ } catch (error) {
20412
+ throw new GitDiffError("not-a-repo", `not a git repo: ${errorText(error)}`);
20413
+ }
20414
+ }
20415
+ function gitAdminDir(repo) {
20416
+ try {
20417
+ return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--absolute-git-dir"], {
20418
+ cwd: repo,
20419
+ encoding: "utf8",
20420
+ stdio: ["ignore", "pipe", "pipe"]
20421
+ }).trim();
20422
+ } catch (error) {
20423
+ throw new GitDiffError("not-a-repo", `cannot resolve git metadata dir: ${errorText(error)}`);
20424
+ }
20425
+ }
20426
+ function parseNameStatus(raw, layer) {
20427
+ const fields = raw.split("\0");
20428
+ if (fields.at(-1) === "") fields.pop();
20429
+ const entries = [];
20430
+ for (let i = 0; i < fields.length; ) {
20431
+ const status = fields[i++] ?? "";
20432
+ const code = status[0] ?? "M";
20433
+ const first = fields[i++];
20434
+ if (first === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed name-status output");
20435
+ if (code === "R") {
20436
+ const second = fields[i++];
20437
+ if (second === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed rename output");
20438
+ entries.push({ path: first, status: "D", layer }, { path: second, status: "A", layer });
20439
+ } else if (code === "C") {
20440
+ const second = fields[i++];
20441
+ if (second === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed copy output");
20442
+ entries.push({ path: second, status: "A", layer });
20443
+ } else {
20444
+ entries.push({ path: first, status: code, layer });
20445
+ }
20446
+ }
20447
+ return entries;
20448
+ }
20449
+ function nulList(raw) {
20450
+ return raw.split("\0").filter(Boolean);
20451
+ }
20452
+ function canonicalPath(path) {
20453
+ try {
20454
+ return (0, import_node_fs6.realpathSync)(path);
20455
+ } catch {
20456
+ return (0, import_node_path6.resolve)(path);
20457
+ }
20458
+ }
20459
+ function targetPrefix(root, target) {
20460
+ const native = (0, import_node_path6.relative)(root, target);
20461
+ if (!native) return "";
20462
+ if ((0, import_node_path6.isAbsolute)(native) || native === ".." || native.startsWith(`..${import_node_path6.sep}`))
20463
+ throw new GitDiffError("not-a-repo", `target is outside its Git worktree: ${target}`);
20464
+ return native.split(import_node_path6.sep).join("/");
20465
+ }
20466
+ function scopeEntries(entries, prefix) {
20467
+ if (!prefix) return entries;
20468
+ const start = `${prefix}/`;
20469
+ return entries.filter((entry) => entry.path.startsWith(start)).map((entry) => ({ ...entry, path: entry.path.slice(start.length) }));
20470
+ }
20471
+ function digestPath(repo, rel) {
20472
+ const abs = (0, import_node_path6.join)(repo, rel);
20473
+ try {
20474
+ const stat = (0, import_node_fs6.lstatSync)(abs);
20475
+ if (stat.isSymbolicLink()) return `symlink:${(0, import_node_fs6.readlinkSync)(abs)}`;
20476
+ if (stat.isDirectory()) {
20477
+ try {
20478
+ const head = (0, import_node_child_process3.execFileSync)("git", ["-C", abs, "rev-parse", "--verify", "HEAD"], {
20479
+ encoding: "utf8",
20480
+ stdio: ["ignore", "pipe", "pipe"]
20481
+ }).trim();
20482
+ const nested = collectChanges(abs, "HEAD", { mode: "exact" });
20483
+ return `gitlink:${head}:${nested.fingerprint}`;
20484
+ } catch {
20485
+ return `directory:${stat.mode}`;
20486
+ }
20487
+ }
20488
+ if (!stat.isFile()) return `other:${stat.mode}`;
20489
+ const gitMode = stat.mode & 73 ? "100755" : "100644";
20490
+ return `file:${gitMode}:${(0, import_node_crypto5.createHash)("sha256").update((0, import_node_fs6.readFileSync)(abs)).digest("hex")}`;
20491
+ } catch {
20492
+ return "(missing)";
20493
+ }
20494
+ }
20495
+ function digestIndex(repo, rel) {
20496
+ try {
20497
+ const entry = (0, import_node_child_process3.execFileSync)("git", ["ls-files", "--stage", "-z", "--", rel], {
20498
+ cwd: repo,
20499
+ encoding: "utf8",
20500
+ stdio: ["ignore", "pipe", "pipe"]
20501
+ });
20502
+ return entry || "(missing-index)";
20503
+ } catch (error) {
20504
+ throw new GitDiffError("diff-failed", `cannot fingerprint Git index entry ${rel}: ${errorText(error)}`);
20505
+ }
20506
+ }
20507
+ function fingerprint(repo, resolvedBase, entries) {
20508
+ const hash = (0, import_node_crypto5.createHash)("sha256");
20509
+ hash.update("harness-kit/change-fingerprint/v1\0");
20510
+ hash.update(resolvedBase ?? EMPTY_TREE_BASE);
20511
+ for (const entry of entries) {
20512
+ hash.update("\0");
20513
+ hash.update(entry.layer);
20514
+ hash.update("\0");
20515
+ hash.update(entry.status);
20516
+ hash.update("\0");
20517
+ hash.update(entry.path);
20518
+ hash.update("\0");
20519
+ hash.update(entry.layer === "index" ? digestIndex(repo, entry.path) : digestPath(repo, entry.path));
20520
+ }
20521
+ return hash.digest("hex");
20522
+ }
20523
+ function collectChanges(repoInput, base = "HEAD", opts = {}) {
20524
+ const target = canonicalPath(repoInput);
20525
+ const root = canonicalPath(gitRoot(target));
20526
+ const prefix = targetPrefix(root, target);
20527
+ const head = tryCommit(root, "HEAD");
20528
+ let baseCommit;
20529
+ if (base === EMPTY_TREE_BASE) {
20530
+ baseCommit = null;
20531
+ } else {
20532
+ baseCommit = tryCommit(root, base);
20533
+ if (!baseCommit && base === "HEAD" && !head) baseCommit = null;
20534
+ else if (!baseCommit) throw new GitDiffError("invalid-base", `invalid base ref: ${base}`);
20535
+ }
20536
+ let resolvedBase = baseCommit;
20537
+ if ((opts.mode ?? "merge-base") === "merge-base" && baseCommit && head) {
20538
+ try {
20539
+ resolvedBase = git(root, ["merge-base", baseCommit, head]).trim();
20540
+ } catch (error) {
20541
+ throw new GitDiffError("invalid-base", `invalid base ref or no merge base: ${base} (${error.message})`);
20542
+ }
20543
+ }
20544
+ let entries;
20545
+ if (resolvedBase) {
20546
+ entries = parseNameStatus(git(root, ["diff", "--cached", "--name-status", "-z", resolvedBase, "--"]), "index");
20547
+ } else {
20548
+ entries = nulList(git(root, ["ls-files", "--cached", "-z"])).map((path) => ({ path, status: "A", layer: "index" }));
20549
+ }
20550
+ entries.push(...parseNameStatus(git(root, ["diff", "--name-status", "-z", "--"]), "worktree"));
20551
+ for (const path of nulList(git(root, ["ls-files", "--others", "--exclude-standard", "-z"]))) {
20552
+ entries.push({ path, status: "A", layer: "untracked" });
20553
+ }
20554
+ entries = scopeEntries(entries, prefix);
20555
+ entries = entries.sort((a, b) => a.path.localeCompare(b.path) || a.layer.localeCompare(b.layer) || a.status.localeCompare(b.status));
20556
+ const files = [...new Set(entries.map((entry) => entry.path))];
20557
+ return {
20558
+ requestedBase: base,
20559
+ resolvedBase,
20560
+ head,
20561
+ files,
20562
+ entries,
20563
+ fingerprint: fingerprint(target, resolvedBase, entries)
20564
+ };
20565
+ }
20566
+
20567
+ // src/upgrade.ts
20568
+ var UPGRADE_STATE_REL = ".agents/harness.lock.json";
20569
+ var UPGRADE_STATE_SCHEMA = "ai-harness/upgrade-state/v1";
20570
+ var UPGRADE_REPORT_SCHEMA = "ai-harness/upgrade-report/v1";
20571
+ var UPGRADE_MIGRATIONS = [
20572
+ {
20573
+ id: "upgrade-state-v1",
20574
+ migrate: () => {
20575
+ }
20576
+ }
20577
+ ];
20578
+ function parseSemver(value) {
20579
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(
20580
+ value
20581
+ );
20582
+ if (!match) return null;
20583
+ const prerelease = match[4]?.split(".") ?? [];
20584
+ const core = [Number(match[1]), Number(match[2]), Number(match[3])];
20585
+ if (core.some((part) => !Number.isSafeInteger(part))) return null;
20586
+ if (prerelease.some((part) => /^\d+$/.test(part) && part.length > 1 && part.startsWith("0"))) return null;
20587
+ return {
20588
+ major: core[0],
20589
+ minor: core[1],
20590
+ patch: core[2],
20591
+ prerelease
20592
+ };
20593
+ }
20594
+ function comparePrerelease(left, right) {
20595
+ if (!left.length || !right.length) return left.length === right.length ? 0 : left.length ? -1 : 1;
20596
+ const length = Math.max(left.length, right.length);
20597
+ for (let index = 0; index < length; index++) {
20598
+ const a = left[index];
20599
+ const b = right[index];
20600
+ if (a === void 0 || b === void 0) return a === b ? 0 : a === void 0 ? -1 : 1;
20601
+ if (a === b) continue;
20602
+ const aNumeric = /^\d+$/.test(a);
20603
+ const bNumeric = /^\d+$/.test(b);
20604
+ if (aNumeric && bNumeric) return a.length === b.length ? a < b ? -1 : 1 : a.length < b.length ? -1 : 1;
20605
+ if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
20606
+ return a < b ? -1 : 1;
20607
+ }
20608
+ return 0;
20609
+ }
20610
+ function compareSemver(left, right) {
20611
+ for (const key of ["major", "minor", "patch"]) {
20612
+ if (left[key] !== right[key]) return left[key] < right[key] ? -1 : 1;
20613
+ }
20614
+ return comparePrerelease(left.prerelease, right.prerelease);
20615
+ }
20616
+ function reportBase(options) {
20617
+ return {
20618
+ schema: UPGRADE_REPORT_SCHEMA,
20619
+ status: "blocked",
20620
+ package: options.packageName,
20621
+ fromVersion: null,
20622
+ toVersion: options.targetVersion,
20623
+ manifestSpec: null,
20624
+ pendingMigrations: [],
20625
+ appliedMigrations: [],
20626
+ changedFiles: [],
20627
+ dirtyFiles: [],
20628
+ hooksChanged: false,
20629
+ errors: [],
20630
+ notes: ["upgrade does not install, remove, or rewrite lifecycle hooks"]
20631
+ };
20632
+ }
20633
+ function fail(report, message) {
20634
+ report.status = "blocked";
20635
+ report.errors.push(message);
20636
+ return report;
20637
+ }
20638
+ function parseState(content, options, report) {
20639
+ let value;
20640
+ try {
20641
+ value = JSON.parse(content);
20642
+ } catch (error) {
20643
+ return fail(report, `${UPGRADE_STATE_REL} is not valid JSON: ${error.message}`);
20644
+ }
20645
+ if (!value || typeof value !== "object" || Array.isArray(value))
20646
+ return fail(report, `${UPGRADE_STATE_REL} root must be an object`);
20647
+ const candidate = value;
20648
+ if (candidate.schema !== UPGRADE_STATE_SCHEMA)
20649
+ return fail(report, `${UPGRADE_STATE_REL} has unsupported schema: ${String(candidate.schema)}`);
20650
+ if (candidate.package !== options.packageName)
20651
+ return fail(report, `${UPGRADE_STATE_REL} belongs to ${String(candidate.package)}, not ${options.packageName}`);
20652
+ if (typeof candidate.version !== "string" || !parseSemver(candidate.version))
20653
+ return fail(report, `${UPGRADE_STATE_REL} has invalid version: ${String(candidate.version)}`);
20654
+ if (typeof candidate.manifestSpec !== "string" || !candidate.manifestSpec)
20655
+ return fail(report, `${UPGRADE_STATE_REL} has invalid manifestSpec`);
20656
+ if (!Array.isArray(candidate.appliedMigrations) || candidate.appliedMigrations.some((id) => typeof id !== "string"))
20657
+ return fail(report, `${UPGRADE_STATE_REL} appliedMigrations must be a string array`);
20658
+ const unique = new Set(candidate.appliedMigrations);
20659
+ if (unique.size !== candidate.appliedMigrations.length)
20660
+ return fail(report, `${UPGRADE_STATE_REL} appliedMigrations contains duplicates`);
20661
+ const known = new Set(UPGRADE_MIGRATIONS.map((migration) => migration.id));
20662
+ const unknown = candidate.appliedMigrations.filter((id) => !known.has(id));
20663
+ if (unknown.length) return fail(report, `${UPGRADE_STATE_REL} contains unknown migrations: ${unknown.join(", ")}`);
20664
+ return candidate;
20665
+ }
20666
+ function sameInspection(left, right) {
20667
+ return left.relativePath === right.relativePath && left.absolutePath === right.absolutePath && left.kind === right.kind && left.currentContent === right.currentContent && left.linkTarget === right.linkTarget;
20668
+ }
20669
+ function renderState(state) {
20670
+ return `${JSON.stringify(state, null, 2)}
20671
+ `;
20672
+ }
20673
+ function asManifest(document, report) {
20674
+ if (document.errors.length)
20675
+ return fail(report, `${MANIFEST_REL} YAML is invalid: ${document.errors.map((error) => error.message).join("; ")}`);
20676
+ const value = document.toJS();
20677
+ if (!value || typeof value !== "object" || Array.isArray(value))
20678
+ return fail(report, `${MANIFEST_REL} root must be an object`);
20679
+ const manifest = value;
20680
+ const errors = validateManifest(manifest).filter((issue) => issue.level === "error");
20681
+ if (errors.length) return fail(report, `manifest invalid: ${errors.map((issue) => issue.msg).join("; ")}`);
20682
+ return manifest;
20683
+ }
20684
+ function internalUpgrade(repo, options) {
20685
+ const report = reportBase(options);
20686
+ const targetSemver = parseSemver(options.targetVersion);
20687
+ if (!targetSemver) return fail(report, `running harness-kit has an invalid version: ${options.targetVersion}`);
20688
+ const changes = collectChanges(repo, "HEAD", { mode: "exact" });
20689
+ report.dirtyFiles = changes.files;
20690
+ if (!options.check && report.dirtyFiles.length)
20691
+ return fail(report, `repository has uncommitted changes: ${report.dirtyFiles.join(", ")}`);
20692
+ const sourceInspections = inspectManagedFiles(repo, [
20693
+ [MANIFEST_REL, ""],
20694
+ [UPGRADE_STATE_REL, ""]
20695
+ ]);
20696
+ const manifestInspection = sourceInspections[0];
20697
+ const stateInspection = sourceInspections[1];
20698
+ if (manifestInspection.kind === "missing" || manifestInspection.currentContent === null)
20699
+ return fail(report, `${MANIFEST_REL} is missing; run harness-kit init first`);
20700
+ let state = null;
20701
+ if (stateInspection.kind !== "missing") {
20702
+ if (stateInspection.currentContent === null) return fail(report, `${UPGRADE_STATE_REL} is not a readable regular file`);
20703
+ const parsed = parseState(stateInspection.currentContent, options, report);
20704
+ if ("status" in parsed) return parsed;
20705
+ state = parsed;
20706
+ report.fromVersion = state.version;
20707
+ report.appliedMigrations = [...state.appliedMigrations];
20708
+ const currentSemver = parseSemver(state.version);
20709
+ if (compareSemver(currentSemver, targetSemver) > 0)
20710
+ return fail(report, `refusing downgrade from ${state.version} to ${options.targetVersion}`);
20711
+ }
20712
+ const document = (0, import_yaml2.parseDocument)(manifestInspection.currentContent);
20713
+ const sourceManifest = asManifest(document, report);
20714
+ if ("status" in sourceManifest) return sourceManifest;
20715
+ report.manifestSpec = sourceManifest.spec;
20716
+ const normalizedSource = document.toString();
20717
+ const applied = new Set(state?.appliedMigrations ?? []);
20718
+ const pending = UPGRADE_MIGRATIONS.filter((migration) => !applied.has(migration.id));
20719
+ report.pendingMigrations = pending.map((migration) => migration.id);
20720
+ for (const migration of pending) migration.migrate(document);
20721
+ const finalManifest = asManifest(document, report);
20722
+ if ("status" in finalManifest) return finalManifest;
20723
+ const migratedManifestContent = document.toString();
20724
+ const nextState = {
20725
+ schema: UPGRADE_STATE_SCHEMA,
20726
+ package: options.packageName,
20727
+ version: options.targetVersion,
20728
+ manifestSpec: finalManifest.spec,
20729
+ appliedMigrations: UPGRADE_MIGRATIONS.map((migration) => migration.id)
20730
+ };
20731
+ const manifestChanged = migratedManifestContent !== normalizedSource;
20732
+ const finalManifestContent = manifestChanged ? migratedManifestContent : manifestInspection.currentContent;
20733
+ const targets = [
20734
+ // Keep an unchanged manifest in the transaction preflight so generated
20735
+ // files can never be committed from bytes that changed after planning.
20736
+ [MANIFEST_REL, finalManifestContent],
20737
+ ...renderTargets(finalManifest),
20738
+ [UPGRADE_STATE_REL, renderState(nextState)]
20739
+ ];
20740
+ const preflight = inspectManagedFiles(repo, targets);
20741
+ const generatedPaths = new Set(renderTargets(finalManifest).map(([path]) => path));
20742
+ try {
20743
+ assertManagedFileAdoption(
20744
+ repo,
20745
+ preflight.filter((inspection) => generatedPaths.has(inspection.relativePath)),
20746
+ false
20747
+ );
20748
+ } catch (error) {
20749
+ return fail(report, error.message);
20750
+ }
20751
+ report.changedFiles = preflight.filter((inspection) => !inspection.satisfiesDesired).map((inspection) => inspection.relativePath);
20752
+ const stateMatchesManifest = state?.manifestSpec === finalManifest.spec;
20753
+ const stateMatchesVersion = state?.version === options.targetVersion;
20754
+ const stateMatchesMigrations = state?.appliedMigrations.join("\0") === nextState.appliedMigrations.join("\0");
20755
+ const needsUpgrade = report.changedFiles.length > 0 || !stateMatchesManifest || !stateMatchesVersion || !stateMatchesMigrations;
20756
+ if (options.check) {
20757
+ report.status = needsUpgrade ? "upgrade-available" : "current";
20758
+ return report;
20759
+ }
20760
+ if (!needsUpgrade) {
20761
+ report.status = "current";
20762
+ report.pendingMigrations = [];
20763
+ return report;
20764
+ }
20765
+ const expected = new Map(preflight.map((inspection) => [inspection.relativePath, inspection]));
20766
+ const result = writeManagedFiles(repo, targets, {
20767
+ authorize: (inspections) => {
20768
+ for (const inspection of inspections) {
20769
+ const prior = expected.get(inspection.relativePath);
20770
+ if (!prior || !sameInspection(prior, inspection))
20771
+ throw new Error(`upgrade target changed after inspection: ${inspection.relativePath}`);
20772
+ }
20773
+ assertManagedFileAdoption(
20774
+ repo,
20775
+ inspections.filter((inspection) => generatedPaths.has(inspection.relativePath)),
20776
+ false
20777
+ );
20778
+ }
20779
+ });
20780
+ report.status = "upgraded";
20781
+ report.changedFiles = result.written;
20782
+ report.appliedMigrations = nextState.appliedMigrations;
20783
+ return report;
20784
+ }
20785
+ function upgradeRepository(repo, options) {
20786
+ try {
20787
+ return internalUpgrade(repo, options);
20788
+ } catch (error) {
20789
+ return fail(reportBase(options), error.message);
20790
+ }
20791
+ }
20792
+ function initialUpgradeState(packageName, version, manifestSpec) {
20793
+ return renderState({
20794
+ schema: UPGRADE_STATE_SCHEMA,
20795
+ package: packageName,
20796
+ version,
20797
+ manifestSpec,
20798
+ appliedMigrations: UPGRADE_MIGRATIONS.map((migration) => migration.id)
20799
+ });
20800
+ }
20801
+
20355
20802
  // src/commands/init.ts
20356
20803
  function manifestTemplate(name) {
20357
20804
  return `spec: ai-harness/v0
@@ -20402,6 +20849,7 @@ playbooks:
20402
20849
  function initCmd(repo, name, force) {
20403
20850
  const targets = [
20404
20851
  [".agents/manifest.yaml", manifestTemplate(name)],
20852
+ [UPGRADE_STATE_REL, initialUpgradeState(package_default.name, package_default.version, "ai-harness/v0")],
20405
20853
  [
20406
20854
  ".agents/knowledge/domain.md",
20407
20855
  `# ${name} \u2014 domain
@@ -20592,45 +21040,58 @@ function unsafeHookIssue(issue) {
20592
21040
  function hookActions(hooks) {
20593
21041
  if (hooks.state === "active") return [];
20594
21042
  const configured = hooks.configuredAgents.join(",");
20595
- if (hooks.state === "configured" || hooks.configuredAgents.length > 0 && hooks.issues.every(evidenceOnlyIssue)) {
20596
- return [{
20597
- id: "prove-lifecycle-hooks",
20598
- priority: "required",
20599
- owner: "agent",
20600
- when: "before-harness-ready",
20601
- title: "Prove the lifecycle Hook in a fresh Agent session",
20602
- reason: `A complete Hook is configured for ${configured || "the current Agent"}, but no current SessionStart + Stop evidence proves that the host executed it.`,
20603
- commands: ["harness-kit evidence --repo . --json"],
20604
- completion: "A newly created Agent session finishes once and evidence reports hookActive: true."
20605
- }];
20606
- }
20607
21043
  const unsafe = hooks.issues.filter(unsafeHookIssue);
20608
21044
  if (unsafe.length) {
20609
21045
  return [{
20610
21046
  id: "review-lifecycle-hook-conflict",
20611
- priority: "required",
21047
+ priority: "recommended",
20612
21048
  owner: "human",
20613
- when: "before-harness-ready",
20614
- title: "Approve resolution of an existing Hook configuration conflict",
20615
- 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.",
20616
21052
  commands: [],
20617
- 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."
20618
21081
  }];
20619
21082
  }
20620
- const agents = configured || "<current-agent>";
20621
21083
  return [{
20622
- id: hooks.configuredAgents.length ? "repair-lifecycle-hooks" : "install-lifecycle-hooks",
20623
- priority: "required",
21084
+ id: "repair-lifecycle-hooks",
21085
+ priority: "recommended",
20624
21086
  owner: "agent",
20625
- when: "before-harness-ready",
20626
- title: hooks.configuredAgents.length ? "Repair the Agent lifecycle Hook" : "Install the Agent lifecycle Hook",
20627
- 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.",
20628
21090
  commands: [
20629
- `harness-kit install-hooks --repo . --stop --agents ${agents}`,
20630
- "harness-kit install-hooks --repo . --stop --agents codex --allow-user-dispatcher # linked Codex worktree only",
20631
- "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 ."
20632
21093
  ],
20633
- 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."
20634
21095
  }];
20635
21096
  }
20636
21097
  function evidenceActions(evidence) {
@@ -20640,14 +21101,13 @@ function evidenceActions(evidence) {
20640
21101
  priority: "required",
20641
21102
  owner: "agent",
20642
21103
  when: "before-finish",
20643
- title: "Create delivery evidence for this change",
20644
- 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.",
20645
21106
  commands: [
20646
- "harness-kit run-checks --repo . --base <task-start-sha>",
20647
- "harness-kit verify --repo .",
21107
+ "harness-kit deliver --repo .",
20648
21108
  "harness-kit evidence --repo . --json"
20649
21109
  ],
20650
- completion: "Evidence reports valid: true for the current code fingerprint."
21110
+ completion: "deliver reports status=accepted (or no-change) and evidence stamp is valid."
20651
21111
  }];
20652
21112
  }
20653
21113
  if (evidence.stale) {
@@ -20656,14 +21116,10 @@ function evidenceActions(evidence) {
20656
21116
  priority: "required",
20657
21117
  owner: "agent",
20658
21118
  when: "before-finish",
20659
- title: "Re-run validation for the current code",
20660
- reason: "The saved green result belongs to an older code fingerprint.",
20661
- commands: [
20662
- "harness-kit run-checks --repo . --base <task-start-sha>",
20663
- "harness-kit verify --repo .",
20664
- "harness-kit evidence --repo . --json"
20665
- ],
20666
- 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."
20667
21123
  }];
20668
21124
  }
20669
21125
  if (!evidence.runChecksValid) {
@@ -20672,10 +21128,10 @@ function evidenceActions(evidence) {
20672
21128
  priority: "required",
20673
21129
  owner: "agent",
20674
21130
  when: "before-finish",
20675
- title: "Complete the impact-driven checks",
21131
+ title: "Complete impact-driven delivery checks",
20676
21132
  reason: "The selected checks did not produce valid evidence for the current code.",
20677
- commands: ["harness-kit run-checks --repo . --base <task-start-sha>", "harness-kit evidence --repo . --json"],
20678
- 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."
20679
21135
  }];
20680
21136
  }
20681
21137
  if (!evidence.verifyPassed || !evidence.valid) {
@@ -20684,22 +21140,22 @@ function evidenceActions(evidence) {
20684
21140
  priority: "required",
20685
21141
  owner: "agent",
20686
21142
  when: "before-finish",
20687
- title: "Complete repository verification",
21143
+ title: "Complete delivery verification",
20688
21144
  reason: "Change checks passed, but matching verify evidence is missing or failed.",
20689
- commands: ["harness-kit verify --repo .", "harness-kit evidence --repo . --json"],
20690
- 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."
20691
21147
  }];
20692
21148
  }
20693
21149
  return [];
20694
21150
  }
20695
21151
  function buildHarnessGuidance(input) {
20696
21152
  const gapDetails = input.manifest ? declaredVerificationGaps(input.manifest) : [];
20697
- const nextActions = [
21153
+ const nextActions2 = [
20698
21154
  ...input.evidence ? evidenceActions(input.evidence) : [],
20699
21155
  ...input.hooks ? hookActions(input.hooks) : []
20700
21156
  ];
20701
21157
  const improvement = automationAction(gapDetails);
20702
- if (improvement) nextActions.push(improvement);
21158
+ if (improvement) nextActions2.push(improvement);
20703
21159
  return {
20704
21160
  gapDetails,
20705
21161
  gapSummary: {
@@ -20707,7 +21163,7 @@ function buildHarnessGuidance(input) {
20707
21163
  recommended: gapDetails.filter((item) => item.classification === "recommended").length,
20708
21164
  informational: gapDetails.filter((item) => item.classification === "informational").length
20709
21165
  },
20710
- nextActions
21166
+ nextActions: nextActions2
20711
21167
  };
20712
21168
  }
20713
21169
 
@@ -20720,213 +21176,6 @@ var import_node_child_process4 = require("node:child_process");
20720
21176
  var import_node_fs7 = require("node:fs");
20721
21177
  var import_node_os = require("node:os");
20722
21178
  var import_node_path7 = require("node:path");
20723
-
20724
- // src/git.ts
20725
- var import_node_child_process3 = require("node:child_process");
20726
- var import_node_crypto5 = require("node:crypto");
20727
- var import_node_fs6 = require("node:fs");
20728
- var import_node_path6 = require("node:path");
20729
- var GitDiffError = class extends Error {
20730
- constructor(kind, message) {
20731
- super(message);
20732
- this.kind = kind;
20733
- this.name = "GitDiffError";
20734
- }
20735
- kind;
20736
- };
20737
- var EMPTY_TREE_BASE = "(empty-tree)";
20738
- function errorText(error) {
20739
- const e = error;
20740
- const stderr = Buffer.isBuffer(e.stderr) ? e.stderr.toString("utf8") : e.stderr;
20741
- return String(stderr || e.message || error).trim();
20742
- }
20743
- function git(repo, args) {
20744
- try {
20745
- return (0, import_node_child_process3.execFileSync)("git", args, {
20746
- cwd: repo,
20747
- encoding: "utf8",
20748
- stdio: ["ignore", "pipe", "pipe"],
20749
- maxBuffer: 32 * 1024 * 1024
20750
- });
20751
- } catch (error) {
20752
- throw new GitDiffError("diff-failed", `git ${args[0] ?? "command"} failed: ${errorText(error)}`);
20753
- }
20754
- }
20755
- function tryCommit(repo, ref) {
20756
- try {
20757
- return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], {
20758
- cwd: repo,
20759
- encoding: "utf8",
20760
- stdio: ["ignore", "pipe", "pipe"]
20761
- }).trim();
20762
- } catch {
20763
- return null;
20764
- }
20765
- }
20766
- function gitRoot(repo) {
20767
- try {
20768
- return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--show-toplevel"], {
20769
- cwd: repo,
20770
- encoding: "utf8",
20771
- stdio: ["ignore", "pipe", "pipe"]
20772
- }).trim();
20773
- } catch (error) {
20774
- throw new GitDiffError("not-a-repo", `not a git repo: ${errorText(error)}`);
20775
- }
20776
- }
20777
- function gitAdminDir(repo) {
20778
- try {
20779
- return (0, import_node_child_process3.execFileSync)("git", ["rev-parse", "--absolute-git-dir"], {
20780
- cwd: repo,
20781
- encoding: "utf8",
20782
- stdio: ["ignore", "pipe", "pipe"]
20783
- }).trim();
20784
- } catch (error) {
20785
- throw new GitDiffError("not-a-repo", `cannot resolve git metadata dir: ${errorText(error)}`);
20786
- }
20787
- }
20788
- function parseNameStatus(raw, layer) {
20789
- const fields = raw.split("\0");
20790
- if (fields.at(-1) === "") fields.pop();
20791
- const entries = [];
20792
- for (let i = 0; i < fields.length; ) {
20793
- const status = fields[i++] ?? "";
20794
- const code = status[0] ?? "M";
20795
- const first = fields[i++];
20796
- if (first === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed name-status output");
20797
- if (code === "R") {
20798
- const second = fields[i++];
20799
- if (second === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed rename output");
20800
- entries.push({ path: first, status: "D", layer }, { path: second, status: "A", layer });
20801
- } else if (code === "C") {
20802
- const second = fields[i++];
20803
- if (second === void 0) throw new GitDiffError("diff-failed", "git diff returned malformed copy output");
20804
- entries.push({ path: second, status: "A", layer });
20805
- } else {
20806
- entries.push({ path: first, status: code, layer });
20807
- }
20808
- }
20809
- return entries;
20810
- }
20811
- function nulList(raw) {
20812
- return raw.split("\0").filter(Boolean);
20813
- }
20814
- function canonicalPath(path) {
20815
- try {
20816
- return (0, import_node_fs6.realpathSync)(path);
20817
- } catch {
20818
- return (0, import_node_path6.resolve)(path);
20819
- }
20820
- }
20821
- function targetPrefix(root, target) {
20822
- const native = (0, import_node_path6.relative)(root, target);
20823
- if (!native) return "";
20824
- if ((0, import_node_path6.isAbsolute)(native) || native === ".." || native.startsWith(`..${import_node_path6.sep}`))
20825
- throw new GitDiffError("not-a-repo", `target is outside its Git worktree: ${target}`);
20826
- return native.split(import_node_path6.sep).join("/");
20827
- }
20828
- function scopeEntries(entries, prefix) {
20829
- if (!prefix) return entries;
20830
- const start = `${prefix}/`;
20831
- return entries.filter((entry) => entry.path.startsWith(start)).map((entry) => ({ ...entry, path: entry.path.slice(start.length) }));
20832
- }
20833
- function digestPath(repo, rel) {
20834
- const abs = (0, import_node_path6.join)(repo, rel);
20835
- try {
20836
- const stat = (0, import_node_fs6.lstatSync)(abs);
20837
- if (stat.isSymbolicLink()) return `symlink:${(0, import_node_fs6.readlinkSync)(abs)}`;
20838
- if (stat.isDirectory()) {
20839
- try {
20840
- const head = (0, import_node_child_process3.execFileSync)("git", ["-C", abs, "rev-parse", "--verify", "HEAD"], {
20841
- encoding: "utf8",
20842
- stdio: ["ignore", "pipe", "pipe"]
20843
- }).trim();
20844
- const nested = collectChanges(abs, "HEAD", { mode: "exact" });
20845
- return `gitlink:${head}:${nested.fingerprint}`;
20846
- } catch {
20847
- return `directory:${stat.mode}`;
20848
- }
20849
- }
20850
- if (!stat.isFile()) return `other:${stat.mode}`;
20851
- const gitMode = stat.mode & 73 ? "100755" : "100644";
20852
- return `file:${gitMode}:${(0, import_node_crypto5.createHash)("sha256").update((0, import_node_fs6.readFileSync)(abs)).digest("hex")}`;
20853
- } catch {
20854
- return "(missing)";
20855
- }
20856
- }
20857
- function digestIndex(repo, rel) {
20858
- try {
20859
- const entry = (0, import_node_child_process3.execFileSync)("git", ["ls-files", "--stage", "-z", "--", rel], {
20860
- cwd: repo,
20861
- encoding: "utf8",
20862
- stdio: ["ignore", "pipe", "pipe"]
20863
- });
20864
- return entry || "(missing-index)";
20865
- } catch (error) {
20866
- throw new GitDiffError("diff-failed", `cannot fingerprint Git index entry ${rel}: ${errorText(error)}`);
20867
- }
20868
- }
20869
- function fingerprint(repo, resolvedBase, entries) {
20870
- const hash = (0, import_node_crypto5.createHash)("sha256");
20871
- hash.update("harness-kit/change-fingerprint/v1\0");
20872
- hash.update(resolvedBase ?? EMPTY_TREE_BASE);
20873
- for (const entry of entries) {
20874
- hash.update("\0");
20875
- hash.update(entry.layer);
20876
- hash.update("\0");
20877
- hash.update(entry.status);
20878
- hash.update("\0");
20879
- hash.update(entry.path);
20880
- hash.update("\0");
20881
- hash.update(entry.layer === "index" ? digestIndex(repo, entry.path) : digestPath(repo, entry.path));
20882
- }
20883
- return hash.digest("hex");
20884
- }
20885
- function collectChanges(repoInput, base = "HEAD", opts = {}) {
20886
- const target = canonicalPath(repoInput);
20887
- const root = canonicalPath(gitRoot(target));
20888
- const prefix = targetPrefix(root, target);
20889
- const head = tryCommit(root, "HEAD");
20890
- let baseCommit;
20891
- if (base === EMPTY_TREE_BASE) {
20892
- baseCommit = null;
20893
- } else {
20894
- baseCommit = tryCommit(root, base);
20895
- if (!baseCommit && base === "HEAD" && !head) baseCommit = null;
20896
- else if (!baseCommit) throw new GitDiffError("invalid-base", `invalid base ref: ${base}`);
20897
- }
20898
- let resolvedBase = baseCommit;
20899
- if ((opts.mode ?? "merge-base") === "merge-base" && baseCommit && head) {
20900
- try {
20901
- resolvedBase = git(root, ["merge-base", baseCommit, head]).trim();
20902
- } catch (error) {
20903
- throw new GitDiffError("invalid-base", `invalid base ref or no merge base: ${base} (${error.message})`);
20904
- }
20905
- }
20906
- let entries;
20907
- if (resolvedBase) {
20908
- entries = parseNameStatus(git(root, ["diff", "--cached", "--name-status", "-z", resolvedBase, "--"]), "index");
20909
- } else {
20910
- entries = nulList(git(root, ["ls-files", "--cached", "-z"])).map((path) => ({ path, status: "A", layer: "index" }));
20911
- }
20912
- entries.push(...parseNameStatus(git(root, ["diff", "--name-status", "-z", "--"]), "worktree"));
20913
- for (const path of nulList(git(root, ["ls-files", "--others", "--exclude-standard", "-z"]))) {
20914
- entries.push({ path, status: "A", layer: "untracked" });
20915
- }
20916
- entries = scopeEntries(entries, prefix);
20917
- entries = entries.sort((a, b) => a.path.localeCompare(b.path) || a.layer.localeCompare(b.layer) || a.status.localeCompare(b.status));
20918
- const files = [...new Set(entries.map((entry) => entry.path))];
20919
- return {
20920
- requestedBase: base,
20921
- resolvedBase,
20922
- head,
20923
- files,
20924
- entries,
20925
- fingerprint: fingerprint(target, resolvedBase, entries)
20926
- };
20927
- }
20928
-
20929
- // src/codex-linked-hooks.ts
20930
21179
  var CODEX_LINKED_PROTOCOL = "ai-harness/codex-linked-dispatch/v1";
20931
21180
  var DISPATCH_ID = "codex-linked-dispatch-v1";
20932
21181
  var DISPATCHER_REL = `harness-kit/${DISPATCH_ID}.cjs`;
@@ -22838,9 +23087,9 @@ function doctorCmd(repo, opts = {}) {
22838
23087
  const hooks = inspectAgentHookStatus(repo);
22839
23088
  const configuredAgents = hooks.configuredAgents.length ? hooks.configuredAgents.join(", ") : "none";
22840
23089
  if (hooks.state === "active") {
22841
- 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)`);
22842
23091
  } else if (hooks.state === "configured") {
22843
- 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`);
22844
23093
  } else {
22845
23094
  warn(`DEGRADED \u2014 configured: ${configuredAgents}; ${hooks.issues.join("; ")}`);
22846
23095
  }
@@ -23169,9 +23418,9 @@ verify: FAILED (${manifestErrors.length} manifest problem(s))`);
23169
23418
  emit("info", "\n5) Agent lifecycle hooks");
23170
23419
  const configuredAgents = hooks.configuredAgents.length ? hooks.configuredAgents.join(", ") : "none";
23171
23420
  if (hooks.state === "active")
23172
- 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)`);
23173
23422
  else if (hooks.state === "configured")
23174
- 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`);
23175
23424
  else emit("warn", `DEGRADED \u2014 configured: ${configuredAgents}; ${hooks.issues.join("; ")}`);
23176
23425
  emit("info", "\n6) Declared verification boundaries");
23177
23426
  if (!guidance.gapSummary.total) emit("ok", "no declared verification boundaries");
@@ -23315,8 +23564,9 @@ var META = `<!-- harness-kit check-loop -->
23315
23564
  You are an AI agent implementing a requirement or fixing a bug in the CURRENT repo.
23316
23565
  Follow the loop below. Run every harness-kit command through
23317
23566
  \`npx -y @erzhe/harness-kit@latest <cmd>\` unless a local build is available.
23318
- The lifecycle hook records the SessionStart base, then runs \`run-checks + verify\` whenever you try to finish.
23319
- 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.
23320
23570
 
23321
23571
  ---
23322
23572
 
@@ -23325,6 +23575,131 @@ function checkLoopCmd() {
23325
23575
  return printSkill(SKILL_REL, META);
23326
23576
  }
23327
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
+
23328
23703
  // src/commands/evidence.ts
23329
23704
  function safeHookStatus(repo) {
23330
23705
  try {
@@ -23393,6 +23768,7 @@ function evidenceCmd(repo, opts = {}) {
23393
23768
  const valid = runChecksValid && evidence.verifyPassed === true;
23394
23769
  const hookConfigurationCurrent = session.agent !== "manual" && !!session.hookConfigFingerprint && agentHookConfigurationFingerprint(repo, session.agent) === session.hookConfigFingerprint;
23395
23770
  const hookActive = valid && hookConfigurationCurrent;
23771
+ const stamp = inspectDeliveryStamp(repo);
23396
23772
  const guidance = buildHarnessGuidance({
23397
23773
  hooks,
23398
23774
  evidence: { found: true, stale, runChecksValid, verifyPassed: evidence.verifyPassed, valid }
@@ -23401,6 +23777,7 @@ function evidenceCmd(repo, opts = {}) {
23401
23777
  ...body,
23402
23778
  runChecksValid,
23403
23779
  valid,
23780
+ stamp,
23404
23781
  hookActive,
23405
23782
  hookConfigurationCurrent,
23406
23783
  stale,
@@ -23416,16 +23793,16 @@ function evidenceCmd(repo, opts = {}) {
23416
23793
  process.stdout.write(JSON.stringify(result, null, 2) + "\n");
23417
23794
  return valid ? 0 : 1;
23418
23795
  }
23419
- if (valid) ok(evidence.status);
23420
- else if (stale) err("stale evidence \u2014 the change no longer matches this record");
23421
- 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");
23422
23799
  else err(evidence.status);
23423
23800
  info(`session: ${session.token}`);
23424
23801
  info(`agent: ${session.agent}`);
23425
- 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)");
23426
23803
  info(`base: ${evidence.requestedBase} -> ${evidence.resolvedBase ?? "empty tree"}`);
23427
23804
  info(`fingerprint: ${evidence.fingerprint}`);
23428
- 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(", ")}`);
23429
23806
  if (evidence.verifyPassed !== void 0) info(`verify: ${evidence.verifyPassed ? "passed" : "failed"}`);
23430
23807
  else err("verify: no matching result was recorded");
23431
23808
  if (freshness.error) err(`cannot refresh current validation plan: ${freshness.error}`);
@@ -23439,15 +23816,20 @@ function evidenceCmd(repo, opts = {}) {
23439
23816
  info("errors:");
23440
23817
  for (const message of evidence.errors) err(message);
23441
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
+ }
23442
23824
  const requiredActions = guidance.nextActions.filter((action) => action.priority === "required");
23443
23825
  printNextActions(requiredActions);
23444
- if (requiredActions.length) warn(`Harness readiness: INCOMPLETE (${requiredActions.length} required action(s) above)`);
23445
- 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");
23446
23828
  return valid ? 0 : 1;
23447
23829
  }
23448
23830
 
23449
23831
  // src/commands/hook-event.ts
23450
- var import_node_fs15 = require("node:fs");
23832
+ var import_node_fs16 = require("node:fs");
23451
23833
 
23452
23834
  // src/commands/run-checks.ts
23453
23835
  var import_node_child_process6 = require("node:child_process");
@@ -23462,11 +23844,12 @@ function isWaivableGap(gap2) {
23462
23844
  }
23463
23845
  function runOne(repo, cmd, timeoutMs) {
23464
23846
  const started = Date.now();
23847
+ const timeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.max(1, timeoutMs) : void 0;
23465
23848
  const r = (0, import_node_child_process6.spawnSync)(cmd, {
23466
23849
  cwd: repo,
23467
23850
  shell: true,
23468
23851
  encoding: "utf8",
23469
- timeout: Math.max(1, timeoutMs),
23852
+ ...timeout !== void 0 ? { timeout } : {},
23470
23853
  maxBuffer: 32 * 1024 * 1024
23471
23854
  });
23472
23855
  const out = `${r.stdout ?? ""}${r.stderr ?? ""}${r.error ? `
@@ -23573,9 +23956,9 @@ function fallbackChanges(base) {
23573
23956
  function runChecksCmd(repo, opts) {
23574
23957
  const errors = [];
23575
23958
  let session = null;
23576
- const implicitManualBase = !opts.session && opts.base === void 0;
23959
+ const implicitManualBase = !opts.session && opts.base === void 0 && !opts.allowEmptyAsNoChange;
23577
23960
  let base = opts.base ?? "HEAD";
23578
- let mode = "merge-base";
23961
+ let mode = opts.mode ?? "merge-base";
23579
23962
  if (opts.session) {
23580
23963
  try {
23581
23964
  session = readValidationSession(repo, opts.session);
@@ -23668,19 +24051,20 @@ function runChecksCmd(repo, opts) {
23668
24051
  const skipped = [];
23669
24052
  const checks = [];
23670
24053
  const capabilities = manifest?.capabilities ?? {};
23671
- 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);
23672
24056
  if (!errors.length) {
23673
24057
  for (const check of plan.checks) {
23674
24058
  const remainingMs = checkDeadline - Date.now();
23675
- if (remainingMs <= 0) {
23676
- 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";
23677
24061
  skipped.push({ id: check.id, reason });
23678
24062
  checks.push({ id: check.id, status: "not-run", exitCode: 1, durationMs: 0 });
23679
24063
  plan.gaps.push({
23680
24064
  kind: "selected-check-not-run",
23681
24065
  where: check.id,
23682
24066
  why: reason,
23683
- 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",
23684
24068
  severity: "blocking"
23685
24069
  });
23686
24070
  continue;
@@ -23699,7 +24083,7 @@ function runChecksCmd(repo, opts) {
23699
24083
  });
23700
24084
  continue;
23701
24085
  }
23702
- const result = runOne(repo, cap.run, remainingMs);
24086
+ const result = runOne(repo, cap.run, unlimitedBudget ? 0 : remainingMs);
23703
24087
  checks.push({ id: check.id, status: result.ok ? "passed" : "failed", exitCode: result.code, durationMs: result.durationMs });
23704
24088
  if (result.ok) passed.push(check.id);
23705
24089
  else failed.push({ id: check.id, cmd: cap.run, code: result.code, logTail: result.logTail, durationMs: result.durationMs });
@@ -23737,6 +24121,152 @@ function runChecksCmd(repo, opts) {
23737
24121
  return report.ok ? 0 : 1;
23738
24122
  }
23739
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
+
23740
24270
  // src/commands/hook-event.ts
23741
24271
  var MAX_HOOK_VERIFY_BUDGET_MS = 2 * 60 * 1e3;
23742
24272
  function hookVerifyBudgetMs() {
@@ -23744,8 +24274,12 @@ function hookVerifyBudgetMs() {
23744
24274
  if (!Number.isFinite(configured) || configured <= 0) return MAX_HOOK_VERIFY_BUDGET_MS;
23745
24275
  return Math.min(configured, MAX_HOOK_VERIFY_BUDGET_MS);
23746
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
+ }
23747
24281
  function readPayload() {
23748
- const raw = (0, import_node_fs15.readFileSync)(0, "utf8").trim();
24282
+ const raw = (0, import_node_fs16.readFileSync)(0, "utf8").trim();
23749
24283
  if (!raw) return {};
23750
24284
  const value = JSON.parse(raw);
23751
24285
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("hook stdin must be a JSON object");
@@ -23754,7 +24288,7 @@ function readPayload() {
23754
24288
  function sessionId(payload) {
23755
24289
  return payload.session_id ?? payload.conversation_id ?? payload.turn_id ?? null;
23756
24290
  }
23757
- function captureStdout(fn) {
24291
+ function captureStdout2(fn) {
23758
24292
  const chunks = [];
23759
24293
  const original = process.stdout.write.bind(process.stdout);
23760
24294
  process.stdout.write = (chunk) => {
@@ -23788,13 +24322,23 @@ function block(agent, event, reason) {
23788
24322
  process.stderr.write(reason.trimEnd() + "\n");
23789
24323
  return 2;
23790
24324
  }
23791
- function parseRunReport(output) {
24325
+ function parseRunReport2(output) {
23792
24326
  try {
23793
24327
  return JSON.parse(output);
23794
24328
  } catch {
23795
24329
  return null;
23796
24330
  }
23797
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
+ }
23798
24342
  function failureMessage(report, verifyOutput, token) {
23799
24343
  const lines = ["harness-kit: delivery is not verified; continue working before stopping."];
23800
24344
  if (!report) lines.push("run-checks did not return valid evidence.");
@@ -23818,80 +24362,74 @@ function failureMessage(report, verifyOutput, token) {
23818
24362
  const actionable = outputLines.filter((line) => /\bERR\b|timed out|budget exhausted|verify: FAILED/.test(line));
23819
24363
  lines.push(`- verify: ${(actionable.length ? actionable.slice(-8) : outputLines.slice(-8)).join(" | ")}`);
23820
24364
  }
23821
- 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)");
23822
24366
  lines.push(
23823
- `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>"`
23824
24368
  );
23825
24369
  return lines.join("\n");
23826
24370
  }
23827
- function hookEventCmd(repoInput, opts) {
23828
- let payload;
24371
+ function thinStop(repo, agent) {
24372
+ let scope;
23829
24373
  try {
23830
- payload = readPayload();
24374
+ scope = resolveChangeScope(repo);
23831
24375
  } catch (error) {
23832
- return block(opts.agent, opts.event, `harness-kit hook input invalid: ${error.message}`);
23833
- }
23834
- const id = sessionId(payload);
23835
- if (!id) return block(opts.agent, opts.event, "harness-kit hook input has no session/conversation id");
23836
- let repo;
23837
- try {
23838
- repo = gitRoot(repoInput);
23839
- } catch (error) {
23840
- return block(opts.agent, opts.event, `harness-kit cannot resolve repository root: ${error.message}`);
23841
- }
23842
- if (opts.event === "session-start") {
23843
- try {
23844
- const initial = collectChanges(repo, "HEAD", { mode: "exact" });
23845
- startValidationSession({
23846
- repo,
23847
- agent: opts.agent,
23848
- sessionId: id,
23849
- baseSha: initial.head,
23850
- initialFingerprint: initial.fingerprint,
23851
- initialDirty: initial.files,
23852
- hookConfigFingerprint: agentHookConfigurationFingerprint(repo, opts.agent) ?? void 0
23853
- });
23854
- return allow(opts.agent);
23855
- } catch (error) {
23856
- return block(opts.agent, opts.event, `harness-kit could not capture the session baseline: ${error.message}`);
23857
- }
23858
- }
23859
- if (opts.agent === "cursor" && ["aborted", "error"].includes(payload.status ?? "")) return allow(opts.agent);
23860
- 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);
23861
24390
  let session;
23862
24391
  try {
23863
24392
  session = readValidationSession(repo, token);
23864
24393
  } catch (error) {
23865
- 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}`));
23866
24395
  }
23867
24396
  if (!session) {
23868
- return block(
23869
- opts.agent,
23870
- opts.event,
23871
- "harness-kit has no SessionStart baseline for this conversation. Start a new agent session after installing hooks; refusing to guess and miss committed changes."
23872
- );
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));
23873
24407
  }
23874
- 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);
23875
24411
  return block(
23876
- opts.agent,
23877
- opts.event,
23878
- "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
+ )
23879
24417
  );
23880
24418
  }
23881
24419
  try {
23882
24420
  clearValidationEvidence(repo, session);
23883
24421
  } catch (error) {
23884
- 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}`));
23885
24423
  }
23886
- const run = captureStdout(() => runChecksCmd(repo, { session: token, json: true }));
23887
- const report = parseRunReport(run.output);
23888
- 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 }));
23889
24427
  let finalFingerprintError = "";
23890
24428
  if (report?.fingerprint) {
23891
24429
  try {
23892
24430
  const current = collectChanges(repo, session.baseSha ?? EMPTY_TREE_BASE, { mode: "exact" });
23893
24431
  if (current.fingerprint !== report.fingerprint)
23894
- 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";
23895
24433
  } catch (error) {
23896
24434
  finalFingerprintError = `final fingerprint failed: ${error.message}`;
23897
24435
  }
@@ -23901,21 +24439,69 @@ function hookEventCmd(repoInput, opts) {
23901
24439
  try {
23902
24440
  evidencePersisted = markLatestVerifyResult(repo, token, verifyPassed, report?.fingerprint, report?.planFingerprint);
23903
24441
  } catch (error) {
23904
- 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}`));
23905
24443
  }
23906
- if (run.code === 0 && report?.ok && verifyPassed && evidencePersisted) return allow(opts.agent);
24444
+ if (run.code === 0 && report?.ok && verifyPassed && evidencePersisted) return allow(agent);
23907
24445
  const verifyDetails = [
23908
24446
  verify.code === 0 ? "" : verify.output.trim(),
23909
24447
  finalFingerprintError,
23910
24448
  evidencePersisted ? "" : "matching final evidence was not persisted; refusing to allow Stop"
23911
24449
  ].filter(Boolean).join("\n");
23912
- 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);
23913
24499
  }
23914
24500
 
23915
24501
  // src/commands/install-hooks.ts
23916
24502
  var import_node_child_process7 = require("node:child_process");
23917
- var import_node_fs16 = require("node:fs");
23918
- var import_node_path15 = require("node:path");
24503
+ var import_node_fs17 = require("node:fs");
24504
+ var import_node_path16 = require("node:path");
23919
24505
  var MARK = "harness-kit-managed-hook";
23920
24506
  function git2(repo, args) {
23921
24507
  const result = (0, import_node_child_process7.spawnSync)("git", args, { cwd: repo, encoding: "utf8" });
@@ -23957,9 +24543,9 @@ function inspectGitHookScope(repo) {
23957
24543
  }
23958
24544
  ];
23959
24545
  });
23960
- const hooksDir = (0, import_node_path15.resolve)(repo, hooks.stdout.trim());
23961
- const commonDir = (0, import_node_path15.resolve)(repo, common.stdout.trim());
23962
- 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());
23963
24549
  return {
23964
24550
  scope: {
23965
24551
  hooksDir,
@@ -23968,21 +24554,21 @@ function inspectGitHookScope(repo) {
23968
24554
  worktrees,
23969
24555
  hooksPathConfigs,
23970
24556
  hooksPathConfigRaw,
23971
- defaultHooksDirMatches: hooksDir === (0, import_node_path15.join)(commonDir, "hooks")
24557
+ defaultHooksDirMatches: hooksDir === (0, import_node_path16.join)(commonDir, "hooks")
23972
24558
  }
23973
24559
  };
23974
24560
  }
23975
24561
  function hookOwnership(path) {
23976
24562
  try {
23977
- if (!(0, import_node_fs16.lstatSync)(path).isFile()) return "foreign";
23978
- 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";
23979
24565
  } catch (error) {
23980
24566
  return error.code === "ENOENT" ? "missing" : "foreign";
23981
24567
  }
23982
24568
  }
23983
24569
  function hooksPathReason(scope) {
23984
24570
  if (!scope.hooksPathConfigRaw.length) {
23985
- 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`;
23986
24572
  }
23987
24573
  if (scope.hooksPathConfigs.length !== 1 || scope.hooksPathConfigRaw.length !== 1) {
23988
24574
  return `core.hooksPath is ambiguous: ${scope.hooksPathConfigRaw.join("; ")}`;
@@ -24033,7 +24619,7 @@ function installGitHooks(repo, force, allowSharedGitHooks) {
24033
24619
  ["pre-commit", preCommit()],
24034
24620
  ["pre-push", prePush()]
24035
24621
  ];
24036
- 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))]));
24037
24623
  const reasons = [];
24038
24624
  const configuredPathReason = hooksPathReason(scope);
24039
24625
  if (configuredPathReason) reasons.push(configuredPathReason);
@@ -24056,10 +24642,10 @@ function installGitHooks(repo, force, allowSharedGitHooks) {
24056
24642
  );
24057
24643
  }
24058
24644
  for (const [name, body] of targets) {
24059
- const p = (0, import_node_path15.join)(scope.hooksDir, name);
24645
+ const p = (0, import_node_path16.join)(scope.hooksDir, name);
24060
24646
  const wasManaged = ownership.get(name) === "managed";
24061
24647
  writeText(p, body);
24062
- (0, import_node_fs16.chmodSync)(p, 493);
24648
+ (0, import_node_fs17.chmodSync)(p, 493);
24063
24649
  ok(`${wasManaged ? force ? "refreshed" : "updated" : "installed"} ${name}`);
24064
24650
  }
24065
24651
  info(`
@@ -24172,10 +24758,10 @@ function recordContextReviewCmd(repo, opts) {
24172
24758
  }
24173
24759
 
24174
24760
  // src/commands/prepare-adoption.ts
24175
- var import_node_path16 = require("node:path");
24761
+ var import_node_path17 = require("node:path");
24176
24762
  function prepareAdoptionCmd(repo, opts) {
24177
24763
  if (!opts.output?.trim()) throw new Error("candidate output directory is required");
24178
- const output = (0, import_node_path16.resolve)(opts.output);
24764
+ const output = (0, import_node_path17.resolve)(opts.output);
24179
24765
  const candidate = prepareAdoptionCandidate(repo, output);
24180
24766
  const result = {
24181
24767
  ok: true,
@@ -24193,15 +24779,15 @@ function prepareAdoptionCmd(repo, opts) {
24193
24779
  }
24194
24780
 
24195
24781
  // src/commands/record-adoption-audit.ts
24196
- var import_node_path17 = require("node:path");
24782
+ var import_node_path18 = require("node:path");
24197
24783
  function recordAdoptionAuditCmd(repo, opts) {
24198
24784
  if (!opts.candidate?.trim()) throw new Error("candidate directory is required");
24199
24785
  if (!opts.report?.trim()) throw new Error("audit report path is required");
24200
- const recorded = recordAdoptionAudit(repo, (0, import_node_path17.resolve)(opts.candidate), {
24786
+ const recorded = recordAdoptionAudit(repo, (0, import_node_path18.resolve)(opts.candidate), {
24201
24787
  verdict: opts.verdict,
24202
24788
  reason: opts.reason,
24203
- reportPath: (0, import_node_path17.resolve)(opts.report),
24204
- 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
24205
24791
  });
24206
24792
  const result = {
24207
24793
  ok: true,
@@ -24217,6 +24803,134 @@ function recordAdoptionAuditCmd(repo, opts) {
24217
24803
  return 0;
24218
24804
  }
24219
24805
 
24806
+ // src/commands/upgrade.ts
24807
+ var import_node_util = require("node:util");
24808
+ function captureOutput(run) {
24809
+ const chunks = [];
24810
+ const originalLog = console.log;
24811
+ const originalWrite = process.stdout.write;
24812
+ console.log = (...args) => {
24813
+ chunks.push(`${(0, import_node_util.format)(...args)}
24814
+ `);
24815
+ };
24816
+ process.stdout.write = ((chunk) => {
24817
+ chunks.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));
24818
+ return true;
24819
+ });
24820
+ try {
24821
+ return { exitCode: run(), output: chunks.join("") };
24822
+ } catch (error) {
24823
+ return { exitCode: 1, output: chunks.join(""), error: error.message };
24824
+ } finally {
24825
+ console.log = originalLog;
24826
+ process.stdout.write = originalWrite;
24827
+ }
24828
+ }
24829
+ function runJsonVerification(repo, report) {
24830
+ const doctor = captureOutput(() => doctorCmd(repo, { details: true }));
24831
+ const verify = captureOutput(() => verifyCmd(repo, { json: true, details: true, recordManualEvidence: false }));
24832
+ let verifyReport;
24833
+ try {
24834
+ verifyReport = JSON.parse(verify.output);
24835
+ } catch {
24836
+ verifyReport = void 0;
24837
+ }
24838
+ report.verification = {
24839
+ doctor: { exitCode: doctor.exitCode, output: doctor.output, ...doctor.error ? { error: doctor.error } : {} },
24840
+ verify: verifyReport === void 0 ? { exitCode: verify.exitCode, output: verify.output, ...verify.error ? { error: verify.error } : {} } : { exitCode: verify.exitCode, report: verifyReport, ...verify.error ? { error: verify.error } : {} }
24841
+ };
24842
+ if (doctor.exitCode !== 0 || verify.exitCode !== 0) {
24843
+ report.status = "incomplete";
24844
+ report.errors.push("post-upgrade doctor or verify failed");
24845
+ return 1;
24846
+ }
24847
+ return 0;
24848
+ }
24849
+ function printHumanReport(report) {
24850
+ if (report.status === "blocked") {
24851
+ for (const message of report.errors) err(message);
24852
+ return;
24853
+ }
24854
+ if (report.status === "upgrade-available") {
24855
+ warn(`upgrade available: ${report.fromVersion ?? "untracked"} -> ${report.toVersion}`);
24856
+ if (report.pendingMigrations.length) info(`Pending migrations: ${report.pendingMigrations.join(", ")}`);
24857
+ if (report.changedFiles.length) info(`Files to update: ${report.changedFiles.join(", ")}`);
24858
+ if (report.dirtyFiles.length) warn("apply is blocked until the target Git scope is clean");
24859
+ return;
24860
+ }
24861
+ if (report.status === "current") {
24862
+ ok(`repository is current at ${report.toVersion}`);
24863
+ return;
24864
+ }
24865
+ ok(`upgraded repository: ${report.fromVersion ?? "untracked"} -> ${report.toVersion}`);
24866
+ for (const path of report.changedFiles) ok(`wrote ${path}`);
24867
+ info("Lifecycle hooks were not changed. Manage them explicitly with `harness-kit install-hooks`.");
24868
+ }
24869
+ function upgradeCmd(repo, options = {}) {
24870
+ const report = upgradeRepository(repo, {
24871
+ packageName: package_default.name,
24872
+ targetVersion: package_default.version,
24873
+ check: options.check
24874
+ });
24875
+ if (options.json) {
24876
+ let code = report.status === "blocked" ? 1 : report.status === "upgrade-available" ? 2 : 0;
24877
+ if (!options.check && (report.status === "upgraded" || report.status === "current"))
24878
+ code = runJsonVerification(repo, report);
24879
+ process.stdout.write(`${JSON.stringify(report)}
24880
+ `);
24881
+ return code;
24882
+ }
24883
+ printHumanReport(report);
24884
+ if (report.status === "blocked") return 1;
24885
+ if (report.status === "upgrade-available") return 2;
24886
+ if (options.check) return 0;
24887
+ info("\nRunning post-upgrade doctor --details ...");
24888
+ const doctorCode = doctorCmd(repo, { details: true });
24889
+ info("\nRunning post-upgrade verify --details ...");
24890
+ const verifyCode = verifyCmd(repo, { details: true, recordManualEvidence: false });
24891
+ if (doctorCode !== 0 || verifyCode !== 0) {
24892
+ err("upgrade applied, but post-upgrade verification is incomplete");
24893
+ return 1;
24894
+ }
24895
+ ok("upgrade complete; doctor and verify exited 0 (read their readiness output above)");
24896
+ return 0;
24897
+ }
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
+
24220
24934
  // src/cli.ts
24221
24935
  function guard(fn) {
24222
24936
  try {
@@ -24229,7 +24943,7 @@ function guard(fn) {
24229
24943
  }
24230
24944
  var program2 = new Command();
24231
24945
  program2.name("harness-kit").description("AI-friendly repo harness").version(package_default.version);
24232
- 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());
24233
24947
  function agentList(value) {
24234
24948
  const agents = value.split(",").map((item) => item.trim()).filter(Boolean);
24235
24949
  const invalid = agents.filter((agent) => !ALL_AGENTS.includes(agent));
@@ -24246,6 +24960,7 @@ program2.command("sync").description("generate tool files (AGENTS.md, CLAUDE.md)
24246
24960
  })
24247
24961
  )
24248
24962
  );
24963
+ program2.command("upgrade").description("upgrade this repository to the running harness-kit version").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--check", "read-only; exit 2 when an upgrade is available", false).option("--json", "machine-readable single-report output", false).action((o) => guard(() => upgradeCmd(repoOf(o), { check: o.check, json: o.json })));
24249
24964
  program2.command("prepare-adoption").description("render a private, repository-external candidate bundle for blind legacy review").option("-C, --repo <dir>", "target repo dir (default: current directory)").requiredOption("--out <dir>", "new or empty output directory outside the repository").option("--json", "machine-readable output", false).action((o) => guard(() => prepareAdoptionCmd(repoOf(o), { output: o.out, json: o.json })));
24250
24965
  program2.command("record-adoption-audit").description("record a declared pass/fail review receipt bound to one adoption candidate and report").option("-C, --repo <dir>", "target repo dir (default: current directory)").requiredOption("--candidate <dir>", "prepared adoption bundle outside the repository").requiredOption("--verdict <pass|fail>", "declared audit verdict").requiredOption("--report <file>", "independent audit report to hash and bind").requiredOption("--reason <text>", "non-empty reviewer rationale").option("--out <receipt>", "receipt path outside the repository (default: candidate bundle)").option("--json", "machine-readable output", false).action(
24251
24966
  (o) => guard(
@@ -24262,6 +24977,17 @@ program2.command("record-adoption-audit").description("record a declared pass/fa
24262
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 })));
24263
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 })));
24264
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
+ );
24265
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(
24266
24992
  (o) => guard(
24267
24993
  () => runChecksCmd(repoOf(o), {
@@ -24275,7 +25001,7 @@ program2.command("run-checks").description("plan + run resolved checks; record e
24275
25001
  })
24276
25002
  )
24277
25003
  );
24278
- 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 })));
24279
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(
24280
25006
  (o) => guard(
24281
25007
  () => recordContextReviewCmd(repoOf(o), {