@erzhe/harness-kit 0.5.1 → 0.7.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.
@@ -4441,9 +4441,9 @@ var require_parse = __commonJS({
4441
4441
  const idx = prev.value.lastIndexOf("[");
4442
4442
  const pre = prev.value.slice(0, idx);
4443
4443
  const rest2 = prev.value.slice(idx + 2);
4444
- const posix = POSIX_REGEX_SOURCE[rest2];
4445
- if (posix) {
4446
- prev.value = pre + posix;
4444
+ const posix2 = POSIX_REGEX_SOURCE[rest2];
4445
+ if (posix2) {
4446
+ prev.value = pre + posix2;
4447
4447
  state.backtrack = true;
4448
4448
  advance();
4449
4449
  if (!bos.output && tokens.indexOf(prev) === 1) {
@@ -4959,7 +4959,7 @@ var require_picomatch = __commonJS({
4959
4959
  throw new TypeError("Expected pattern to be a non-empty string");
4960
4960
  }
4961
4961
  const opts = options || {};
4962
- const posix = opts.windows;
4962
+ const posix2 = opts.windows;
4963
4963
  const regex = isState ? picomatch4.compileRe(glob, options) : picomatch4.makeRe(glob, options, false, true);
4964
4964
  const state = regex.state;
4965
4965
  delete regex.state;
@@ -4969,8 +4969,8 @@ var require_picomatch = __commonJS({
4969
4969
  isIgnored = picomatch4(opts.ignore, ignoreOpts, returnState);
4970
4970
  }
4971
4971
  const matcher = (input, returnObject = false) => {
4972
- const { isMatch, match, output } = picomatch4.test(input, regex, options, { glob, posix });
4973
- const result = { glob, state, regex, posix, input, output, match, isMatch };
4972
+ const { isMatch, match, output } = picomatch4.test(input, regex, options, { glob, posix: posix2 });
4973
+ const result = { glob, state, regex, posix: posix2, input, output, match, isMatch };
4974
4974
  if (typeof opts.onResult === "function") {
4975
4975
  opts.onResult(result);
4976
4976
  }
@@ -4995,7 +4995,7 @@ var require_picomatch = __commonJS({
4995
4995
  }
4996
4996
  return matcher;
4997
4997
  };
4998
- picomatch4.test = (input, regex, options, { glob, posix } = {}) => {
4998
+ picomatch4.test = (input, regex, options, { glob, posix: posix2 } = {}) => {
4999
4999
  if (typeof input !== "string") {
5000
5000
  throw new TypeError("Expected input to be a string");
5001
5001
  }
@@ -5003,7 +5003,7 @@ var require_picomatch = __commonJS({
5003
5003
  return { isMatch: false, output: "" };
5004
5004
  }
5005
5005
  const opts = options || {};
5006
- const format2 = opts.format || (posix ? utils.toPosixSlashes : null);
5006
+ const format2 = opts.format || (posix2 ? utils.toPosixSlashes : null);
5007
5007
  let match = input === glob;
5008
5008
  let output = match && format2 ? format2(input) : input;
5009
5009
  if (match === false) {
@@ -5012,16 +5012,16 @@ var require_picomatch = __commonJS({
5012
5012
  }
5013
5013
  if (match === false || opts.capture === true) {
5014
5014
  if (opts.matchBase === true || opts.basename === true) {
5015
- match = picomatch4.matchBase(input, regex, options, posix);
5015
+ match = picomatch4.matchBase(input, regex, options, posix2);
5016
5016
  } else {
5017
5017
  match = regex.exec(output);
5018
5018
  }
5019
5019
  }
5020
5020
  return { isMatch: Boolean(match), match, output };
5021
5021
  };
5022
- picomatch4.matchBase = (input, glob, options, posix = options && options.windows) => {
5022
+ picomatch4.matchBase = (input, glob, options, posix2 = options && options.windows) => {
5023
5023
  const regex = glob instanceof RegExp ? glob : picomatch4.makeRe(glob, options);
5024
- return regex.test(utils.basename(input, { windows: posix }));
5024
+ return regex.test(utils.basename(input, { windows: posix2 }));
5025
5025
  };
5026
5026
  picomatch4.isMatch = (str, patterns, options) => picomatch4(patterns, options)(str);
5027
5027
  picomatch4.parse = (pattern, options) => {
@@ -9051,10 +9051,10 @@ var require_resolve_block_map = __commonJS({
9051
9051
  let offset = bm.offset;
9052
9052
  let commentEnd = null;
9053
9053
  for (const collItem of bm.items) {
9054
- const { start, key, sep: sep5, value } = collItem;
9054
+ const { start, key, sep: sep6, value } = collItem;
9055
9055
  const keyProps = resolveProps.resolveProps(start, {
9056
9056
  indicator: "explicit-key-ind",
9057
- next: key ?? sep5?.[0],
9057
+ next: key ?? sep6?.[0],
9058
9058
  offset,
9059
9059
  onError,
9060
9060
  parentIndent: bm.indent,
@@ -9068,7 +9068,7 @@ var require_resolve_block_map = __commonJS({
9068
9068
  else if ("indent" in key && key.indent !== bm.indent)
9069
9069
  onError(offset, "BAD_INDENT", startColMsg);
9070
9070
  }
9071
- if (!keyProps.anchor && !keyProps.tag && !sep5) {
9071
+ if (!keyProps.anchor && !keyProps.tag && !sep6) {
9072
9072
  commentEnd = keyProps.end;
9073
9073
  if (keyProps.comment) {
9074
9074
  if (map.comment)
@@ -9092,7 +9092,7 @@ var require_resolve_block_map = __commonJS({
9092
9092
  ctx.atKey = false;
9093
9093
  if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
9094
9094
  onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
9095
- const valueProps = resolveProps.resolveProps(sep5 ?? [], {
9095
+ const valueProps = resolveProps.resolveProps(sep6 ?? [], {
9096
9096
  indicator: "map-value-ind",
9097
9097
  next: value,
9098
9098
  offset: keyNode.range[2],
@@ -9108,7 +9108,7 @@ var require_resolve_block_map = __commonJS({
9108
9108
  if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
9109
9109
  onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
9110
9110
  }
9111
- const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep5, null, valueProps, onError);
9111
+ const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep6, null, valueProps, onError);
9112
9112
  if (ctx.schema.compat)
9113
9113
  utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
9114
9114
  offset = valueNode.range[2];
@@ -9199,7 +9199,7 @@ var require_resolve_end = __commonJS({
9199
9199
  let comment = "";
9200
9200
  if (end) {
9201
9201
  let hasSpace = false;
9202
- let sep5 = "";
9202
+ let sep6 = "";
9203
9203
  for (const token of end) {
9204
9204
  const { source, type } = token;
9205
9205
  switch (type) {
@@ -9213,13 +9213,13 @@ var require_resolve_end = __commonJS({
9213
9213
  if (!comment)
9214
9214
  comment = cb;
9215
9215
  else
9216
- comment += sep5 + cb;
9217
- sep5 = "";
9216
+ comment += sep6 + cb;
9217
+ sep6 = "";
9218
9218
  break;
9219
9219
  }
9220
9220
  case "newline":
9221
9221
  if (comment)
9222
- sep5 += source;
9222
+ sep6 += source;
9223
9223
  hasSpace = true;
9224
9224
  break;
9225
9225
  default:
@@ -9262,18 +9262,18 @@ var require_resolve_flow_collection = __commonJS({
9262
9262
  let offset = fc.offset + fc.start.source.length;
9263
9263
  for (let i = 0; i < fc.items.length; ++i) {
9264
9264
  const collItem = fc.items[i];
9265
- const { start, key, sep: sep5, value } = collItem;
9265
+ const { start, key, sep: sep6, value } = collItem;
9266
9266
  const props = resolveProps.resolveProps(start, {
9267
9267
  flow: fcName,
9268
9268
  indicator: "explicit-key-ind",
9269
- next: key ?? sep5?.[0],
9269
+ next: key ?? sep6?.[0],
9270
9270
  offset,
9271
9271
  onError,
9272
9272
  parentIndent: fc.indent,
9273
9273
  startOnNewline: false
9274
9274
  });
9275
9275
  if (!props.found) {
9276
- if (!props.anchor && !props.tag && !sep5 && !value) {
9276
+ if (!props.anchor && !props.tag && !sep6 && !value) {
9277
9277
  if (i === 0 && props.comma)
9278
9278
  onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
9279
9279
  else if (i < fc.items.length - 1)
@@ -9327,8 +9327,8 @@ var require_resolve_flow_collection = __commonJS({
9327
9327
  }
9328
9328
  }
9329
9329
  }
9330
- if (!isMap && !sep5 && !props.found) {
9331
- const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep5, null, props, onError);
9330
+ if (!isMap && !sep6 && !props.found) {
9331
+ const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep6, null, props, onError);
9332
9332
  coll.items.push(valueNode);
9333
9333
  offset = valueNode.range[2];
9334
9334
  if (isBlock(value))
@@ -9340,7 +9340,7 @@ var require_resolve_flow_collection = __commonJS({
9340
9340
  if (isBlock(key))
9341
9341
  onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
9342
9342
  ctx.atKey = false;
9343
- const valueProps = resolveProps.resolveProps(sep5 ?? [], {
9343
+ const valueProps = resolveProps.resolveProps(sep6 ?? [], {
9344
9344
  flow: fcName,
9345
9345
  indicator: "map-value-ind",
9346
9346
  next: value,
@@ -9351,8 +9351,8 @@ var require_resolve_flow_collection = __commonJS({
9351
9351
  });
9352
9352
  if (valueProps.found) {
9353
9353
  if (!isMap && !props.found && ctx.options.strict) {
9354
- if (sep5)
9355
- for (const st of sep5) {
9354
+ if (sep6)
9355
+ for (const st of sep6) {
9356
9356
  if (st === valueProps.found)
9357
9357
  break;
9358
9358
  if (st.type === "newline") {
@@ -9369,7 +9369,7 @@ var require_resolve_flow_collection = __commonJS({
9369
9369
  else
9370
9370
  onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
9371
9371
  }
9372
- const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep5, null, valueProps, onError) : null;
9372
+ const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep6, null, valueProps, onError) : null;
9373
9373
  if (valueNode) {
9374
9374
  if (isBlock(value))
9375
9375
  onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
@@ -9549,7 +9549,7 @@ var require_resolve_block_scalar = __commonJS({
9549
9549
  chompStart = i + 1;
9550
9550
  }
9551
9551
  let value = "";
9552
- let sep5 = "";
9552
+ let sep6 = "";
9553
9553
  let prevMoreIndented = false;
9554
9554
  for (let i = 0; i < contentStart; ++i)
9555
9555
  value += lines[i][0].slice(trimIndent) + "\n";
@@ -9566,24 +9566,24 @@ var require_resolve_block_scalar = __commonJS({
9566
9566
  indent = "";
9567
9567
  }
9568
9568
  if (type === Scalar.Scalar.BLOCK_LITERAL) {
9569
- value += sep5 + indent.slice(trimIndent) + content;
9570
- sep5 = "\n";
9569
+ value += sep6 + indent.slice(trimIndent) + content;
9570
+ sep6 = "\n";
9571
9571
  } else if (indent.length > trimIndent || content[0] === " ") {
9572
- if (sep5 === " ")
9573
- sep5 = "\n";
9574
- else if (!prevMoreIndented && sep5 === "\n")
9575
- sep5 = "\n\n";
9576
- value += sep5 + indent.slice(trimIndent) + content;
9577
- sep5 = "\n";
9572
+ if (sep6 === " ")
9573
+ sep6 = "\n";
9574
+ else if (!prevMoreIndented && sep6 === "\n")
9575
+ sep6 = "\n\n";
9576
+ value += sep6 + indent.slice(trimIndent) + content;
9577
+ sep6 = "\n";
9578
9578
  prevMoreIndented = true;
9579
9579
  } else if (content === "") {
9580
- if (sep5 === "\n")
9580
+ if (sep6 === "\n")
9581
9581
  value += "\n";
9582
9582
  else
9583
- sep5 = "\n";
9583
+ sep6 = "\n";
9584
9584
  } else {
9585
- value += sep5 + content;
9586
- sep5 = " ";
9585
+ value += sep6 + content;
9586
+ sep6 = " ";
9587
9587
  prevMoreIndented = false;
9588
9588
  }
9589
9589
  }
@@ -9765,25 +9765,25 @@ var require_resolve_flow_scalar = __commonJS({
9765
9765
  if (!match)
9766
9766
  return source;
9767
9767
  let res = match[1];
9768
- let sep5 = " ";
9768
+ let sep6 = " ";
9769
9769
  let pos = first.lastIndex;
9770
9770
  line.lastIndex = pos;
9771
9771
  while (match = line.exec(source)) {
9772
9772
  if (match[1] === "") {
9773
- if (sep5 === "\n")
9774
- res += sep5;
9773
+ if (sep6 === "\n")
9774
+ res += sep6;
9775
9775
  else
9776
- sep5 = "\n";
9776
+ sep6 = "\n";
9777
9777
  } else {
9778
- res += sep5 + match[1];
9779
- sep5 = " ";
9778
+ res += sep6 + match[1];
9779
+ sep6 = " ";
9780
9780
  }
9781
9781
  pos = line.lastIndex;
9782
9782
  }
9783
9783
  const last = /[ \t]*(.*)/sy;
9784
9784
  last.lastIndex = pos;
9785
9785
  match = last.exec(source);
9786
- return res + sep5 + (match?.[1] ?? "");
9786
+ return res + sep6 + (match?.[1] ?? "");
9787
9787
  }
9788
9788
  function doubleQuotedValue(source, onError) {
9789
9789
  let res = "";
@@ -10593,14 +10593,14 @@ var require_cst_stringify = __commonJS({
10593
10593
  }
10594
10594
  }
10595
10595
  }
10596
- function stringifyItem({ start, key, sep: sep5, value }) {
10596
+ function stringifyItem({ start, key, sep: sep6, value }) {
10597
10597
  let res = "";
10598
10598
  for (const st of start)
10599
10599
  res += st.source;
10600
10600
  if (key)
10601
10601
  res += stringifyToken(key);
10602
- if (sep5)
10603
- for (const st of sep5)
10602
+ if (sep6)
10603
+ for (const st of sep6)
10604
10604
  res += st.source;
10605
10605
  if (value)
10606
10606
  res += stringifyToken(value);
@@ -11767,18 +11767,18 @@ var require_parser = __commonJS({
11767
11767
  if (this.type === "map-value-ind") {
11768
11768
  const prev = getPrevProps(this.peek(2));
11769
11769
  const start = getFirstKeyStartProps(prev);
11770
- let sep5;
11770
+ let sep6;
11771
11771
  if (scalar.end) {
11772
- sep5 = scalar.end;
11773
- sep5.push(this.sourceToken);
11772
+ sep6 = scalar.end;
11773
+ sep6.push(this.sourceToken);
11774
11774
  delete scalar.end;
11775
11775
  } else
11776
- sep5 = [this.sourceToken];
11776
+ sep6 = [this.sourceToken];
11777
11777
  const map = {
11778
11778
  type: "block-map",
11779
11779
  offset: scalar.offset,
11780
11780
  indent: scalar.indent,
11781
- items: [{ start, key: scalar, sep: sep5 }]
11781
+ items: [{ start, key: scalar, sep: sep6 }]
11782
11782
  };
11783
11783
  this.onKeyLine = true;
11784
11784
  this.stack[this.stack.length - 1] = map;
@@ -11931,15 +11931,15 @@ var require_parser = __commonJS({
11931
11931
  } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
11932
11932
  const start2 = getFirstKeyStartProps(it.start);
11933
11933
  const key = it.key;
11934
- const sep5 = it.sep;
11935
- sep5.push(this.sourceToken);
11934
+ const sep6 = it.sep;
11935
+ sep6.push(this.sourceToken);
11936
11936
  delete it.key;
11937
11937
  delete it.sep;
11938
11938
  this.stack.push({
11939
11939
  type: "block-map",
11940
11940
  offset: this.offset,
11941
11941
  indent: this.indent,
11942
- items: [{ start: start2, key, sep: sep5 }]
11942
+ items: [{ start: start2, key, sep: sep6 }]
11943
11943
  });
11944
11944
  } else if (start.length > 0) {
11945
11945
  it.sep = it.sep.concat(start, this.sourceToken);
@@ -12133,13 +12133,13 @@ var require_parser = __commonJS({
12133
12133
  const prev = getPrevProps(parent);
12134
12134
  const start = getFirstKeyStartProps(prev);
12135
12135
  fixFlowSeqItems(fc);
12136
- const sep5 = fc.end.splice(1, fc.end.length);
12137
- sep5.push(this.sourceToken);
12136
+ const sep6 = fc.end.splice(1, fc.end.length);
12137
+ sep6.push(this.sourceToken);
12138
12138
  const map = {
12139
12139
  type: "block-map",
12140
12140
  offset: fc.offset,
12141
12141
  indent: fc.indent,
12142
- items: [{ start, key: fc, sep: sep5 }]
12142
+ items: [{ start, key: fc, sep: sep6 }]
12143
12143
  };
12144
12144
  this.onKeyLine = true;
12145
12145
  this.stack[this.stack.length - 1] = map;
@@ -14892,9 +14892,9 @@ var require_parse3 = __commonJS({
14892
14892
  const idx = prev.value.lastIndexOf("[");
14893
14893
  const pre = prev.value.slice(0, idx);
14894
14894
  const rest2 = prev.value.slice(idx + 2);
14895
- const posix = POSIX_REGEX_SOURCE[rest2];
14896
- if (posix) {
14897
- prev.value = pre + posix;
14895
+ const posix2 = POSIX_REGEX_SOURCE[rest2];
14896
+ if (posix2) {
14897
+ prev.value = pre + posix2;
14898
14898
  state.backtrack = true;
14899
14899
  advance();
14900
14900
  if (!bos.output && tokens.indexOf(prev) === 1) {
@@ -15415,7 +15415,7 @@ var require_picomatch3 = __commonJS({
15415
15415
  throw new TypeError("Expected pattern to be a non-empty string");
15416
15416
  }
15417
15417
  const opts = options || {};
15418
- const posix = utils.isWindows(options);
15418
+ const posix2 = utils.isWindows(options);
15419
15419
  const regex = isState ? picomatch4.compileRe(glob, options) : picomatch4.makeRe(glob, options, false, true);
15420
15420
  const state = regex.state;
15421
15421
  delete regex.state;
@@ -15425,8 +15425,8 @@ var require_picomatch3 = __commonJS({
15425
15425
  isIgnored = picomatch4(opts.ignore, ignoreOpts, returnState);
15426
15426
  }
15427
15427
  const matcher = (input, returnObject = false) => {
15428
- const { isMatch, match, output } = picomatch4.test(input, regex, options, { glob, posix });
15429
- const result = { glob, state, regex, posix, input, output, match, isMatch };
15428
+ const { isMatch, match, output } = picomatch4.test(input, regex, options, { glob, posix: posix2 });
15429
+ const result = { glob, state, regex, posix: posix2, input, output, match, isMatch };
15430
15430
  if (typeof opts.onResult === "function") {
15431
15431
  opts.onResult(result);
15432
15432
  }
@@ -15451,7 +15451,7 @@ var require_picomatch3 = __commonJS({
15451
15451
  }
15452
15452
  return matcher;
15453
15453
  };
15454
- picomatch4.test = (input, regex, options, { glob, posix } = {}) => {
15454
+ picomatch4.test = (input, regex, options, { glob, posix: posix2 } = {}) => {
15455
15455
  if (typeof input !== "string") {
15456
15456
  throw new TypeError("Expected input to be a string");
15457
15457
  }
@@ -15459,7 +15459,7 @@ var require_picomatch3 = __commonJS({
15459
15459
  return { isMatch: false, output: "" };
15460
15460
  }
15461
15461
  const opts = options || {};
15462
- const format2 = opts.format || (posix ? utils.toPosixSlashes : null);
15462
+ const format2 = opts.format || (posix2 ? utils.toPosixSlashes : null);
15463
15463
  let match = input === glob;
15464
15464
  let output = match && format2 ? format2(input) : input;
15465
15465
  if (match === false) {
@@ -15468,14 +15468,14 @@ var require_picomatch3 = __commonJS({
15468
15468
  }
15469
15469
  if (match === false || opts.capture === true) {
15470
15470
  if (opts.matchBase === true || opts.basename === true) {
15471
- match = picomatch4.matchBase(input, regex, options, posix);
15471
+ match = picomatch4.matchBase(input, regex, options, posix2);
15472
15472
  } else {
15473
15473
  match = regex.exec(output);
15474
15474
  }
15475
15475
  }
15476
15476
  return { isMatch: Boolean(match), match, output };
15477
15477
  };
15478
- picomatch4.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
15478
+ picomatch4.matchBase = (input, glob, options, posix2 = utils.isWindows(options)) => {
15479
15479
  const regex = glob instanceof RegExp ? glob : picomatch4.makeRe(glob, options);
15480
15480
  return regex.test(path.basename(input));
15481
15481
  };
@@ -15664,9 +15664,9 @@ var require_micromatch = __commonJS({
15664
15664
  return [].concat(patterns).every((p) => picomatch4(p, options)(str));
15665
15665
  };
15666
15666
  micromatch.capture = (glob, input, options) => {
15667
- let posix = utils.isWindows(options);
15667
+ let posix2 = utils.isWindows(options);
15668
15668
  let regex = picomatch4.makeRe(String(glob), { ...options, capture: true });
15669
- let match = regex.exec(posix ? utils.toPosixSlashes(input) : input);
15669
+ let match = regex.exec(posix2 ? utils.toPosixSlashes(input) : input);
15670
15670
  if (match) {
15671
15671
  return match.slice(1).map((v) => v === void 0 ? "" : v);
15672
15672
  }
@@ -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
  };
@@ -18117,19 +18117,19 @@ var require_out4 = __commonJS({
18117
18117
  return utils.path.convertPathToPattern(source);
18118
18118
  }
18119
18119
  FastGlob2.convertPathToPattern = convertPathToPattern;
18120
- let posix;
18121
- (function(posix2) {
18120
+ let posix2;
18121
+ (function(posix3) {
18122
18122
  function escapePath2(source) {
18123
18123
  assertPatternsInput(source);
18124
18124
  return utils.path.escapePosixPath(source);
18125
18125
  }
18126
- posix2.escapePath = escapePath2;
18126
+ posix3.escapePath = escapePath2;
18127
18127
  function convertPathToPattern2(source) {
18128
18128
  assertPatternsInput(source);
18129
18129
  return utils.path.convertPosixPathToPattern(source);
18130
18130
  }
18131
- posix2.convertPathToPattern = convertPathToPattern2;
18132
- })(posix = FastGlob2.posix || (FastGlob2.posix = {}));
18131
+ posix3.convertPathToPattern = convertPathToPattern2;
18132
+ })(posix2 = FastGlob2.posix || (FastGlob2.posix = {}));
18133
18133
  let win32;
18134
18134
  (function(win322) {
18135
18135
  function escapePath2(source) {
@@ -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_path21 = require("node:path");
18184
18184
 
18185
18185
  // package.json
18186
18186
  var package_default = {
18187
18187
  name: "@erzhe/harness-kit",
18188
- version: "0.5.1",
18188
+ version: "0.7.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: [
@@ -18199,13 +18199,13 @@ var package_default = {
18199
18199
  "cursor",
18200
18200
  "claude"
18201
18201
  ],
18202
- homepage: "https://github.com/MeCKodo/harness-kit#readme",
18202
+ homepage: "https://github.com/reunion-labs/harness-kit#readme",
18203
18203
  repository: {
18204
18204
  type: "git",
18205
- url: "git+https://github.com/MeCKodo/harness-kit.git"
18205
+ url: "git+https://github.com/reunion-labs/harness-kit.git"
18206
18206
  },
18207
18207
  bugs: {
18208
- url: "https://github.com/MeCKodo/harness-kit/issues"
18208
+ url: "https://github.com/reunion-labs/harness-kit/issues"
18209
18209
  },
18210
18210
  author: "MeCKodo (\u4E8C\u54F2) <https://erzhe.me/>",
18211
18211
  license: "MIT",
@@ -18250,8 +18250,8 @@ var package_default = {
18250
18250
  // src/adoption.ts
18251
18251
  var import_node_child_process2 = require("node:child_process");
18252
18252
  var import_node_crypto4 = require("node:crypto");
18253
- var import_node_fs5 = require("node:fs");
18254
- var import_node_path5 = require("node:path");
18253
+ var import_node_fs6 = require("node:fs");
18254
+ var import_node_path6 = require("node:path");
18255
18255
 
18256
18256
  // src/manifest.ts
18257
18257
  var import_node_fs2 = require("node:fs");
@@ -19171,27 +19171,52 @@ function writeManagedFiles(repo, targets, options = {}) {
19171
19171
  };
19172
19172
  }
19173
19173
 
19174
- // src/util.ts
19175
- var import_node_crypto3 = require("node:crypto");
19174
+ // src/harness-cli.ts
19176
19175
  var import_node_fs4 = require("node:fs");
19177
19176
  var import_node_path4 = require("node:path");
19177
+ var HARNESS_LOCK_REL = ".agents/harness.lock.json";
19178
+ var HARNESS_PACKAGE = package_default.name;
19179
+ var SAFE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
19180
+ function lockedHarnessVersion(repo) {
19181
+ const path = (0, import_node_path4.join)(repo, HARNESS_LOCK_REL);
19182
+ try {
19183
+ if (!(0, import_node_fs4.lstatSync)(path).isFile()) return null;
19184
+ const value = JSON.parse((0, import_node_fs4.readFileSync)(path, "utf8"));
19185
+ if (value?.package !== HARNESS_PACKAGE || typeof value.version !== "string") return null;
19186
+ return SAFE_VERSION.test(value.version) ? value.version : null;
19187
+ } catch {
19188
+ return null;
19189
+ }
19190
+ }
19191
+ function harnessInvocation(version) {
19192
+ const pinned = version && SAFE_VERSION.test(version) ? version : "latest";
19193
+ return `npx -y ${HARNESS_PACKAGE}@${pinned}`;
19194
+ }
19195
+ function repoHarnessInvocation(repo) {
19196
+ return harnessInvocation(lockedHarnessVersion(repo));
19197
+ }
19198
+
19199
+ // src/util.ts
19200
+ var import_node_crypto3 = require("node:crypto");
19201
+ var import_node_fs5 = require("node:fs");
19202
+ var import_node_path5 = require("node:path");
19178
19203
  function sha256(input) {
19179
19204
  return (0, import_node_crypto3.createHash)("sha256").update(input).digest("hex");
19180
19205
  }
19181
19206
  function hashFile(absPath) {
19182
19207
  try {
19183
- if (!(0, import_node_fs4.statSync)(absPath).isFile()) return null;
19184
- return sha256((0, import_node_fs4.readFileSync)(absPath));
19208
+ if (!(0, import_node_fs5.statSync)(absPath).isFile()) return null;
19209
+ return sha256((0, import_node_fs5.readFileSync)(absPath));
19185
19210
  } catch {
19186
19211
  return null;
19187
19212
  }
19188
19213
  }
19189
19214
  function readText(absPath) {
19190
- return (0, import_node_fs4.existsSync)(absPath) ? (0, import_node_fs4.readFileSync)(absPath, "utf8") : null;
19215
+ return (0, import_node_fs5.existsSync)(absPath) ? (0, import_node_fs5.readFileSync)(absPath, "utf8") : null;
19191
19216
  }
19192
19217
  function writeText(absPath, content) {
19193
- (0, import_node_fs4.mkdirSync)((0, import_node_path4.dirname)(absPath), { recursive: true });
19194
- (0, import_node_fs4.writeFileSync)(absPath, content);
19218
+ (0, import_node_fs5.mkdirSync)((0, import_node_path5.dirname)(absPath), { recursive: true });
19219
+ (0, import_node_fs5.writeFileSync)(absPath, content);
19195
19220
  }
19196
19221
  var ok = (m) => console.log(` OK ${m}`);
19197
19222
  var err = (m) => console.log(` ERR ${m}`);
@@ -19206,9 +19231,9 @@ function safeStr(v) {
19206
19231
  if (typeof v === "number" || typeof v === "boolean") return String(v);
19207
19232
  return JSON.stringify(v);
19208
19233
  }
19209
- function renderTargets(m) {
19234
+ function renderTargets(m, opts = {}) {
19210
19235
  const targets = [
19211
- ["AGENTS.md", renderAgentsMd(m)],
19236
+ ["AGENTS.md", renderAgentsMd(m, opts)],
19212
19237
  ["CLAUDE.md", renderClaudeMd()],
19213
19238
  [".agents/reference.md", renderReferenceMd(m)]
19214
19239
  ];
@@ -19216,15 +19241,20 @@ function renderTargets(m) {
19216
19241
  if (m.modules?.length) targets.push([".agents/modules.md", renderModulesMd(m)]);
19217
19242
  return targets;
19218
19243
  }
19219
- function renderAgentsMd(m) {
19244
+ function renderAgentsMd(m, opts = {}) {
19220
19245
  const id = m.identity;
19246
+ const hk = harnessInvocation(opts.harnessVersion);
19221
19247
  const L = [];
19222
19248
  L.push(GEN_HEADER(), "");
19223
19249
  L.push(`# ${id.name}`, "");
19224
19250
  if (id.summary) L.push(id.summary, "");
19225
19251
  L.push("## Working agreement (read first)", "");
19226
19252
  L.push(
19227
- "`AGENTS.md`, `CLAUDE.md`, and `.agents/reference.md` are GENERATED from `.agents/manifest.yaml`; `.agents/routing.md` / `.agents/modules.md` are generated when those sections are declared. Do NOT edit those files by hand \u2014 edit the manifest and run `harness-kit sync`. Knowledge is hand-authored; `.agents/hooks/` is managed by `harness-kit install-hooks`.",
19253
+ `Harness CLI: run every \`harness-kit <command>\` here as \`${hk} <command>\` ` + (opts.harnessVersion ? `(version pinned by \`${HARNESS_LOCK_REL}\`; no global install needed).` : `(no global install needed; this repository has no \`${HARNESS_LOCK_REL}\` version pin yet).`),
19254
+ ""
19255
+ );
19256
+ L.push(
19257
+ `\`AGENTS.md\`, \`CLAUDE.md\`, and \`.agents/reference.md\` are GENERATED from \`.agents/manifest.yaml\`; \`.agents/routing.md\` / \`.agents/modules.md\` are generated when those sections are declared. Do NOT edit those files by hand \u2014 edit the manifest and run \`${hk} sync\`. Knowledge is hand-authored; \`.agents/hooks/\` is managed by \`${hk} install-hooks\`.`,
19228
19258
  ""
19229
19259
  );
19230
19260
  L.push("Before you touch code:");
@@ -19235,16 +19265,20 @@ function renderAgentsMd(m) {
19235
19265
  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
19266
  else L.push("2. Read the relevant files before editing. Do NOT full-repo grep and guess.");
19237
19267
  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>`.");
19268
+ L.push(` Prefer \`${hk} task-start\` before editing so committed work stays in the deliver scope.`);
19239
19269
  L.push("");
19240
19270
  const hasImpactMap = (m.modules ?? []).some((mod) => (mod.owns?.length ?? 0) > 0) || !!m.validation;
19241
19271
  L.push("Before you finish:");
19242
- if (hasImpactMap)
19272
+ if (hasImpactMap) {
19273
+ L.push(
19274
+ `3. Run \`${hk} 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.`
19275
+ );
19243
19276
  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."
19277
+ ` Optional: \`${hk} task-start\` before editing so later commits stay in scope; without it, deliver falls back to the current worktree git diff vs HEAD.`
19245
19278
  );
19246
- else
19247
- L.push("3. Run `harness-kit verify`. It enforces the invariants below and classifies anything it cannot check automatically.");
19279
+ } else {
19280
+ L.push(`3. Run \`${hk} deliver\` (or at least \`${hk} verify\`). Do not claim completion without a passing stamp/verify.`);
19281
+ }
19248
19282
  L.push(
19249
19283
  "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
19284
  );
@@ -19296,7 +19330,7 @@ function renderAgentsMd(m) {
19296
19330
  const how = inv.enforcement ? "enforced" : inv.check ? "checked" : "manual";
19297
19331
  L.push(`- ${inv.rule} [${how}]`);
19298
19332
  }
19299
- L.push("", "Run `harness-kit verify` to check the enforceable ones.", "");
19333
+ L.push("", `Run \`${hk} verify\` to check the enforceable ones.`, "");
19300
19334
  }
19301
19335
  L.push("## Knowledge & maps (load on demand)", "");
19302
19336
  if (!m.knowledge?.length || m.knowledge.some((knowledge) => (knowledge.root ?? "agents") === "agents"))
@@ -19307,7 +19341,7 @@ function renderAgentsMd(m) {
19307
19341
  L.push("- Full commands, environment, and registered knowledge catalog: `.agents/reference.md`");
19308
19342
  if (m.routing?.length) L.push("- Change-type routing (read before editing): `.agents/routing.md`");
19309
19343
  if (m.modules?.length) L.push("- Module map + common pitfalls: `.agents/modules.md`");
19310
- if (hasImpactMap) L.push("- Implement -> verify loop (deep guide): run `harness-kit check-loop`");
19344
+ if (hasImpactMap) L.push(`- Implement -> verify loop (deep guide): run \`${hk} check-loop\``);
19311
19345
  L.push("- Tooling adoption log (earn heavier tooling): `.agents/adoption.md`");
19312
19346
  if (m.playbooks?.dir) L.push(`- Task playbooks: \`.agents/${m.playbooks.dir}\``);
19313
19347
  L.push("");
@@ -19424,7 +19458,7 @@ function validPermissionMode(mode) {
19424
19458
  }
19425
19459
  function safeEvidencePath(path) {
19426
19460
  try {
19427
- return safeRelativePath(path, "legacy evidence") === path && !path.startsWith(`${LEGACY_DIR_REL}${import_node_path5.sep}`);
19461
+ return safeRelativePath(path, "legacy evidence") === path && !path.startsWith(`${LEGACY_DIR_REL}${import_node_path6.sep}`);
19428
19462
  } catch {
19429
19463
  return false;
19430
19464
  }
@@ -19434,39 +19468,39 @@ function isErrno2(error, code) {
19434
19468
  }
19435
19469
  function ensureNoSymlinkDirectoryChain(root, directory, label, create) {
19436
19470
  if (!inside2(root, directory)) throw new Error(`${label} parent escapes the repository`);
19437
- const rel = (0, import_node_path5.relative)(root, directory);
19471
+ const rel = (0, import_node_path6.relative)(root, directory);
19438
19472
  let cursor = root;
19439
- for (const component of rel.split(import_node_path5.sep).filter(Boolean)) {
19440
- cursor = (0, import_node_path5.join)(cursor, component);
19473
+ for (const component of rel.split(import_node_path6.sep).filter(Boolean)) {
19474
+ cursor = (0, import_node_path6.join)(cursor, component);
19441
19475
  let stat;
19442
19476
  try {
19443
- stat = (0, import_node_fs5.lstatSync)(cursor);
19477
+ stat = (0, import_node_fs6.lstatSync)(cursor);
19444
19478
  } catch (error) {
19445
19479
  if (!isErrno2(error, "ENOENT")) throw new Error(`cannot inspect ${label} parent ${cursor}: ${errorMessage2(error)}`);
19446
19480
  if (!create) return false;
19447
19481
  try {
19448
- (0, import_node_fs5.mkdirSync)(cursor);
19482
+ (0, import_node_fs6.mkdirSync)(cursor);
19449
19483
  } catch (mkdirError) {
19450
19484
  if (!isErrno2(mkdirError, "EEXIST"))
19451
19485
  throw new Error(`cannot create ${label} parent ${cursor}: ${errorMessage2(mkdirError)}`);
19452
19486
  }
19453
- stat = (0, import_node_fs5.lstatSync)(cursor);
19487
+ stat = (0, import_node_fs6.lstatSync)(cursor);
19454
19488
  }
19455
19489
  if (stat.isSymbolicLink()) throw new Error(`${label} parent must not be a symlink: ${cursor}`);
19456
19490
  if (!stat.isDirectory()) throw new Error(`${label} parent must be a directory: ${cursor}`);
19457
- const resolved = (0, import_node_fs5.realpathSync)(cursor);
19491
+ const resolved = (0, import_node_fs6.realpathSync)(cursor);
19458
19492
  if (!inside2(root, resolved)) throw new Error(`${label} parent resolves outside the repository: ${cursor}`);
19459
19493
  }
19460
19494
  return true;
19461
19495
  }
19462
19496
  function readOptionalRepositoryFile(repoRoot, relativePath, label, afterLstat) {
19463
19497
  const normalized = safeRelativePath(relativePath, label);
19464
- const absolute = (0, import_node_path5.resolve)(repoRoot, normalized);
19498
+ const absolute = (0, import_node_path6.resolve)(repoRoot, normalized);
19465
19499
  if (!inside2(repoRoot, absolute) || absolute === repoRoot) throw new Error(`${label} path escapes the repository`);
19466
- if (!ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path5.dirname)(absolute), label, false)) return null;
19500
+ if (!ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)(absolute), label, false)) return null;
19467
19501
  let before;
19468
19502
  try {
19469
- before = (0, import_node_fs5.lstatSync)(absolute);
19503
+ before = (0, import_node_fs6.lstatSync)(absolute);
19470
19504
  } catch (error) {
19471
19505
  if (isErrno2(error, "ENOENT")) return null;
19472
19506
  throw new Error(`cannot inspect ${label}: ${errorMessage2(error)}`);
@@ -19475,22 +19509,22 @@ function readOptionalRepositoryFile(repoRoot, relativePath, label, afterLstat) {
19475
19509
  afterLstat?.(normalized);
19476
19510
  let fd;
19477
19511
  try {
19478
- fd = (0, import_node_fs5.openSync)(absolute, import_node_fs5.constants.O_RDONLY | import_node_fs5.constants.O_NOFOLLOW);
19512
+ fd = (0, import_node_fs6.openSync)(absolute, import_node_fs6.constants.O_RDONLY | import_node_fs6.constants.O_NOFOLLOW);
19479
19513
  } catch (error) {
19480
19514
  throw new Error(`cannot open ${label} without following links: ${errorMessage2(error)}`);
19481
19515
  }
19482
19516
  try {
19483
- const opened = (0, import_node_fs5.fstatSync)(fd);
19517
+ const opened = (0, import_node_fs6.fstatSync)(fd);
19484
19518
  if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino)
19485
19519
  throw new Error(`${label} changed while it was being inspected: ${relativePath}`);
19486
19520
  return {
19487
- bytes: (0, import_node_fs5.readFileSync)(fd),
19521
+ bytes: (0, import_node_fs6.readFileSync)(fd),
19488
19522
  mode: permissionMode(opened.mode),
19489
19523
  dev: opened.dev,
19490
19524
  ino: opened.ino
19491
19525
  };
19492
19526
  } finally {
19493
- (0, import_node_fs5.closeSync)(fd);
19527
+ (0, import_node_fs6.closeSync)(fd);
19494
19528
  }
19495
19529
  }
19496
19530
  function parseAdoptionIndex(raw) {
@@ -19508,7 +19542,7 @@ function parseAdoptionIndex(raw) {
19508
19542
  throw new Error(`${INDEX_REL} \u683C\u5F0F\u65E0\u6548\uFF1Aentry path \u4E0D\u5B89\u5168\u6216\u91CD\u590D`);
19509
19543
  seen.add(entry.path);
19510
19544
  if (entry.type === "file") {
19511
- const expectedSnapshot = (0, import_node_path5.join)(LEGACY_DIR_REL, snapshotName(entry.path));
19545
+ const expectedSnapshot = (0, import_node_path6.join)(LEGACY_DIR_REL, snapshotName(entry.path));
19512
19546
  if (!/^[a-f0-9]{64}$/.test(entry.sha256 ?? "") || entry.snapshot !== expectedSnapshot || !validPermissionMode(entry.mode))
19513
19547
  throw new Error(`${INDEX_REL} \u683C\u5F0F\u65E0\u6548\uFF1A${entry.path} snapshot/mode/hash \u65E0\u6548`);
19514
19548
  } else if (entry.type === "symlink") {
@@ -19529,15 +19563,15 @@ function readAdoptionIndex(repo) {
19529
19563
  }
19530
19564
  function verifyAdoptionEntry(repo, entry) {
19531
19565
  const root = repositoryRoot2(repo);
19532
- const path = (0, import_node_path5.join)(root, entry.path);
19566
+ const path = (0, import_node_path6.join)(root, entry.path);
19533
19567
  let stat;
19534
19568
  try {
19535
- if (!ensureNoSymlinkDirectoryChain(root, (0, import_node_path5.dirname)(path), `legacy source ${entry.path}`, false)) return false;
19536
- stat = (0, import_node_fs5.lstatSync)(path);
19569
+ if (!ensureNoSymlinkDirectoryChain(root, (0, import_node_path6.dirname)(path), `legacy source ${entry.path}`, false)) return false;
19570
+ stat = (0, import_node_fs6.lstatSync)(path);
19537
19571
  } catch {
19538
19572
  return false;
19539
19573
  }
19540
- if (entry.type === "symlink") return stat.isSymbolicLink() && (0, import_node_fs5.readlinkSync)(path) === entry.linkTarget;
19574
+ if (entry.type === "symlink") return stat.isSymbolicLink() && (0, import_node_fs6.readlinkSync)(path) === entry.linkTarget;
19541
19575
  if (!stat.isFile() || stat.isSymbolicLink() || !entry.sha256 || !entry.snapshot || !validPermissionMode(entry.mode)) return false;
19542
19576
  try {
19543
19577
  const source = readOptionalRepositoryFile(root, entry.path, `legacy source ${entry.path}`);
@@ -19551,22 +19585,22 @@ function snapshotName(path) {
19551
19585
  return path.replaceAll("/", "__") + ".pre-harness";
19552
19586
  }
19553
19587
  function captureEntry(repo, path) {
19554
- const absolute = (0, import_node_path5.join)(repo, path);
19588
+ const absolute = (0, import_node_path6.join)(repo, path);
19555
19589
  let stat;
19556
19590
  try {
19557
- stat = (0, import_node_fs5.lstatSync)(absolute);
19591
+ stat = (0, import_node_fs6.lstatSync)(absolute);
19558
19592
  } catch (error) {
19559
19593
  if (isErrno2(error, "ENOENT")) return { entry: null };
19560
19594
  throw error;
19561
19595
  }
19562
- if (stat.isSymbolicLink()) return { entry: { path, type: "symlink", linkTarget: (0, import_node_fs5.readlinkSync)(absolute) } };
19596
+ if (stat.isSymbolicLink()) return { entry: { path, type: "symlink", linkTarget: (0, import_node_fs6.readlinkSync)(absolute) } };
19563
19597
  if (!stat.isFile()) throw new Error(`\u65E0\u6CD5\u63A5\u7BA1 ${path}\uFF1A\u5B83\u65E2\u4E0D\u662F\u666E\u901A\u6587\u4EF6\u4E5F\u4E0D\u662F\u8F6F\u94FE\u63A5`);
19564
19598
  const source = readOptionalRepositoryFile(repo, path, `legacy source ${path}`);
19565
19599
  if (!source) return { entry: null };
19566
19600
  const content = source.bytes;
19567
19601
  if (content.toString("utf8").startsWith(GENERATED_MARKER)) return { entry: null };
19568
19602
  const mode = source.mode;
19569
- const snapshot = (0, import_node_path5.join)(LEGACY_DIR_REL, snapshotName(path));
19603
+ const snapshot = (0, import_node_path6.join)(LEGACY_DIR_REL, snapshotName(path));
19570
19604
  const existing = readOptionalRepositoryFile(repo, snapshot, `legacy snapshot ${path}`);
19571
19605
  if (existing && (sha256(existing.bytes) !== sha256(content) || existing.mode !== mode))
19572
19606
  throw new Error(`\u5DF2\u6709 legacy snapshot \u5185\u5BB9\u6216 mode \u4E0D\u5339\u914D\uFF0C\u62D2\u7EDD\u8986\u76D6: ${snapshot}`);
@@ -19585,25 +19619,25 @@ function findAgentEntryPaths(repo) {
19585
19619
  maxBuffer: 32 * 1024 * 1024
19586
19620
  });
19587
19621
  for (const path of tracked.split("\0").filter(Boolean)) {
19588
- const normalized = (0, import_node_path5.normalize)(path);
19589
- if (AGENT_ENTRY_NAMES.has((0, import_node_path5.basename)(normalized)) && safeEvidencePath(normalized) && !normalized.startsWith(`.agents${import_node_path5.sep}adoption${import_node_path5.sep}`) && entryExists((0, import_node_path5.join)(repo, normalized))) entries.add(normalized);
19622
+ const normalized = (0, import_node_path6.normalize)(path);
19623
+ if (AGENT_ENTRY_NAMES.has((0, import_node_path6.basename)(normalized)) && safeEvidencePath(normalized) && !normalized.startsWith(`.agents${import_node_path6.sep}adoption${import_node_path6.sep}`) && entryExists((0, import_node_path6.join)(repo, normalized))) entries.add(normalized);
19590
19624
  }
19591
19625
  } catch {
19592
19626
  }
19593
19627
  const walk = (directory, prefix) => {
19594
- const directoryStat = (0, import_node_fs5.lstatSync)(directory);
19595
- if (directoryStat.isSymbolicLink() || !directoryStat.isDirectory() || !inside2(repo, (0, import_node_fs5.realpathSync)(directory)))
19628
+ const directoryStat = (0, import_node_fs6.lstatSync)(directory);
19629
+ if (directoryStat.isSymbolicLink() || !directoryStat.isDirectory() || !inside2(repo, (0, import_node_fs6.realpathSync)(directory)))
19596
19630
  throw new Error(`guidance scan directory is unsafe or outside the repository: ${directory}`);
19597
- for (const item of (0, import_node_fs5.readdirSync)(directory, { withFileTypes: true })) {
19598
- const path = prefix ? (0, import_node_path5.join)(prefix, item.name) : item.name;
19599
- const absolute = (0, import_node_path5.join)(directory, item.name);
19600
- const stat = (0, import_node_fs5.lstatSync)(absolute);
19631
+ for (const item of (0, import_node_fs6.readdirSync)(directory, { withFileTypes: true })) {
19632
+ const path = prefix ? (0, import_node_path6.join)(prefix, item.name) : item.name;
19633
+ const absolute = (0, import_node_path6.join)(directory, item.name);
19634
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19601
19635
  if (stat.isSymbolicLink()) {
19602
19636
  if (AGENT_ENTRY_NAMES.has(item.name)) entries.add(path);
19603
19637
  continue;
19604
19638
  }
19605
19639
  if (stat.isDirectory()) {
19606
- const adoptionEvidence = item.name === "adoption" && (0, import_node_path5.basename)(prefix) === ".agents";
19640
+ const adoptionEvidence = item.name === "adoption" && (0, import_node_path6.basename)(prefix) === ".agents";
19607
19641
  if (ALWAYS_PRUNED_DIRECTORY_NAMES.has(item.name) || adoptionEvidence) continue;
19608
19642
  walk(absolute, path);
19609
19643
  continue;
@@ -19623,35 +19657,35 @@ function installPendingSnapshots(repoRoot, pending) {
19623
19657
  let tempPath = null;
19624
19658
  try {
19625
19659
  for (const snapshot of pending) {
19626
- const absolute = (0, import_node_path5.resolve)(repoRoot, snapshot.relativePath);
19627
- ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path5.dirname)(absolute), `legacy snapshot ${snapshot.relativePath}`, true);
19628
- tempPath = (0, import_node_path5.join)(
19629
- (0, import_node_path5.dirname)(absolute),
19630
- `.${(0, import_node_path5.basename)(absolute)}.harness-kit-adoption-${process.pid}-${(0, import_node_crypto4.randomUUID)()}.tmp`
19660
+ const absolute = (0, import_node_path6.resolve)(repoRoot, snapshot.relativePath);
19661
+ ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)(absolute), `legacy snapshot ${snapshot.relativePath}`, true);
19662
+ tempPath = (0, import_node_path6.join)(
19663
+ (0, import_node_path6.dirname)(absolute),
19664
+ `.${(0, import_node_path6.basename)(absolute)}.harness-kit-adoption-${process.pid}-${(0, import_node_crypto4.randomUUID)()}.tmp`
19631
19665
  );
19632
- const fd = (0, import_node_fs5.openSync)(
19666
+ const fd = (0, import_node_fs6.openSync)(
19633
19667
  tempPath,
19634
- import_node_fs5.constants.O_WRONLY | import_node_fs5.constants.O_CREAT | import_node_fs5.constants.O_EXCL | import_node_fs5.constants.O_NOFOLLOW,
19668
+ import_node_fs6.constants.O_WRONLY | import_node_fs6.constants.O_CREAT | import_node_fs6.constants.O_EXCL | import_node_fs6.constants.O_NOFOLLOW,
19635
19669
  snapshot.mode & 511
19636
19670
  );
19637
19671
  try {
19638
- (0, import_node_fs5.writeFileSync)(fd, snapshot.bytes);
19639
- (0, import_node_fs5.fchmodSync)(fd, snapshot.mode);
19640
- const stat = (0, import_node_fs5.fstatSync)(fd);
19672
+ (0, import_node_fs6.writeFileSync)(fd, snapshot.bytes);
19673
+ (0, import_node_fs6.fchmodSync)(fd, snapshot.mode);
19674
+ const stat = (0, import_node_fs6.fstatSync)(fd);
19641
19675
  if (!stat.isFile()) throw new Error(`staged legacy snapshot is not a regular file: ${snapshot.relativePath}`);
19642
19676
  } finally {
19643
- (0, import_node_fs5.closeSync)(fd);
19677
+ (0, import_node_fs6.closeSync)(fd);
19644
19678
  }
19645
- (0, import_node_fs5.linkSync)(tempPath, absolute);
19679
+ (0, import_node_fs6.linkSync)(tempPath, absolute);
19646
19680
  installed.push({ absolutePath: absolute });
19647
- (0, import_node_fs5.unlinkSync)(tempPath);
19681
+ (0, import_node_fs6.unlinkSync)(tempPath);
19648
19682
  tempPath = null;
19649
19683
  }
19650
19684
  return installed;
19651
19685
  } catch (error) {
19652
19686
  if (tempPath) {
19653
19687
  try {
19654
- (0, import_node_fs5.unlinkSync)(tempPath);
19688
+ (0, import_node_fs6.unlinkSync)(tempPath);
19655
19689
  } catch (cleanupError) {
19656
19690
  if (!isErrno2(cleanupError, "ENOENT")) {
19657
19691
  }
@@ -19662,7 +19696,7 @@ function installPendingSnapshots(repoRoot, pending) {
19662
19696
  }
19663
19697
  function entryExists(path) {
19664
19698
  try {
19665
- (0, import_node_fs5.lstatSync)(path);
19699
+ (0, import_node_fs6.lstatSync)(path);
19666
19700
  return true;
19667
19701
  } catch {
19668
19702
  return false;
@@ -19672,8 +19706,8 @@ function textCanContainReferences(bytes) {
19672
19706
  return !bytes.includes(0);
19673
19707
  }
19674
19708
  function isLegacyEntry(repoRoot, path, testHooks) {
19675
- const absolute = (0, import_node_path5.join)(repoRoot, path);
19676
- const stat = (0, import_node_fs5.lstatSync)(absolute);
19709
+ const absolute = (0, import_node_path6.join)(repoRoot, path);
19710
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19677
19711
  if (stat.isSymbolicLink() || !stat.isFile()) return true;
19678
19712
  const source = readOptionalRepositoryFile(
19679
19713
  repoRoot,
@@ -19685,7 +19719,7 @@ function isLegacyEntry(repoRoot, path, testHooks) {
19685
19719
  return !source.bytes.toString("utf8").startsWith(GENERATED_MARKER);
19686
19720
  }
19687
19721
  function documentLike(path) {
19688
- return AGENT_ENTRY_NAMES.has((0, import_node_path5.basename)(path)) || DOCUMENT_EXTENSIONS.has((0, import_node_path5.extname)(path).toLowerCase());
19722
+ return AGENT_ENTRY_NAMES.has((0, import_node_path6.basename)(path)) || DOCUMENT_EXTENSIONS.has((0, import_node_path6.extname)(path).toLowerCase());
19689
19723
  }
19690
19724
  function cleanReference(raw) {
19691
19725
  let value = raw.trim();
@@ -19719,15 +19753,15 @@ function explicitReferences(content) {
19719
19753
  return [...references];
19720
19754
  }
19721
19755
  function resolveGuidanceReference(repoRoot, sourcePath, reference, testHooks) {
19722
- const candidates = reference.startsWith("/") ? [(0, import_node_path5.resolve)(repoRoot, reference.slice(1))] : [(0, import_node_path5.resolve)(repoRoot, (0, import_node_path5.dirname)(sourcePath), reference), (0, import_node_path5.resolve)(repoRoot, reference)];
19756
+ const candidates = reference.startsWith("/") ? [(0, import_node_path6.resolve)(repoRoot, reference.slice(1))] : [(0, import_node_path6.resolve)(repoRoot, (0, import_node_path6.dirname)(sourcePath), reference), (0, import_node_path6.resolve)(repoRoot, reference)];
19723
19757
  for (const absolute of candidates) {
19724
19758
  if (!inside2(repoRoot, absolute) || !entryExists(absolute)) continue;
19725
19759
  let stat;
19726
19760
  try {
19727
- const path2 = (0, import_node_path5.relative)(repoRoot, absolute);
19728
- if (!safeEvidencePath(path2) || !ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path5.dirname)(absolute), `guidance ${path2}`, false))
19761
+ const path2 = (0, import_node_path6.relative)(repoRoot, absolute);
19762
+ if (!safeEvidencePath(path2) || !ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)(absolute), `guidance ${path2}`, false))
19729
19763
  continue;
19730
- stat = (0, import_node_fs5.lstatSync)(absolute);
19764
+ stat = (0, import_node_fs6.lstatSync)(absolute);
19731
19765
  if (!stat.isSymbolicLink() && !stat.isFile()) continue;
19732
19766
  if (stat.isFile()) {
19733
19767
  const source = readOptionalRepositoryFile(
@@ -19741,19 +19775,19 @@ function resolveGuidanceReference(repoRoot, sourcePath, reference, testHooks) {
19741
19775
  } catch {
19742
19776
  continue;
19743
19777
  }
19744
- const path = (0, import_node_path5.relative)(repoRoot, absolute);
19778
+ const path = (0, import_node_path6.relative)(repoRoot, absolute);
19745
19779
  if (safeEvidencePath(path)) return path;
19746
19780
  }
19747
19781
  return null;
19748
19782
  }
19749
19783
  function resolveGuidanceSymlinkTarget(repoRoot, sourcePath, linkTarget, testHooks) {
19750
- const absolute = (0, import_node_path5.isAbsolute)(linkTarget) ? (0, import_node_path5.resolve)(linkTarget) : (0, import_node_path5.resolve)(repoRoot, (0, import_node_path5.dirname)(sourcePath), linkTarget);
19784
+ const absolute = (0, import_node_path6.isAbsolute)(linkTarget) ? (0, import_node_path6.resolve)(linkTarget) : (0, import_node_path6.resolve)(repoRoot, (0, import_node_path6.dirname)(sourcePath), linkTarget);
19751
19785
  if (!inside2(repoRoot, absolute) || !entryExists(absolute)) return null;
19752
19786
  try {
19753
- const path2 = (0, import_node_path5.relative)(repoRoot, absolute);
19754
- if (!safeEvidencePath(path2) || !ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path5.dirname)(absolute), `guidance ${path2}`, false))
19787
+ const path2 = (0, import_node_path6.relative)(repoRoot, absolute);
19788
+ if (!safeEvidencePath(path2) || !ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)(absolute), `guidance ${path2}`, false))
19755
19789
  return null;
19756
- const stat = (0, import_node_fs5.lstatSync)(absolute);
19790
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19757
19791
  if (!stat.isSymbolicLink() && !stat.isFile()) return null;
19758
19792
  if (stat.isFile()) {
19759
19793
  const source = readOptionalRepositoryFile(
@@ -19767,17 +19801,17 @@ function resolveGuidanceSymlinkTarget(repoRoot, sourcePath, linkTarget, testHook
19767
19801
  } catch {
19768
19802
  return null;
19769
19803
  }
19770
- const path = (0, import_node_path5.relative)(repoRoot, absolute);
19804
+ const path = (0, import_node_path6.relative)(repoRoot, absolute);
19771
19805
  return safeEvidencePath(path) ? path : null;
19772
19806
  }
19773
19807
  function liveGuidanceEvidence(repoRoot, path, testHooks) {
19774
- const absolute = (0, import_node_path5.join)(repoRoot, path);
19775
- if (!ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path5.dirname)(absolute), `guidance ${path}`, false))
19808
+ const absolute = (0, import_node_path6.join)(repoRoot, path);
19809
+ if (!ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)(absolute), `guidance ${path}`, false))
19776
19810
  throw new Error(`guidance disappeared while it was being inspected: ${path}`);
19777
- const stat = (0, import_node_fs5.lstatSync)(absolute);
19811
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19778
19812
  const mode = permissionMode(stat.mode);
19779
19813
  if (stat.isSymbolicLink()) {
19780
- const linkTarget = (0, import_node_fs5.readlinkSync)(absolute);
19814
+ const linkTarget = (0, import_node_fs6.readlinkSync)(absolute);
19781
19815
  if (!resolveGuidanceSymlinkTarget(repoRoot, path, linkTarget, testHooks))
19782
19816
  throw new Error(`guidance symlink cannot be resolved to a safe in-repo text file: ${path}`);
19783
19817
  return { path, type: "symlink", mode, linkTarget };
@@ -19798,13 +19832,13 @@ function discoverGuidance(repo, testHooks = {}) {
19798
19832
  const all = findAgentEntryPaths(root);
19799
19833
  const entryPaths = /* @__PURE__ */ new Set();
19800
19834
  for (const path of all) {
19801
- if (!AGENT_ENTRY_NAMES.has((0, import_node_path5.basename)(path)) || !safeEvidencePath(path)) continue;
19802
- const absolute = (0, import_node_path5.join)(root, path);
19835
+ if (!AGENT_ENTRY_NAMES.has((0, import_node_path6.basename)(path)) || !safeEvidencePath(path)) continue;
19836
+ const absolute = (0, import_node_path6.join)(root, path);
19803
19837
  if (entryExists(absolute) && isLegacyEntry(root, path, testHooks)) entryPaths.add(path);
19804
19838
  }
19805
19839
  for (const path of MANAGED_ENTRY_PATHS) {
19806
- if (!AGENT_ENTRY_NAMES.has((0, import_node_path5.basename)(path))) continue;
19807
- const absolute = (0, import_node_path5.join)(root, path);
19840
+ if (!AGENT_ENTRY_NAMES.has((0, import_node_path6.basename)(path))) continue;
19841
+ const absolute = (0, import_node_path6.join)(root, path);
19808
19842
  if (entryExists(absolute) && isLegacyEntry(root, path, testHooks)) entryPaths.add(path);
19809
19843
  }
19810
19844
  const evidence = new Set([...entryPaths].filter((path) => !MANAGED_ENTRY_PATHS.includes(path)));
@@ -19815,12 +19849,12 @@ function discoverGuidance(repo, testHooks = {}) {
19815
19849
  const sourcePath = queue.shift();
19816
19850
  if (reviewed.has(sourcePath)) continue;
19817
19851
  reviewed.add(sourcePath);
19818
- const absolute = (0, import_node_path5.join)(root, sourcePath);
19819
- if (!ensureNoSymlinkDirectoryChain(root, (0, import_node_path5.dirname)(absolute), `guidance ${sourcePath}`, false))
19852
+ const absolute = (0, import_node_path6.join)(root, sourcePath);
19853
+ if (!ensureNoSymlinkDirectoryChain(root, (0, import_node_path6.dirname)(absolute), `guidance ${sourcePath}`, false))
19820
19854
  throw new Error(`guidance disappeared while it was being inspected: ${sourcePath}`);
19821
- const stat = (0, import_node_fs5.lstatSync)(absolute);
19855
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19822
19856
  if (stat.isSymbolicLink()) {
19823
- const target = resolveGuidanceSymlinkTarget(root, sourcePath, (0, import_node_fs5.readlinkSync)(absolute), testHooks);
19857
+ const target = resolveGuidanceSymlinkTarget(root, sourcePath, (0, import_node_fs6.readlinkSync)(absolute), testHooks);
19824
19858
  if (!target) throw new Error(`guidance symlink cannot be resolved to a safe in-repo text file: ${sourcePath}`);
19825
19859
  if (!MANAGED_ENTRY_PATHS.includes(target)) evidence.add(target);
19826
19860
  if (!reviewed.has(target) && !queued.has(target)) {
@@ -19898,17 +19932,17 @@ function errorMessage2(error) {
19898
19932
  return error instanceof Error ? error.message : String(error);
19899
19933
  }
19900
19934
  function inside2(root, candidate) {
19901
- const rel = (0, import_node_path5.relative)(root, candidate);
19902
- return rel === "" || rel !== ".." && !rel.startsWith(`..${import_node_path5.sep}`) && !(0, import_node_path5.isAbsolute)(rel);
19935
+ const rel = (0, import_node_path6.relative)(root, candidate);
19936
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${import_node_path6.sep}`) && !(0, import_node_path6.isAbsolute)(rel);
19903
19937
  }
19904
19938
  function repositoryRoot2(repo) {
19905
19939
  let root;
19906
19940
  try {
19907
- root = (0, import_node_fs5.realpathSync)(repo);
19941
+ root = (0, import_node_fs6.realpathSync)(repo);
19908
19942
  } catch (error) {
19909
19943
  throw new Error(`cannot resolve repository root ${repo}: ${errorMessage2(error)}`);
19910
19944
  }
19911
- if (!(0, import_node_fs5.statSync)(root).isDirectory()) throw new Error(`repository root is not a directory: ${repo}`);
19945
+ if (!(0, import_node_fs6.statSync)(root).isDirectory()) throw new Error(`repository root is not a directory: ${repo}`);
19912
19946
  return root;
19913
19947
  }
19914
19948
  function canonicalJson(value) {
@@ -19924,102 +19958,102 @@ function isSha256(value) {
19924
19958
  return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
19925
19959
  }
19926
19960
  function safeRelativePath(path, label) {
19927
- if (!path || path.includes("\0") || (0, import_node_path5.isAbsolute)(path)) throw new Error(`${label} path is unsafe: ${path}`);
19928
- const normalized = (0, import_node_path5.normalize)(path);
19929
- if (normalized === "." || normalized === ".." || normalized.startsWith(`..${import_node_path5.sep}`))
19961
+ if (!path || path.includes("\0") || (0, import_node_path6.isAbsolute)(path)) throw new Error(`${label} path is unsafe: ${path}`);
19962
+ const normalized = (0, import_node_path6.normalize)(path);
19963
+ if (normalized === "." || normalized === ".." || normalized.startsWith(`..${import_node_path6.sep}`))
19930
19964
  throw new Error(`${label} path escapes its bundle: ${path}`);
19931
19965
  return normalized;
19932
19966
  }
19933
19967
  function existingAncestor(path) {
19934
19968
  const suffix = [];
19935
19969
  let cursor = path;
19936
- while (!(0, import_node_fs5.existsSync)(cursor)) {
19937
- const parent = (0, import_node_path5.dirname)(cursor);
19970
+ while (!(0, import_node_fs6.existsSync)(cursor)) {
19971
+ const parent = (0, import_node_path6.dirname)(cursor);
19938
19972
  if (parent === cursor) throw new Error(`cannot resolve destination parent: ${path}`);
19939
- suffix.unshift(cursor.slice(parent.length + (parent.endsWith(import_node_path5.sep) ? 0 : 1)));
19973
+ suffix.unshift(cursor.slice(parent.length + (parent.endsWith(import_node_path6.sep) ? 0 : 1)));
19940
19974
  cursor = parent;
19941
19975
  }
19942
19976
  return { ancestor: cursor, suffix };
19943
19977
  }
19944
19978
  function prospectiveRealPath(path) {
19945
19979
  const { ancestor, suffix } = existingAncestor(path);
19946
- const stat = (0, import_node_fs5.lstatSync)(ancestor);
19980
+ const stat = (0, import_node_fs6.lstatSync)(ancestor);
19947
19981
  if (!stat.isDirectory() && !stat.isSymbolicLink()) throw new Error(`destination parent is not a directory: ${ancestor}`);
19948
- const resolvedAncestor = (0, import_node_fs5.realpathSync)(ancestor);
19949
- if (!(0, import_node_fs5.statSync)(resolvedAncestor).isDirectory()) throw new Error(`destination parent is not a directory: ${ancestor}`);
19950
- return (0, import_node_path5.resolve)(resolvedAncestor, ...suffix);
19982
+ const resolvedAncestor = (0, import_node_fs6.realpathSync)(ancestor);
19983
+ if (!(0, import_node_fs6.statSync)(resolvedAncestor).isDirectory()) throw new Error(`destination parent is not a directory: ${ancestor}`);
19984
+ return (0, import_node_path6.resolve)(resolvedAncestor, ...suffix);
19951
19985
  }
19952
19986
  function assertExternalPath(repoRoot, requestedPath, label) {
19953
- const absolute = (0, import_node_path5.resolve)(requestedPath);
19954
- const resolved = (0, import_node_fs5.existsSync)(absolute) ? (0, import_node_fs5.realpathSync)(absolute) : prospectiveRealPath(absolute);
19987
+ const absolute = (0, import_node_path6.resolve)(requestedPath);
19988
+ const resolved = (0, import_node_fs6.existsSync)(absolute) ? (0, import_node_fs6.realpathSync)(absolute) : prospectiveRealPath(absolute);
19955
19989
  if (inside2(repoRoot, resolved)) throw new Error(`${label} must be outside the repository: ${absolute}`);
19956
19990
  return resolved;
19957
19991
  }
19958
19992
  function prepareEmptyExternalDirectory(repoRoot, outputDir) {
19959
- const absolute = (0, import_node_path5.resolve)(outputDir);
19960
- if ((0, import_node_fs5.existsSync)(absolute)) {
19961
- const stat2 = (0, import_node_fs5.lstatSync)(absolute);
19993
+ const absolute = (0, import_node_path6.resolve)(outputDir);
19994
+ if ((0, import_node_fs6.existsSync)(absolute)) {
19995
+ const stat2 = (0, import_node_fs6.lstatSync)(absolute);
19962
19996
  if (stat2.isSymbolicLink()) throw new Error(`candidate output must not be a symlink: ${absolute}`);
19963
19997
  if (!stat2.isDirectory()) throw new Error(`candidate output must be a directory: ${absolute}`);
19964
- if ((0, import_node_fs5.readdirSync)(absolute).length > 0) throw new Error(`candidate output must be empty: ${absolute}`);
19998
+ if ((0, import_node_fs6.readdirSync)(absolute).length > 0) throw new Error(`candidate output must be empty: ${absolute}`);
19965
19999
  }
19966
20000
  const expected = assertExternalPath(repoRoot, absolute, "candidate output");
19967
- if (!(0, import_node_fs5.existsSync)(absolute)) (0, import_node_fs5.mkdirSync)(absolute, { recursive: true, mode: 448 });
19968
- const stat = (0, import_node_fs5.lstatSync)(absolute);
20001
+ if (!(0, import_node_fs6.existsSync)(absolute)) (0, import_node_fs6.mkdirSync)(absolute, { recursive: true, mode: 448 });
20002
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19969
20003
  if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`candidate output is unsafe: ${absolute}`);
19970
- const actual = (0, import_node_fs5.realpathSync)(absolute);
20004
+ const actual = (0, import_node_fs6.realpathSync)(absolute);
19971
20005
  if (actual !== expected || inside2(repoRoot, actual)) throw new Error(`candidate output changed or escaped: ${absolute}`);
19972
- (0, import_node_fs5.chmodSync)(actual, 448);
20006
+ (0, import_node_fs6.chmodSync)(actual, 448);
19973
20007
  return actual;
19974
20008
  }
19975
20009
  function ensurePrivateDirectory(bundleRoot, directory) {
19976
- const rel = (0, import_node_path5.relative)(bundleRoot, directory);
19977
- if (rel === ".." || rel.startsWith(`..${import_node_path5.sep}`) || (0, import_node_path5.isAbsolute)(rel)) throw new Error(`bundle directory escapes: ${directory}`);
20010
+ const rel = (0, import_node_path6.relative)(bundleRoot, directory);
20011
+ if (rel === ".." || rel.startsWith(`..${import_node_path6.sep}`) || (0, import_node_path6.isAbsolute)(rel)) throw new Error(`bundle directory escapes: ${directory}`);
19978
20012
  let cursor = bundleRoot;
19979
- for (const component of rel.split(import_node_path5.sep).filter(Boolean)) {
19980
- cursor = (0, import_node_path5.join)(cursor, component);
19981
- if (!(0, import_node_fs5.existsSync)(cursor)) (0, import_node_fs5.mkdirSync)(cursor, { mode: 448 });
19982
- const stat = (0, import_node_fs5.lstatSync)(cursor);
20013
+ for (const component of rel.split(import_node_path6.sep).filter(Boolean)) {
20014
+ cursor = (0, import_node_path6.join)(cursor, component);
20015
+ if (!(0, import_node_fs6.existsSync)(cursor)) (0, import_node_fs6.mkdirSync)(cursor, { mode: 448 });
20016
+ const stat = (0, import_node_fs6.lstatSync)(cursor);
19983
20017
  if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`bundle directory is unsafe: ${cursor}`);
19984
- (0, import_node_fs5.chmodSync)(cursor, 448);
20018
+ (0, import_node_fs6.chmodSync)(cursor, 448);
19985
20019
  }
19986
20020
  }
19987
20021
  function bundleFilePath(bundleRoot, relativePath) {
19988
20022
  const normalized = safeRelativePath(relativePath, "bundle artifact");
19989
- const absolute = (0, import_node_path5.resolve)(bundleRoot, normalized);
20023
+ const absolute = (0, import_node_path6.resolve)(bundleRoot, normalized);
19990
20024
  if (!inside2(bundleRoot, absolute) || absolute === bundleRoot) throw new Error(`bundle artifact escapes: ${relativePath}`);
19991
20025
  return absolute;
19992
20026
  }
19993
20027
  function privateWriteBundleFile(bundleRoot, relativePath, content) {
19994
20028
  const absolute = bundleFilePath(bundleRoot, relativePath);
19995
- ensurePrivateDirectory(bundleRoot, (0, import_node_path5.dirname)(absolute));
19996
- (0, import_node_fs5.writeFileSync)(absolute, content, { flag: "wx", mode: 384 });
19997
- (0, import_node_fs5.chmodSync)(absolute, 384);
20029
+ ensurePrivateDirectory(bundleRoot, (0, import_node_path6.dirname)(absolute));
20030
+ (0, import_node_fs6.writeFileSync)(absolute, content, { flag: "wx", mode: 384 });
20031
+ (0, import_node_fs6.chmodSync)(absolute, 384);
19998
20032
  return absolute;
19999
20033
  }
20000
20034
  function readRegularFile(path, label) {
20001
20035
  let stat;
20002
20036
  try {
20003
- stat = (0, import_node_fs5.lstatSync)(path);
20037
+ stat = (0, import_node_fs6.lstatSync)(path);
20004
20038
  } catch (error) {
20005
20039
  throw new Error(`${label} is missing or unreadable at ${path}: ${errorMessage2(error)}`);
20006
20040
  }
20007
20041
  if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`${label} must be a regular file: ${path}`);
20008
- const fd = (0, import_node_fs5.openSync)(path, import_node_fs5.constants.O_RDONLY | import_node_fs5.constants.O_NOFOLLOW);
20042
+ const fd = (0, import_node_fs6.openSync)(path, import_node_fs6.constants.O_RDONLY | import_node_fs6.constants.O_NOFOLLOW);
20009
20043
  try {
20010
- if (!(0, import_node_fs5.fstatSync)(fd).isFile()) throw new Error(`${label} must be a regular file: ${path}`);
20011
- return (0, import_node_fs5.readFileSync)(fd);
20044
+ if (!(0, import_node_fs6.fstatSync)(fd).isFile()) throw new Error(`${label} must be a regular file: ${path}`);
20045
+ return (0, import_node_fs6.readFileSync)(fd);
20012
20046
  } finally {
20013
- (0, import_node_fs5.closeSync)(fd);
20047
+ (0, import_node_fs6.closeSync)(fd);
20014
20048
  }
20015
20049
  }
20016
20050
  function readBundleFile(bundleRoot, relativePath, label) {
20017
20051
  const absolute = bundleFilePath(bundleRoot, relativePath);
20018
- const parentRel = (0, import_node_path5.relative)(bundleRoot, (0, import_node_path5.dirname)(absolute));
20052
+ const parentRel = (0, import_node_path6.relative)(bundleRoot, (0, import_node_path6.dirname)(absolute));
20019
20053
  let cursor = bundleRoot;
20020
- for (const component of parentRel.split(import_node_path5.sep).filter(Boolean)) {
20021
- cursor = (0, import_node_path5.join)(cursor, component);
20022
- const stat = (0, import_node_fs5.lstatSync)(cursor);
20054
+ for (const component of parentRel.split(import_node_path6.sep).filter(Boolean)) {
20055
+ cursor = (0, import_node_path6.join)(cursor, component);
20056
+ const stat = (0, import_node_fs6.lstatSync)(cursor);
20023
20057
  if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`${label} parent is unsafe: ${cursor}`);
20024
20058
  }
20025
20059
  return readRegularFile(absolute, label);
@@ -20035,15 +20069,15 @@ function parseJsonRecord(bytes, label) {
20035
20069
  return value;
20036
20070
  }
20037
20071
  function readLiveIndexBytes(repoRoot) {
20038
- const bytes = readRegularFile((0, import_node_path5.join)(repoRoot, INDEX_REL), "legacy adoption index");
20072
+ const bytes = readRegularFile((0, import_node_path6.join)(repoRoot, INDEX_REL), "legacy adoption index");
20039
20073
  if (!readAdoptionIndex(repoRoot)) throw new Error(`${INDEX_REL} is required before preparing an adoption candidate`);
20040
20074
  return bytes;
20041
20075
  }
20042
20076
  function legacyEvidenceArtifact(entry) {
20043
- return entry.type === "file" ? (0, import_node_path5.join)("legacy", snapshotName(entry.path)) : (0, import_node_path5.join)("legacy", `${sha256(entry.path)}.symlink.json`);
20077
+ return entry.type === "file" ? (0, import_node_path6.join)("legacy", snapshotName(entry.path)) : (0, import_node_path6.join)("legacy", `${sha256(entry.path)}.symlink.json`);
20044
20078
  }
20045
20079
  function guidanceEvidenceArtifact(evidence) {
20046
- return (0, import_node_path5.join)("guidance", `${sha256(evidence.path)}.${evidence.type === "file" ? "document" : "symlink.json"}`);
20080
+ return (0, import_node_path6.join)("guidance", `${sha256(evidence.path)}.${evidence.type === "file" ? "document" : "symlink.json"}`);
20047
20081
  }
20048
20082
  function guidanceEvidenceBytes(evidence) {
20049
20083
  if (evidence.type === "file") return evidence.bytes;
@@ -20110,11 +20144,11 @@ function validateCandidateMetadata(value) {
20110
20144
  return metadata;
20111
20145
  }
20112
20146
  function readCandidateBundle(repoRoot, candidateDir) {
20113
- const requested = (0, import_node_path5.resolve)(candidateDir);
20114
- if (!(0, import_node_fs5.existsSync)(requested)) throw new Error(`candidate bundle is missing: ${requested}`);
20115
- const stat = (0, import_node_fs5.lstatSync)(requested);
20147
+ const requested = (0, import_node_path6.resolve)(candidateDir);
20148
+ if (!(0, import_node_fs6.existsSync)(requested)) throw new Error(`candidate bundle is missing: ${requested}`);
20149
+ const stat = (0, import_node_fs6.lstatSync)(requested);
20116
20150
  if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`candidate bundle must be a regular directory: ${requested}`);
20117
- const root = (0, import_node_fs5.realpathSync)(requested);
20151
+ const root = (0, import_node_fs6.realpathSync)(requested);
20118
20152
  if (inside2(repoRoot, root)) throw new Error(`candidate bundle must be outside the repository: ${requested}`);
20119
20153
  const metadata = validateCandidateMetadata(parseJsonRecord(readBundleFile(root, CANDIDATE_METADATA, "candidate metadata"), "candidate metadata"));
20120
20154
  const artifacts = [
@@ -20145,17 +20179,17 @@ function prepareAdoptionCandidate(repo, outputDir, testHooks = {}) {
20145
20179
  if (invalidLegacy) throw new Error(`legacy evidence is stale for ${invalidLegacy.path}; prepare refused`);
20146
20180
  const liveGuidance = discoverGuidance(repoRoot, testHooks);
20147
20181
  const root = prepareEmptyExternalDirectory(repoRoot, outputDir);
20148
- const manifestBytes = readRegularFile((0, import_node_path5.join)(repoRoot, MANIFEST_REL), "manifest");
20182
+ const manifestBytes = readRegularFile((0, import_node_path6.join)(repoRoot, MANIFEST_REL), "manifest");
20149
20183
  const indexBytes = readLiveIndexBytes(repoRoot);
20150
- const manifestArtifact = (0, import_node_path5.join)("source", "manifest.yaml");
20151
- const indexArtifact = (0, import_node_path5.join)("source", "legacy-index.json");
20184
+ const manifestArtifact = (0, import_node_path6.join)("source", "manifest.yaml");
20185
+ const indexArtifact = (0, import_node_path6.join)("source", "legacy-index.json");
20152
20186
  privateWriteBundleFile(root, manifestArtifact, manifestBytes);
20153
20187
  privateWriteBundleFile(root, indexArtifact, indexBytes);
20154
20188
  const legacy = [];
20155
20189
  for (const entry of index.entries) {
20156
20190
  const artifact = legacyEvidenceArtifact(entry);
20157
20191
  if (entry.type === "file") {
20158
- const snapshot = readRegularFile((0, import_node_path5.join)(repoRoot, entry.snapshot), `legacy snapshot ${entry.path}`);
20192
+ const snapshot = readRegularFile((0, import_node_path6.join)(repoRoot, entry.snapshot), `legacy snapshot ${entry.path}`);
20159
20193
  privateWriteBundleFile(root, artifact, snapshot);
20160
20194
  legacy.push({
20161
20195
  path: entry.path,
@@ -20192,8 +20226,8 @@ function prepareAdoptionCandidate(repo, outputDir, testHooks = {}) {
20192
20226
  });
20193
20227
  }
20194
20228
  const targets = [];
20195
- for (const [path, content] of renderTargets(manifest)) {
20196
- const artifact = (0, import_node_path5.join)("generated", path);
20229
+ for (const [path, content] of renderTargets(manifest, { harnessVersion: lockedHarnessVersion(repoRoot) })) {
20230
+ const artifact = (0, import_node_path6.join)("generated", path);
20197
20231
  const bytes = Buffer.from(content, "utf8");
20198
20232
  privateWriteBundleFile(root, artifact, bytes);
20199
20233
  targets.push({ path, artifact, sha256: sha256(bytes) });
@@ -20215,15 +20249,15 @@ function prepareAdoptionCandidate(repo, outputDir, testHooks = {}) {
20215
20249
  return metadata;
20216
20250
  }
20217
20251
  function externalReceiptPath(repoRoot, candidateRoot, requested) {
20218
- const absolute = (0, import_node_path5.resolve)(requested ?? (0, import_node_path5.join)(candidateRoot, RECEIPT_DEFAULT));
20219
- const parent = (0, import_node_path5.dirname)(absolute);
20220
- if (!(0, import_node_fs5.existsSync)(parent)) throw new Error(`receipt parent must already exist: ${parent}`);
20221
- const parentStat = (0, import_node_fs5.lstatSync)(parent);
20252
+ const absolute = (0, import_node_path6.resolve)(requested ?? (0, import_node_path6.join)(candidateRoot, RECEIPT_DEFAULT));
20253
+ const parent = (0, import_node_path6.dirname)(absolute);
20254
+ if (!(0, import_node_fs6.existsSync)(parent)) throw new Error(`receipt parent must already exist: ${parent}`);
20255
+ const parentStat = (0, import_node_fs6.lstatSync)(parent);
20222
20256
  if (parentStat.isSymbolicLink() || !parentStat.isDirectory()) throw new Error(`receipt parent is unsafe: ${parent}`);
20223
- const resolvedParent = (0, import_node_fs5.realpathSync)(parent);
20224
- const resolved = (0, import_node_path5.join)(resolvedParent, (0, import_node_path5.relative)(parent, absolute));
20257
+ const resolvedParent = (0, import_node_fs6.realpathSync)(parent);
20258
+ const resolved = (0, import_node_path6.join)(resolvedParent, (0, import_node_path6.relative)(parent, absolute));
20225
20259
  if (inside2(repoRoot, resolved)) throw new Error(`receipt must be outside the repository: ${absolute}`);
20226
- if ((0, import_node_fs5.existsSync)(absolute)) throw new Error(`receipt already exists: ${absolute}`);
20260
+ if ((0, import_node_fs6.existsSync)(absolute)) throw new Error(`receipt already exists: ${absolute}`);
20227
20261
  return resolved;
20228
20262
  }
20229
20263
  function recordAdoptionAudit(repo, candidateDir, options) {
@@ -20232,9 +20266,9 @@ function recordAdoptionAudit(repo, candidateDir, options) {
20232
20266
  const reason = options.reason?.trim();
20233
20267
  if (!reason) throw new Error("audit reason must not be empty");
20234
20268
  const candidate = readCandidateBundle(repoRoot, candidateDir);
20235
- const reportRequested = (0, import_node_path5.resolve)(options.reportPath);
20269
+ const reportRequested = (0, import_node_path6.resolve)(options.reportPath);
20236
20270
  const reportBytes = readRegularFile(reportRequested, "audit report");
20237
- const reportPath = (0, import_node_fs5.realpathSync)(reportRequested);
20271
+ const reportPath = (0, import_node_fs6.realpathSync)(reportRequested);
20238
20272
  const receiptPath = externalReceiptPath(repoRoot, candidate.root, options.receiptPath);
20239
20273
  const receipt = {
20240
20274
  schema: ADOPTION_RECEIPT_SCHEMA,
@@ -20247,20 +20281,20 @@ function recordAdoptionAudit(repo, candidateDir, options) {
20247
20281
  assurance: "declared",
20248
20282
  independence: "unverified"
20249
20283
  };
20250
- (0, import_node_fs5.writeFileSync)(receiptPath, canonicalJson(receipt) + "\n", { flag: "wx", mode: 384 });
20251
- (0, import_node_fs5.chmodSync)(receiptPath, 384);
20284
+ (0, import_node_fs6.writeFileSync)(receiptPath, canonicalJson(receipt) + "\n", { flag: "wx", mode: 384 });
20285
+ (0, import_node_fs6.chmodSync)(receiptPath, 384);
20252
20286
  return { receipt, receiptPath };
20253
20287
  }
20254
20288
  function readReceipt(repoRoot, receiptPath) {
20255
- const requested = (0, import_node_path5.resolve)(receiptPath);
20289
+ const requested = (0, import_node_path6.resolve)(receiptPath);
20256
20290
  const resolved = assertExternalPath(repoRoot, requested, "receipt");
20257
- if (resolved !== (0, import_node_fs5.realpathSync)(requested)) throw new Error(`receipt path changed: ${requested}`);
20291
+ if (resolved !== (0, import_node_fs6.realpathSync)(requested)) throw new Error(`receipt path changed: ${requested}`);
20258
20292
  const value = parseJsonRecord(readRegularFile(requested, "adoption audit receipt"), "adoption audit receipt");
20259
20293
  if (value.schema !== ADOPTION_RECEIPT_SCHEMA || !isSha256(value.candidateHash) || typeof value.candidatePath !== "string" || value.verdict !== "pass" && value.verdict !== "fail" || typeof value.reason !== "string" || !value.reason.trim() || typeof value.recordedAt !== "string" || value.assurance !== "declared" || value.independence !== "unverified" || !value.report || typeof value.report !== "object" || Array.isArray(value.report)) {
20260
20294
  throw new Error(`adoption audit receipt format is invalid: ${requested}`);
20261
20295
  }
20262
20296
  const report = value.report;
20263
- if (typeof report.path !== "string" || !(0, import_node_path5.isAbsolute)(report.path) || !isSha256(report.sha256))
20297
+ if (typeof report.path !== "string" || !(0, import_node_path6.isAbsolute)(report.path) || !isSha256(report.sha256))
20264
20298
  throw new Error(`adoption audit receipt report binding is invalid: ${requested}`);
20265
20299
  return value;
20266
20300
  }
@@ -20294,7 +20328,7 @@ function assertManagedFileAdoptionReceipt(repo, inspections, candidateDir, recei
20294
20328
  if (entry.type !== evidence.type) throw new Error(`candidate legacy type changed for ${entry.path}`);
20295
20329
  const artifact = readBundleFile(candidate.root, evidence.artifact, `legacy evidence ${entry.path}`);
20296
20330
  if (entry.type === "file") {
20297
- const liveSnapshot = readRegularFile((0, import_node_path5.join)(repoRoot, entry.snapshot), `legacy snapshot ${entry.path}`);
20331
+ const liveSnapshot = readRegularFile((0, import_node_path6.join)(repoRoot, entry.snapshot), `legacy snapshot ${entry.path}`);
20298
20332
  if (evidence.sourceSha256 !== entry.sha256 || evidence.mode !== entry.mode || !artifact.equals(liveSnapshot))
20299
20333
  throw new Error(`candidate legacy bytes or mode changed for ${entry.path}`);
20300
20334
  } else {
@@ -20318,18 +20352,18 @@ function assertManagedFileAdoptionReceipt(repo, inspections, candidateDir, recei
20318
20352
  if (receipt.candidatePath !== candidate.root || receipt.candidateHash !== metadata.candidateHash)
20319
20353
  throw new Error(`receipt does not bind candidate ${metadata.candidateHash}`);
20320
20354
  if (receipt.verdict !== "pass") throw new Error(`adoption audit verdict is ${receipt.verdict}; pass is required`);
20321
- const reportPath = (0, import_node_path5.resolve)(receipt.report.path);
20322
- if ((0, import_node_fs5.realpathSync)(reportPath) !== receipt.report.path) throw new Error(`audit report path changed: ${reportPath}`);
20355
+ const reportPath = (0, import_node_path6.resolve)(receipt.report.path);
20356
+ if ((0, import_node_fs6.realpathSync)(reportPath) !== receipt.report.path) throw new Error(`audit report path changed: ${reportPath}`);
20323
20357
  if (sha256(readRegularFile(reportPath, "audit report")) !== receipt.report.sha256)
20324
20358
  throw new Error(`audit report hash mismatch: ${receipt.report.sha256}`);
20325
- const manifestBytes = readRegularFile((0, import_node_path5.join)(repoRoot, MANIFEST_REL), "manifest");
20359
+ const manifestBytes = readRegularFile((0, import_node_path6.join)(repoRoot, MANIFEST_REL), "manifest");
20326
20360
  if (metadata.source.manifest.sha256 !== sha256(manifestBytes)) throw new Error("manifest changed after candidate preparation");
20327
20361
  if (!readBundleFile(candidate.root, metadata.source.manifest.artifact, "candidate manifest").equals(manifestBytes))
20328
20362
  throw new Error("candidate manifest no longer matches the live manifest");
20329
20363
  const manifest = loadManifest(repoRoot);
20330
20364
  const errors = validateManifest(manifest).filter((issue) => issue.level === "error");
20331
20365
  if (errors.length) throw new Error(`manifest invalid: ${errors.map((issue) => issue.msg).join("; ")}`);
20332
- const rendered = renderTargets(manifest);
20366
+ const rendered = renderTargets(manifest, { harnessVersion: lockedHarnessVersion(repoRoot) });
20333
20367
  if (!samePathList(metadata.targets.map((target) => target.path), rendered.map(([path]) => path)))
20334
20368
  throw new Error("current render target list differs from the audited candidate");
20335
20369
  if (!samePathList(inspections.map((inspection) => inspection.relativePath), rendered.map(([path]) => path)))
@@ -20358,8 +20392,8 @@ var import_yaml2 = __toESM(require_dist(), 1);
20358
20392
  // src/git.ts
20359
20393
  var import_node_child_process3 = require("node:child_process");
20360
20394
  var import_node_crypto5 = require("node:crypto");
20361
- var import_node_fs6 = require("node:fs");
20362
- var import_node_path6 = require("node:path");
20395
+ var import_node_fs7 = require("node:fs");
20396
+ var import_node_path7 = require("node:path");
20363
20397
  var GitDiffError = class extends Error {
20364
20398
  constructor(kind, message) {
20365
20399
  super(message);
@@ -20447,17 +20481,17 @@ function nulList(raw) {
20447
20481
  }
20448
20482
  function canonicalPath(path) {
20449
20483
  try {
20450
- return (0, import_node_fs6.realpathSync)(path);
20484
+ return (0, import_node_fs7.realpathSync)(path);
20451
20485
  } catch {
20452
- return (0, import_node_path6.resolve)(path);
20486
+ return (0, import_node_path7.resolve)(path);
20453
20487
  }
20454
20488
  }
20455
20489
  function targetPrefix(root, target) {
20456
- const native = (0, import_node_path6.relative)(root, target);
20490
+ const native = (0, import_node_path7.relative)(root, target);
20457
20491
  if (!native) return "";
20458
- if ((0, import_node_path6.isAbsolute)(native) || native === ".." || native.startsWith(`..${import_node_path6.sep}`))
20492
+ if ((0, import_node_path7.isAbsolute)(native) || native === ".." || native.startsWith(`..${import_node_path7.sep}`))
20459
20493
  throw new GitDiffError("not-a-repo", `target is outside its Git worktree: ${target}`);
20460
- return native.split(import_node_path6.sep).join("/");
20494
+ return native.split(import_node_path7.sep).join("/");
20461
20495
  }
20462
20496
  function scopeEntries(entries, prefix) {
20463
20497
  if (!prefix) return entries;
@@ -20465,10 +20499,10 @@ function scopeEntries(entries, prefix) {
20465
20499
  return entries.filter((entry) => entry.path.startsWith(start)).map((entry) => ({ ...entry, path: entry.path.slice(start.length) }));
20466
20500
  }
20467
20501
  function digestPath(repo, rel) {
20468
- const abs = (0, import_node_path6.join)(repo, rel);
20502
+ const abs = (0, import_node_path7.join)(repo, rel);
20469
20503
  try {
20470
- const stat = (0, import_node_fs6.lstatSync)(abs);
20471
- if (stat.isSymbolicLink()) return `symlink:${(0, import_node_fs6.readlinkSync)(abs)}`;
20504
+ const stat = (0, import_node_fs7.lstatSync)(abs);
20505
+ if (stat.isSymbolicLink()) return `symlink:${(0, import_node_fs7.readlinkSync)(abs)}`;
20472
20506
  if (stat.isDirectory()) {
20473
20507
  try {
20474
20508
  const head = (0, import_node_child_process3.execFileSync)("git", ["-C", abs, "rev-parse", "--verify", "HEAD"], {
@@ -20483,7 +20517,7 @@ function digestPath(repo, rel) {
20483
20517
  }
20484
20518
  if (!stat.isFile()) return `other:${stat.mode}`;
20485
20519
  const gitMode = stat.mode & 73 ? "100755" : "100644";
20486
- return `file:${gitMode}:${(0, import_node_crypto5.createHash)("sha256").update((0, import_node_fs6.readFileSync)(abs)).digest("hex")}`;
20520
+ return `file:${gitMode}:${(0, import_node_crypto5.createHash)("sha256").update((0, import_node_fs7.readFileSync)(abs)).digest("hex")}`;
20487
20521
  } catch {
20488
20522
  return "(missing)";
20489
20523
  }
@@ -20559,9 +20593,22 @@ function collectChanges(repoInput, base = "HEAD", opts = {}) {
20559
20593
  fingerprint: fingerprint(target, resolvedBase, entries)
20560
20594
  };
20561
20595
  }
20596
+ function readFileAtCommit(repoInput, commit, rel) {
20597
+ const target = canonicalPath(repoInput);
20598
+ const root = canonicalPath(gitRoot(target));
20599
+ const prefix = targetPrefix(root, target);
20600
+ const path = prefix ? `${prefix}/${rel}` : rel;
20601
+ const entry = git(root, ["--literal-pathspecs", "ls-tree", "-z", "--full-tree", commit, "--", path]);
20602
+ const match = /^\d+ (\w+) ([0-9a-f]+)\t/.exec(entry);
20603
+ if (!match || match[1] !== "blob") return null;
20604
+ return git(root, ["cat-file", "blob", match[2]]);
20605
+ }
20606
+ function listWorktreeFiles(dir, glob) {
20607
+ return nulList(git(dir, ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", `:(glob)${glob}`]));
20608
+ }
20562
20609
 
20563
20610
  // src/upgrade.ts
20564
- var UPGRADE_STATE_REL = ".agents/harness.lock.json";
20611
+ var UPGRADE_STATE_REL = HARNESS_LOCK_REL;
20565
20612
  var UPGRADE_STATE_SCHEMA = "ai-harness/upgrade-state/v1";
20566
20613
  var UPGRADE_REPORT_SCHEMA = "ai-harness/upgrade-report/v1";
20567
20614
  var UPGRADE_MIGRATIONS = [
@@ -20726,15 +20773,16 @@ function internalUpgrade(repo, options) {
20726
20773
  };
20727
20774
  const manifestChanged = migratedManifestContent !== normalizedSource;
20728
20775
  const finalManifestContent = manifestChanged ? migratedManifestContent : manifestInspection.currentContent;
20776
+ const generated = renderTargets(finalManifest, { harnessVersion: nextState.version });
20729
20777
  const targets = [
20730
20778
  // Keep an unchanged manifest in the transaction preflight so generated
20731
20779
  // files can never be committed from bytes that changed after planning.
20732
20780
  [MANIFEST_REL, finalManifestContent],
20733
- ...renderTargets(finalManifest),
20781
+ ...generated,
20734
20782
  [UPGRADE_STATE_REL, renderState(nextState)]
20735
20783
  ];
20736
20784
  const preflight = inspectManagedFiles(repo, targets);
20737
- const generatedPaths = new Set(renderTargets(finalManifest).map(([path]) => path));
20785
+ const generatedPaths = new Set(generated.map(([path]) => path));
20738
20786
  try {
20739
20787
  assertManagedFileAdoption(
20740
20788
  repo,
@@ -20903,7 +20951,12 @@ function syncCmd(repo, opts = {}) {
20903
20951
  const errors = validateManifest(m).filter((issue) => issue.level === "error");
20904
20952
  if (errors.length) throw new Error(`manifest invalid: ${errors.map((issue) => issue.msg).join("; ")}`);
20905
20953
  info("Syncing generated files from .agents/manifest.yaml ...");
20906
- const targets = renderTargets(m);
20954
+ const harnessVersion = lockedHarnessVersion(repo);
20955
+ if (harnessVersion && harnessVersion !== package_default.version)
20956
+ warn(
20957
+ `running harness-kit ${package_default.version} but ${HARNESS_LOCK_REL} pins ${harnessVersion}; generated entries keep pinning ${harnessVersion}. Use \`upgrade\` to move the repository to this version.`
20958
+ );
20959
+ const targets = renderTargets(m, { harnessVersion });
20907
20960
  if (!!opts.adoptionCandidate !== !!opts.adoptionAudit)
20908
20961
  throw new Error("adoption requires both --candidate <bundle> and --audit <receipt>");
20909
20962
  if ((opts.adoptionCandidate || opts.adoptionAudit) && !opts.adoptExisting)
@@ -20929,8 +20982,8 @@ function syncCmd(repo, opts = {}) {
20929
20982
 
20930
20983
  // src/commands/doctor.ts
20931
20984
  var import_fast_glob3 = __toESM(require_out4(), 1);
20932
- var import_node_fs12 = require("node:fs");
20933
- var import_node_path12 = require("node:path");
20985
+ var import_node_fs13 = require("node:fs");
20986
+ var import_node_path13 = require("node:path");
20934
20987
 
20935
20988
  // src/guidance.ts
20936
20989
  function gap(kind, scope, classification, title, reason, when, legacyText) {
@@ -21011,7 +21064,7 @@ function declaredVerificationGaps(manifest) {
21011
21064
  }
21012
21065
  return gaps;
21013
21066
  }
21014
- function automationAction(gaps) {
21067
+ function automationAction(gaps, cli) {
21015
21068
  const recommended = gaps.filter((item) => item.classification === "recommended");
21016
21069
  if (!recommended.length) return null;
21017
21070
  return {
@@ -21021,7 +21074,7 @@ function automationAction(gaps) {
21021
21074
  when: "harness-maintenance",
21022
21075
  title: `Improve ${recommended.length} verification declaration(s)`,
21023
21076
  reason: "These declarations have no executable check or complete manual procedure. They do not invalidate this run, but they weaken future coverage.",
21024
- commands: ["harness-kit verify --repo . --details"],
21077
+ commands: [`${cli} verify --repo . --details`],
21025
21078
  completion: "Each declaration has a real enforcement/check, or an explicit manual procedure when automation is genuinely impossible."
21026
21079
  };
21027
21080
  }
@@ -21033,65 +21086,74 @@ function unsafeHookIssue(issue) {
21033
21086
  issue
21034
21087
  );
21035
21088
  }
21036
- function hookActions(hooks) {
21089
+ function hookActions(hooks, cli) {
21037
21090
  if (hooks.state === "active") return [];
21038
21091
  const configured = hooks.configuredAgents.join(",");
21039
- if (hooks.state === "configured" || hooks.configuredAgents.length > 0 && hooks.issues.every(evidenceOnlyIssue)) {
21040
- return [{
21041
- id: "prove-lifecycle-hooks",
21042
- priority: "required",
21043
- owner: "agent",
21044
- when: "before-harness-ready",
21045
- title: "Prove the lifecycle Hook in a fresh Agent session",
21046
- reason: `A complete Hook is configured for ${configured || "the current Agent"}, but no current SessionStart + Stop evidence proves that the host executed it.`,
21047
- commands: ["harness-kit evidence --repo . --json"],
21048
- completion: "A newly created Agent session finishes once and evidence reports hookActive: true."
21049
- }];
21050
- }
21051
21092
  const unsafe = hooks.issues.filter(unsafeHookIssue);
21052
21093
  if (unsafe.length) {
21053
21094
  return [{
21054
21095
  id: "review-lifecycle-hook-conflict",
21055
- priority: "required",
21096
+ priority: "recommended",
21056
21097
  owner: "human",
21057
- when: "before-harness-ready",
21058
- title: "Approve resolution of an existing Hook configuration conflict",
21059
- reason: "Harness found a Hook file or registration it cannot safely replace: " + unsafe.join("; "),
21098
+ when: "harness-maintenance",
21099
+ title: "Optional: resolve Hook configuration conflict for session intercept",
21100
+ reason: "Harness found a Hook file or registration it cannot safely replace: " + unsafe.join("; ") + ". Delivery still works via harness-kit deliver without hooks.",
21060
21101
  commands: [],
21061
- completion: "The user approves one exact proposed change; the Agent then installs safely and proves hookActive: true in a fresh session."
21102
+ completion: "User approves one exact proposed change, or accepts cooperative deliver-only workflow."
21103
+ }];
21104
+ }
21105
+ if (hooks.state === "configured" || hooks.configuredAgents.length > 0 && hooks.issues.every(evidenceOnlyIssue)) {
21106
+ return [{
21107
+ id: "optional-lifecycle-hook-observation",
21108
+ priority: "recommended",
21109
+ owner: "agent",
21110
+ when: "harness-maintenance",
21111
+ title: "Optional: observe lifecycle Hook on a later Stop",
21112
+ 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.`,
21113
+ commands: [`${cli} deliver --repo .`, `${cli} evidence --repo . --json`],
21114
+ completion: "Deliver stamp is valid; hook observation is optional."
21115
+ }];
21116
+ }
21117
+ if (!hooks.configuredAgents.length) {
21118
+ return [{
21119
+ id: "optional-install-lifecycle-hooks",
21120
+ priority: "recommended",
21121
+ owner: "agent",
21122
+ when: "harness-maintenance",
21123
+ title: "Optional: install Agent Stop intercept for session-level loops",
21124
+ reason: "Without Stop hooks, agents must run harness-kit deliver cooperatively. Install hooks only when the host supports them.",
21125
+ commands: [
21126
+ `${cli} deliver --repo .`,
21127
+ `${cli} install-hooks --repo . --stop --agents ${configured || "<current-agent>"}`
21128
+ ],
21129
+ completion: "Deliver works without hooks; hooks only add session intercept when the host fires Stop."
21062
21130
  }];
21063
21131
  }
21064
- const agents = configured || "<current-agent>";
21065
21132
  return [{
21066
- id: hooks.configuredAgents.length ? "repair-lifecycle-hooks" : "install-lifecycle-hooks",
21067
- priority: "required",
21133
+ id: "repair-lifecycle-hooks",
21134
+ priority: "recommended",
21068
21135
  owner: "agent",
21069
- when: "before-harness-ready",
21070
- title: hooks.configuredAgents.length ? "Repair the Agent lifecycle Hook" : "Install the Agent lifecycle Hook",
21071
- reason: "Automatic SessionStart + Stop validation is not currently effective. The Agent should handle safe installation without asking the user to choose an implementation.",
21136
+ when: "harness-maintenance",
21137
+ title: "Optional: repair Agent lifecycle Hook configuration",
21138
+ reason: "Hook configuration is incomplete or degraded. Delivery still uses harness-kit deliver.",
21072
21139
  commands: [
21073
- `harness-kit install-hooks --repo . --stop --agents ${agents}`,
21074
- "harness-kit install-hooks --repo . --stop --agents codex --allow-user-dispatcher # linked Codex worktree only",
21075
- "harness-kit evidence --repo . --json # after one fresh Agent session finishes"
21140
+ `${cli} install-hooks --repo . --stop --agents ${configured}`,
21141
+ `${cli} deliver --repo .`
21076
21142
  ],
21077
- completion: "A fresh Agent session records both gates and evidence reports hookActive: true."
21143
+ completion: "Hooks install cleanly or the team accepts deliver-only cooperative mode."
21078
21144
  }];
21079
21145
  }
21080
- function evidenceActions(evidence) {
21146
+ function evidenceActions(evidence, cli) {
21081
21147
  if (!evidence.found) {
21082
21148
  return [{
21083
21149
  id: "record-delivery-evidence",
21084
21150
  priority: "required",
21085
21151
  owner: "agent",
21086
21152
  when: "before-finish",
21087
- title: "Create delivery evidence for this change",
21088
- reason: "No run-checks + verify evidence exists for the current worktree/session.",
21089
- commands: [
21090
- "harness-kit run-checks --repo . --base <task-start-sha>",
21091
- "harness-kit verify --repo .",
21092
- "harness-kit evidence --repo . --json"
21093
- ],
21094
- completion: "Evidence reports valid: true for the current code fingerprint."
21153
+ title: "Accept this change with harness-kit deliver",
21154
+ reason: "No delivery stamp exists for the current worktree/session.",
21155
+ commands: [`${cli} deliver --repo .`, `${cli} evidence --repo . --json`],
21156
+ completion: "deliver reports status=accepted (or no-change) and evidence stamp is valid."
21095
21157
  }];
21096
21158
  }
21097
21159
  if (evidence.stale) {
@@ -21100,14 +21162,10 @@ function evidenceActions(evidence) {
21100
21162
  priority: "required",
21101
21163
  owner: "agent",
21102
21164
  when: "before-finish",
21103
- title: "Re-run validation for the current code",
21104
- reason: "The saved green result belongs to an older code fingerprint.",
21105
- commands: [
21106
- "harness-kit run-checks --repo . --base <task-start-sha>",
21107
- "harness-kit verify --repo .",
21108
- "harness-kit evidence --repo . --json"
21109
- ],
21110
- completion: "Evidence is no longer stale and reports valid: true."
21165
+ title: "Re-run deliver for the current code",
21166
+ reason: "The saved green stamp belongs to an older code fingerprint.",
21167
+ commands: [`${cli} deliver --repo .`, `${cli} evidence --repo . --json`],
21168
+ completion: "Stamp is no longer stale and deliver reports accepted."
21111
21169
  }];
21112
21170
  }
21113
21171
  if (!evidence.runChecksValid) {
@@ -21116,10 +21174,10 @@ function evidenceActions(evidence) {
21116
21174
  priority: "required",
21117
21175
  owner: "agent",
21118
21176
  when: "before-finish",
21119
- title: "Complete the impact-driven checks",
21177
+ title: "Complete impact-driven delivery checks",
21120
21178
  reason: "The selected checks did not produce valid evidence for the current code.",
21121
- commands: ["harness-kit run-checks --repo . --base <task-start-sha>", "harness-kit evidence --repo . --json"],
21122
- completion: "Evidence reports runChecksValid: true for the current code fingerprint."
21179
+ commands: [`${cli} deliver --repo .`, `${cli} evidence --repo . --json`],
21180
+ completion: "deliver reports accepted and stamp runChecksValid: true."
21123
21181
  }];
21124
21182
  }
21125
21183
  if (!evidence.verifyPassed || !evidence.valid) {
@@ -21128,22 +21186,23 @@ function evidenceActions(evidence) {
21128
21186
  priority: "required",
21129
21187
  owner: "agent",
21130
21188
  when: "before-finish",
21131
- title: "Complete repository verification",
21189
+ title: "Complete delivery verification",
21132
21190
  reason: "Change checks passed, but matching verify evidence is missing or failed.",
21133
- commands: ["harness-kit verify --repo .", "harness-kit evidence --repo . --json"],
21134
- completion: "Evidence reports valid: true for the current code fingerprint."
21191
+ commands: [`${cli} deliver --repo .`, `${cli} evidence --repo . --json`],
21192
+ completion: "deliver reports accepted and stamp valid: true."
21135
21193
  }];
21136
21194
  }
21137
21195
  return [];
21138
21196
  }
21139
21197
  function buildHarnessGuidance(input) {
21198
+ const cli = input.cli ?? "harness-kit";
21140
21199
  const gapDetails = input.manifest ? declaredVerificationGaps(input.manifest) : [];
21141
- const nextActions = [
21142
- ...input.evidence ? evidenceActions(input.evidence) : [],
21143
- ...input.hooks ? hookActions(input.hooks) : []
21200
+ const nextActions2 = [
21201
+ ...input.evidence ? evidenceActions(input.evidence, cli) : [],
21202
+ ...input.hooks ? hookActions(input.hooks, cli) : []
21144
21203
  ];
21145
- const improvement = automationAction(gapDetails);
21146
- if (improvement) nextActions.push(improvement);
21204
+ const improvement = automationAction(gapDetails, cli);
21205
+ if (improvement) nextActions2.push(improvement);
21147
21206
  return {
21148
21207
  gapDetails,
21149
21208
  gapSummary: {
@@ -21151,19 +21210,19 @@ function buildHarnessGuidance(input) {
21151
21210
  recommended: gapDetails.filter((item) => item.classification === "recommended").length,
21152
21211
  informational: gapDetails.filter((item) => item.classification === "informational").length
21153
21212
  },
21154
- nextActions
21213
+ nextActions: nextActions2
21155
21214
  };
21156
21215
  }
21157
21216
 
21158
21217
  // src/hook-status.ts
21159
- var import_node_fs10 = require("node:fs");
21160
- var import_node_path10 = require("node:path");
21218
+ var import_node_fs11 = require("node:fs");
21219
+ var import_node_path11 = require("node:path");
21161
21220
 
21162
21221
  // src/codex-linked-hooks.ts
21163
21222
  var import_node_child_process4 = require("node:child_process");
21164
- var import_node_fs7 = require("node:fs");
21223
+ var import_node_fs8 = require("node:fs");
21165
21224
  var import_node_os = require("node:os");
21166
- var import_node_path7 = require("node:path");
21225
+ var import_node_path8 = require("node:path");
21167
21226
  var CODEX_LINKED_PROTOCOL = "ai-harness/codex-linked-dispatch/v1";
21168
21227
  var DISPATCH_ID = "codex-linked-dispatch-v1";
21169
21228
  var DISPATCHER_REL = `harness-kit/${DISPATCH_ID}.cjs`;
@@ -21173,25 +21232,25 @@ var RUNNER_REL = ".agents/hooks/harness-agent-hook.sh";
21173
21232
  var DISPATCHER_MARK = "harness-kit-managed-codex-linked-dispatch-v1";
21174
21233
  function canonical(path) {
21175
21234
  try {
21176
- return (0, import_node_fs7.realpathSync)(path);
21235
+ return (0, import_node_fs8.realpathSync)(path);
21177
21236
  } catch {
21178
- return (0, import_node_path7.resolve)(path);
21237
+ return (0, import_node_path8.resolve)(path);
21179
21238
  }
21180
21239
  }
21181
21240
  function ensureCodexHome(requestedInput, label) {
21182
- const requested = (0, import_node_path7.resolve)(requestedInput);
21183
- (0, import_node_fs7.mkdirSync)(requested, { recursive: true, mode: 448 });
21184
- const resolved = (0, import_node_fs7.realpathSync)(requested);
21185
- if (!(0, import_node_fs7.statSync)(resolved).isDirectory()) throw new Error(`${label} is not a directory: ${requested}`);
21241
+ const requested = (0, import_node_path8.resolve)(requestedInput);
21242
+ (0, import_node_fs8.mkdirSync)(requested, { recursive: true, mode: 448 });
21243
+ const resolved = (0, import_node_fs8.realpathSync)(requested);
21244
+ if (!(0, import_node_fs8.statSync)(resolved).isDirectory()) throw new Error(`${label} is not a directory: ${requested}`);
21186
21245
  return resolved;
21187
21246
  }
21188
21247
  function resolveCodexHookSourceHome(options = {}) {
21189
21248
  const env = options.env ?? process.env;
21190
21249
  const userHome = options.homeDir ?? (0, import_node_os.homedir)();
21191
- const runtimeHome = ensureCodexHome(env.CODEX_HOME ?? (0, import_node_path7.join)(userHome, ".codex"), "CODEX_HOME");
21250
+ const runtimeHome = ensureCodexHome(env.CODEX_HOME ?? (0, import_node_path8.join)(userHome, ".codex"), "CODEX_HOME");
21192
21251
  const orcaRuntimeHome = env.ORCA_CODEX_HOME?.trim();
21193
- if (env.ORCA_WORKTREE_ID?.trim() && orcaRuntimeHome && canonical((0, import_node_path7.resolve)(orcaRuntimeHome)) === runtimeHome) {
21194
- const codexHome = ensureCodexHome((0, import_node_path7.join)(userHome, ".codex"), "Codex system hook source home");
21252
+ if (env.ORCA_WORKTREE_ID?.trim() && orcaRuntimeHome && canonical((0, import_node_path8.resolve)(orcaRuntimeHome)) === runtimeHome) {
21253
+ const codexHome = ensureCodexHome((0, import_node_path8.join)(userHome, ".codex"), "Codex system hook source home");
21195
21254
  return { codexHome, requiresRuntimeRefresh: codexHome !== runtimeHome };
21196
21255
  }
21197
21256
  return { codexHome: runtimeHome, requiresRuntimeRefresh: false };
@@ -21200,7 +21259,7 @@ function shellQuote(value) {
21200
21259
  return `'${value.replace(/'/g, `'"'"'`)}'`;
21201
21260
  }
21202
21261
  function userHookCommand(codexHome, event) {
21203
- return `node ${shellQuote((0, import_node_path7.join)(codexHome, DISPATCHER_REL))} ${event}`;
21262
+ return `node ${shellQuote((0, import_node_path8.join)(codexHome, DISPATCHER_REL))} ${event}`;
21204
21263
  }
21205
21264
  function managedUserGroup(codexHome, event) {
21206
21265
  return {
@@ -21231,7 +21290,7 @@ function parseObjectJson(raw, label) {
21231
21290
  throw new Error(`${label} exists but is not valid JSON`);
21232
21291
  }
21233
21292
  function renderUserHooks(current, codexHome) {
21234
- const hooksPath = (0, import_node_path7.join)(codexHome, USER_HOOKS_REL);
21293
+ const hooksPath = (0, import_node_path8.join)(codexHome, USER_HOOKS_REL);
21235
21294
  const json = parseObjectJson(current, hooksPath);
21236
21295
  if (json.hooks !== void 0 && (!json.hooks || typeof json.hooks !== "object" || Array.isArray(json.hooks))) {
21237
21296
  throw new Error(`${hooksPath} hooks must be an object; refusing to replace an unknown existing shape`);
@@ -21280,9 +21339,9 @@ function registrationFrom(raw, label) {
21280
21339
  }
21281
21340
  function runnerMode(repoRoot, content) {
21282
21341
  try {
21283
- const path = (0, import_node_path7.join)(repoRoot, RUNNER_REL);
21284
- const stat = (0, import_node_fs7.lstatSync)(path);
21285
- if (stat.isFile() && !stat.isSymbolicLink() && (0, import_node_fs7.readFileSync)(path, "utf8") === content) return stat.mode & 511;
21342
+ const path = (0, import_node_path8.join)(repoRoot, RUNNER_REL);
21343
+ const stat = (0, import_node_fs8.lstatSync)(path);
21344
+ if (stat.isFile() && !stat.isSymbolicLink() && (0, import_node_fs8.readFileSync)(path, "utf8") === content) return stat.mode & 511;
21286
21345
  } catch {
21287
21346
  }
21288
21347
  return 493;
@@ -21416,7 +21475,7 @@ function prepareCodexLinkedInstall(repoInput, runnerContent, options = {}) {
21416
21475
  const initialByPath = inspectionMap(initialUser);
21417
21476
  const currentDispatcher = initialByPath.get(DISPATCHER_REL)?.currentContent ?? null;
21418
21477
  if (currentDispatcher !== null && currentDispatcher !== dispatcher) {
21419
- throw new Error(`${(0, import_node_path7.join)(codexHome, DISPATCHER_REL)} exists and is foreign or changed; refusing to replace it`);
21478
+ throw new Error(`${(0, import_node_path8.join)(codexHome, DISPATCHER_REL)} exists and is foreign or changed; refusing to replace it`);
21420
21479
  }
21421
21480
  const currentHooks = initialByPath.get(USER_HOOKS_REL)?.currentContent ?? null;
21422
21481
  const renderedHooks = renderUserHooks(currentHooks, codexHome);
@@ -21460,30 +21519,30 @@ function prepareCodexLinkedInstall(repoInput, runnerContent, options = {}) {
21460
21519
  };
21461
21520
  }
21462
21521
  function registrationPathLabel(gitDir) {
21463
- return (0, import_node_path7.join)(gitDir, REGISTRATION_REL);
21522
+ return (0, import_node_path8.join)(gitDir, REGISTRATION_REL);
21464
21523
  }
21465
21524
  function commitCodexLinkedInstall(plan, testHooks = {}) {
21466
21525
  testHooks.beforeUserTransaction?.();
21467
21526
  const userResult = writeManagedFiles(plan.codexHome, plan.userTargets, {
21468
21527
  authorize: (current) => assertInspectionsUnchanged(plan.userInspections, current, "Codex user Hook source")
21469
21528
  });
21470
- (0, import_node_fs7.chmodSync)((0, import_node_path7.join)(plan.codexHome, DISPATCHER_REL), 448);
21529
+ (0, import_node_fs8.chmodSync)((0, import_node_path8.join)(plan.codexHome, DISPATCHER_REL), 448);
21471
21530
  if (userResult.inspections.find((item) => item.relativePath === USER_HOOKS_REL)?.kind === "missing") {
21472
- (0, import_node_fs7.chmodSync)((0, import_node_path7.join)(plan.codexHome, USER_HOOKS_REL), 384);
21531
+ (0, import_node_fs8.chmodSync)((0, import_node_path8.join)(plan.codexHome, USER_HOOKS_REL), 384);
21473
21532
  }
21474
21533
  testHooks.beforeRegistrationTransaction?.();
21475
21534
  writeManagedFiles(plan.gitDir, [plan.registrationTarget], {
21476
21535
  authorize: (current) => assertInspectionsUnchanged(plan.registrationInspections, current, "Codex linked registration source")
21477
21536
  });
21478
- (0, import_node_fs7.chmodSync)((0, import_node_path7.join)(plan.gitDir, REGISTRATION_REL), 384);
21537
+ (0, import_node_fs8.chmodSync)((0, import_node_path8.join)(plan.gitDir, REGISTRATION_REL), 384);
21479
21538
  }
21480
21539
  function safeContent(root, rel, issues) {
21481
21540
  try {
21482
21541
  const inspected = inspectManagedFiles(root, [[rel, ""]])[0];
21483
21542
  if (inspected.kind === "missing" || inspected.currentContent === null) return { content: null };
21484
- return { content: inspected.currentContent, mode: (0, import_node_fs7.lstatSync)((0, import_node_path7.join)(root, rel)).mode & 511 };
21543
+ return { content: inspected.currentContent, mode: (0, import_node_fs8.lstatSync)((0, import_node_path8.join)(root, rel)).mode & 511 };
21485
21544
  } catch (error) {
21486
- issues.push(`${(0, import_node_path7.join)(root, rel)} is not a safe regular file: ${error.message}`);
21545
+ issues.push(`${(0, import_node_path8.join)(root, rel)} is not a safe regular file: ${error.message}`);
21487
21546
  return { content: null };
21488
21547
  }
21489
21548
  }
@@ -21526,7 +21585,7 @@ function inspectCodexLinkedHooks(repoInput) {
21526
21585
  issues.push("Codex user hooks.json is missing");
21527
21586
  } else {
21528
21587
  try {
21529
- const json = parseObjectJson(userHooksFile.content, (0, import_node_path7.join)(registration.codexHome, USER_HOOKS_REL));
21588
+ const json = parseObjectJson(userHooksFile.content, (0, import_node_path8.join)(registration.codexHome, USER_HOOKS_REL));
21530
21589
  const hooks = json.hooks;
21531
21590
  const start = Array.isArray(hooks?.SessionStart) ? hooks.SessionStart.find((group) => isExactManagedUserGroup(group, registration.codexHome, "session-start")) : void 0;
21532
21591
  const stop = Array.isArray(hooks?.Stop) ? hooks.Stop.find((group) => isExactManagedUserGroup(group, registration.codexHome, "stop")) : void 0;
@@ -21549,8 +21608,8 @@ function inspectCodexLinkedHooks(repoInput) {
21549
21608
 
21550
21609
  // src/validation-state.ts
21551
21610
  var import_node_crypto6 = require("node:crypto");
21552
- var import_node_fs8 = require("node:fs");
21553
- var import_node_path8 = require("node:path");
21611
+ var import_node_fs9 = require("node:fs");
21612
+ var import_node_path9 = require("node:path");
21554
21613
 
21555
21614
  // src/planner.ts
21556
21615
  var import_picomatch2 = __toESM(require_picomatch2(), 1);
@@ -21858,24 +21917,24 @@ var TOKEN_RX = /^[a-f0-9]{64}$/;
21858
21917
  var MAX_SESSIONS = 100;
21859
21918
  var MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
21860
21919
  function stateDir(repo) {
21861
- return (0, import_node_path8.join)(gitAdminDir(repo), "harness-kit", "validation");
21920
+ return (0, import_node_path9.join)(gitAdminDir(repo), "harness-kit", "validation");
21862
21921
  }
21863
21922
  function canonicalTarget(repo) {
21864
21923
  try {
21865
- return (0, import_node_fs8.realpathSync)(repo);
21924
+ return (0, import_node_fs9.realpathSync)(repo);
21866
21925
  } catch {
21867
- return (0, import_node_path8.resolve)(repo);
21926
+ return (0, import_node_path9.resolve)(repo);
21868
21927
  }
21869
21928
  }
21870
21929
  function latestPath(repo) {
21871
- return (0, import_node_path8.join)(stateDir(repo), `latest-${sha256(canonicalTarget(repo)).slice(0, 24)}.json`);
21930
+ return (0, import_node_path9.join)(stateDir(repo), `latest-${sha256(canonicalTarget(repo)).slice(0, 24)}.json`);
21872
21931
  }
21873
21932
  function validationSessionToken(agent, sessionId2) {
21874
21933
  return sha256(`${agent}\0${sessionId2}`);
21875
21934
  }
21876
21935
  function sessionPath(repo, token) {
21877
21936
  if (!TOKEN_RX.test(token)) throw new Error("invalid validation session token");
21878
- return (0, import_node_path8.join)(stateDir(repo), `${token}.json`);
21937
+ return (0, import_node_path9.join)(stateDir(repo), `${token}.json`);
21879
21938
  }
21880
21939
  function readJson(path) {
21881
21940
  const raw = readText(path);
@@ -21888,21 +21947,21 @@ function readJson(path) {
21888
21947
  }
21889
21948
  function expired(path) {
21890
21949
  try {
21891
- return Date.now() - (0, import_node_fs8.statSync)(path).mtimeMs > MAX_AGE_MS;
21950
+ return Date.now() - (0, import_node_fs9.statSync)(path).mtimeMs > MAX_AGE_MS;
21892
21951
  } catch {
21893
21952
  return false;
21894
21953
  }
21895
21954
  }
21896
21955
  function writePrivateJson(path, value) {
21897
- (0, import_node_fs8.mkdirSync)((0, import_node_path8.dirname)(path), { recursive: true });
21956
+ (0, import_node_fs9.mkdirSync)((0, import_node_path9.dirname)(path), { recursive: true });
21898
21957
  const temp = `${path}.${process.pid}.${(0, import_node_crypto6.randomUUID)()}.tmp`;
21899
21958
  try {
21900
- (0, import_node_fs8.writeFileSync)(temp, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
21901
- (0, import_node_fs8.renameSync)(temp, path);
21902
- (0, import_node_fs8.chmodSync)(path, 384);
21959
+ (0, import_node_fs9.writeFileSync)(temp, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
21960
+ (0, import_node_fs9.renameSync)(temp, path);
21961
+ (0, import_node_fs9.chmodSync)(path, 384);
21903
21962
  } catch (error) {
21904
21963
  try {
21905
- (0, import_node_fs8.unlinkSync)(temp);
21964
+ (0, import_node_fs9.unlinkSync)(temp);
21906
21965
  } catch {
21907
21966
  }
21908
21967
  throw error;
@@ -21915,9 +21974,9 @@ function pruneValidationState(repo) {
21915
21974
  const dir = stateDir(repo);
21916
21975
  let files;
21917
21976
  try {
21918
- files = (0, import_node_fs8.readdirSync)(dir).filter((name) => TOKEN_RX.test(name.replace(/\.json$/, ""))).map((name) => {
21919
- const path = (0, import_node_path8.join)(dir, name);
21920
- return { path, mtimeMs: (0, import_node_fs8.statSync)(path).mtimeMs };
21977
+ files = (0, import_node_fs9.readdirSync)(dir).filter((name) => TOKEN_RX.test(name.replace(/\.json$/, ""))).map((name) => {
21978
+ const path = (0, import_node_path9.join)(dir, name);
21979
+ return { path, mtimeMs: (0, import_node_fs9.statSync)(path).mtimeMs };
21921
21980
  }).sort((a, b) => b.mtimeMs - a.mtimeMs);
21922
21981
  } catch {
21923
21982
  return;
@@ -21926,7 +21985,7 @@ function pruneValidationState(repo) {
21926
21985
  for (const [index, file] of files.entries()) {
21927
21986
  if (index >= MAX_SESSIONS || now - file.mtimeMs > MAX_AGE_MS) {
21928
21987
  try {
21929
- (0, import_node_fs8.unlinkSync)(file.path);
21988
+ (0, import_node_fs9.unlinkSync)(file.path);
21930
21989
  } catch {
21931
21990
  }
21932
21991
  }
@@ -21966,7 +22025,7 @@ function readValidationSession(repo, token) {
21966
22025
  const path = sessionPath(repo, token);
21967
22026
  if (expired(path)) {
21968
22027
  try {
21969
- (0, import_node_fs8.unlinkSync)(path);
22028
+ (0, import_node_fs9.unlinkSync)(path);
21970
22029
  } catch {
21971
22030
  }
21972
22031
  return null;
@@ -21984,7 +22043,7 @@ function readLatestHookValidationSession(repoInput) {
21984
22043
  pruneValidationState(repo);
21985
22044
  let tokens;
21986
22045
  try {
21987
- tokens = (0, import_node_fs8.readdirSync)(stateDir(repo)).map((name) => ({ name, token: name.replace(/\.json$/, "") })).filter(({ name, token }) => name.endsWith(".json") && TOKEN_RX.test(token)).map(({ token }) => ({ token, mtimeMs: (0, import_node_fs8.statSync)(sessionPath(repo, token)).mtimeMs })).sort((left, right) => right.mtimeMs - left.mtimeMs);
22046
+ tokens = (0, import_node_fs9.readdirSync)(stateDir(repo)).map((name) => ({ name, token: name.replace(/\.json$/, "") })).filter(({ name, token }) => name.endsWith(".json") && TOKEN_RX.test(token)).map(({ token }) => ({ token, mtimeMs: (0, import_node_fs9.statSync)(sessionPath(repo, token)).mtimeMs })).sort((left, right) => right.mtimeMs - left.mtimeMs);
21988
22047
  } catch {
21989
22048
  return null;
21990
22049
  }
@@ -22092,8 +22151,8 @@ function markManualVerifyResult(repoInput, passed) {
22092
22151
  }
22093
22152
 
22094
22153
  // src/commands/stop-hooks.ts
22095
- var import_node_fs9 = require("node:fs");
22096
- var import_node_path9 = require("node:path");
22154
+ var import_node_fs10 = require("node:fs");
22155
+ var import_node_path10 = require("node:path");
22097
22156
  var ALL_AGENTS = ["claude", "cursor", "codex"];
22098
22157
  var SCRIPT_REL = ".agents/hooks/harness-agent-hook.sh";
22099
22158
  var SCRIPT_MARK = "harness-kit-managed-hook (agent-lifecycle)";
@@ -22310,7 +22369,7 @@ function installStopHooks(repo, agents, opts = {}) {
22310
22369
  err(`agent hooks require a Git worktree: ${error.message}`);
22311
22370
  return 1;
22312
22371
  }
22313
- if (!(0, import_node_fs9.existsSync)((0, import_node_path9.join)(repo, ".agents", "manifest.yaml"))) {
22372
+ if (!(0, import_node_fs10.existsSync)((0, import_node_path10.join)(repo, ".agents", "manifest.yaml"))) {
22314
22373
  err("agent hooks require .agents/manifest.yaml \u2014 onboard the repository first");
22315
22374
  return 1;
22316
22375
  }
@@ -22362,7 +22421,7 @@ function installStopHooks(repo, agents, opts = {}) {
22362
22421
  writeManagedFiles(repo, targets, {
22363
22422
  authorize: (transactionPreflight) => assertRenderedSourcesUnchanged(inspections, transactionPreflight)
22364
22423
  });
22365
- (0, import_node_fs9.chmodSync)((0, import_node_path9.join)(repo, SCRIPT_REL), 493);
22424
+ (0, import_node_fs10.chmodSync)((0, import_node_path10.join)(repo, SCRIPT_REL), 493);
22366
22425
  } catch (error) {
22367
22426
  err(`agent hooks not installed: ${error.message}`);
22368
22427
  return 1;
@@ -22387,8 +22446,8 @@ function installStopHooks(repo, agents, opts = {}) {
22387
22446
  ok("codex: enabled project hooks -> .codex/config.toml");
22388
22447
  if (linkedPlan) {
22389
22448
  ok("codex: removed project Harness hooks so the user dispatcher is the only lifecycle path -> .codex/hooks.json");
22390
- ok(`codex: installed linked-worktree dispatcher source -> ${(0, import_node_path9.join)(linkedPlan.codexHome, "harness-kit", "codex-linked-dispatch-v1.cjs")}`);
22391
- ok(`codex: registered this worktree -> ${(0, import_node_path9.join)(linkedPlan.gitDir, "harness-kit", "codex-linked-dispatch-v1.json")}`);
22449
+ ok(`codex: installed linked-worktree dispatcher source -> ${(0, import_node_path10.join)(linkedPlan.codexHome, "harness-kit", "codex-linked-dispatch-v1.cjs")}`);
22450
+ ok(`codex: registered this worktree -> ${(0, import_node_path10.join)(linkedPlan.gitDir, "harness-kit", "codex-linked-dispatch-v1.json")}`);
22392
22451
  } else {
22393
22452
  ok("codex: installed SessionStart + Stop hooks -> .codex/hooks.json");
22394
22453
  }
@@ -22514,7 +22573,7 @@ function codexFeatureEnabled(repo, issues) {
22514
22573
  return enabled;
22515
22574
  }
22516
22575
  function runnerReady(repo, issues) {
22517
- const path = (0, import_node_path10.join)(repo, RUNNER_REL2);
22576
+ const path = (0, import_node_path11.join)(repo, RUNNER_REL2);
22518
22577
  try {
22519
22578
  const inspected = safeProjectText(repo, RUNNER_REL2, issues);
22520
22579
  if (!inspected.exists) {
@@ -22522,7 +22581,7 @@ function runnerReady(repo, issues) {
22522
22581
  return false;
22523
22582
  }
22524
22583
  if (inspected.content === null) return false;
22525
- const stat = (0, import_node_fs10.lstatSync)(path);
22584
+ const stat = (0, import_node_fs11.lstatSync)(path);
22526
22585
  const withoutOptionalFinalNewline = (value) => value.endsWith("\n") ? value.slice(0, -1) : value;
22527
22586
  const ready = stat.isFile() && !stat.isSymbolicLink() && (stat.mode & 64) !== 0 && withoutOptionalFinalNewline(inspected.content) === withoutOptionalFinalNewline(installedAgentHookRunnerScript());
22528
22587
  if (!ready) issues.push(`${RUNNER_REL2} is not a managed executable runner`);
@@ -22534,7 +22593,7 @@ function runnerReady(repo, issues) {
22534
22593
  }
22535
22594
  function codexLinkedRegistrationExists(repo) {
22536
22595
  try {
22537
- return (0, import_node_fs10.existsSync)((0, import_node_path10.join)(gitAdminDir(repo), CODEX_LINKED_REGISTRATION_REL));
22596
+ return (0, import_node_fs11.existsSync)((0, import_node_path11.join)(gitAdminDir(repo), CODEX_LINKED_REGISTRATION_REL));
22538
22597
  } catch {
22539
22598
  return false;
22540
22599
  }
@@ -22571,7 +22630,7 @@ function agentHookConfigurationFingerprint(repo, agent) {
22571
22630
  artifacts.push({
22572
22631
  path: rel,
22573
22632
  content: inspected.content,
22574
- ...rel === RUNNER_REL2 ? { mode: (0, import_node_fs10.lstatSync)((0, import_node_path10.join)(repo, rel)).mode & 4095 } : {}
22633
+ ...rel === RUNNER_REL2 ? { mode: (0, import_node_fs11.lstatSync)((0, import_node_path11.join)(repo, rel)).mode & 4095 } : {}
22575
22634
  });
22576
22635
  }
22577
22636
  artifacts.push(...linkedArtifacts);
@@ -22643,37 +22702,37 @@ function inspectAgentHookStatus(repo) {
22643
22702
  }
22644
22703
 
22645
22704
  // src/state.ts
22646
- var import_node_fs11 = require("node:fs");
22647
- var import_node_path11 = require("node:path");
22705
+ var import_node_fs12 = require("node:fs");
22706
+ var import_node_path12 = require("node:path");
22648
22707
  var import_fast_glob2 = __toESM(require_out4(), 1);
22649
22708
  var STATE_REL = ".agents/.harness-state.json";
22650
22709
  function inside3(base, target) {
22651
- const rel = (0, import_node_path11.relative)(base, target);
22652
- return rel === "" || !rel.startsWith("..") && !(0, import_node_path11.isAbsolute)(rel);
22710
+ const rel = (0, import_node_path12.relative)(base, target);
22711
+ return rel === "" || !rel.startsWith("..") && !(0, import_node_path12.isAbsolute)(rel);
22653
22712
  }
22654
22713
  function resolveKnowledgePath(repo, knowledge) {
22655
- const base = knowledge.root === "repo" ? (0, import_node_path11.resolve)(repo) : (0, import_node_path11.resolve)(repo, ".agents");
22656
- const target = (0, import_node_path11.resolve)(base, knowledge.path);
22714
+ const base = knowledge.root === "repo" ? (0, import_node_path12.resolve)(repo) : (0, import_node_path12.resolve)(repo, ".agents");
22715
+ const target = (0, import_node_path12.resolve)(base, knowledge.path);
22657
22716
  if (!inside3(base, target)) throw new Error(`knowledge path escapes ${knowledge.root === "repo" ? "repository" : ".agents"}: ${knowledge.path}`);
22658
22717
  return target;
22659
22718
  }
22660
22719
  function hashPath(absPath) {
22661
- if (!(0, import_node_fs11.existsSync)(absPath)) return "(missing)";
22720
+ if (!(0, import_node_fs12.existsSync)(absPath)) return "(missing)";
22662
22721
  let stat;
22663
22722
  try {
22664
- stat = (0, import_node_fs11.statSync)(absPath);
22723
+ stat = (0, import_node_fs12.statSync)(absPath);
22665
22724
  } catch {
22666
22725
  return "(missing)";
22667
22726
  }
22668
22727
  if (stat.isFile()) return hashFile(absPath) ?? "(missing)";
22669
22728
  if (!stat.isDirectory()) return "(missing)";
22670
22729
  const files = import_fast_glob2.default.sync("**/*", { cwd: absPath, onlyFiles: true, dot: true, followSymbolicLinks: false }).sort();
22671
- const entries = files.map((path) => [path, hashFile((0, import_node_path11.join)(absPath, path)) ?? "(missing)"]);
22730
+ const entries = files.map((path) => [path, hashFile((0, import_node_path12.join)(absPath, path)) ?? "(missing)"]);
22672
22731
  return sha256(JSON.stringify(entries));
22673
22732
  }
22674
22733
  function sourceHashes(repo, paths) {
22675
22734
  const result = {};
22676
- for (const path of paths) result[path] = hashFile((0, import_node_path11.join)(repo, path)) ?? "(missing)";
22735
+ for (const path of paths) result[path] = hashFile((0, import_node_path12.join)(repo, path)) ?? "(missing)";
22677
22736
  return result;
22678
22737
  }
22679
22738
  function knowledgeKey(knowledge) {
@@ -22727,14 +22786,17 @@ function contextSnapshots(repo, manifest) {
22727
22786
  }
22728
22787
  return snapshots;
22729
22788
  }
22730
- function readState(repo) {
22731
- const raw = readText((0, import_node_path11.join)(repo, STATE_REL));
22732
- if (!raw) return null;
22789
+ function parseState2(raw) {
22733
22790
  const value = JSON.parse(raw);
22734
22791
  return { bindings: value.bindings ?? {}, reviews: value.reviews ?? {} };
22735
22792
  }
22793
+ function readState(repo) {
22794
+ const raw = readText((0, import_node_path12.join)(repo, STATE_REL));
22795
+ if (!raw) return null;
22796
+ return parseState2(raw);
22797
+ }
22736
22798
  function writeState(repo, state) {
22737
- writeText((0, import_node_path11.join)(repo, STATE_REL), JSON.stringify(state, null, 2) + "\n");
22799
+ writeText((0, import_node_path12.join)(repo, STATE_REL), JSON.stringify(state, null, 2) + "\n");
22738
22800
  }
22739
22801
  function changedSources(before, after) {
22740
22802
  return [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((path) => before[path] !== after[path]).sort();
@@ -22757,6 +22819,7 @@ function inspectContextFreshness(repo, manifest) {
22757
22819
  kind: snapshot.kind,
22758
22820
  target: snapshot.target,
22759
22821
  severity: "blocking",
22822
+ code: "source-missing",
22760
22823
  reason: "\u7ED1\u5B9A\u6E90\u6587\u4EF6\u7F3A\u5931\uFF0C\u4E0D\u80FD\u628A\u4E0A\u4E0B\u6587\u89C6\u4E3A\u5DF2\u590D\u6838",
22761
22824
  changedSources: missing
22762
22825
  });
@@ -22769,6 +22832,7 @@ function inspectContextFreshness(repo, manifest) {
22769
22832
  kind: snapshot.kind,
22770
22833
  target: snapshot.target,
22771
22834
  severity: "blocking",
22835
+ code: "authority-changed",
22772
22836
  reason: `authority \u5728\u590D\u6838\u540E\u4ECE ${review.authority} \u53D8\u4E3A ${expectedAuthority}`,
22773
22837
  changedSources: changedSources(review.sources, snapshot.sources)
22774
22838
  });
@@ -22781,6 +22845,7 @@ function inspectContextFreshness(repo, manifest) {
22781
22845
  kind: snapshot.kind,
22782
22846
  target: snapshot.target,
22783
22847
  severity: "blocking",
22848
+ code: "review-missing",
22784
22849
  reason: `\u5C1A\u672A\u8BB0\u5F55\u590D\u6838\uFF08authority: ${snapshot.authority}\uFF09`,
22785
22850
  changedSources: Object.keys(snapshot.sources).sort()
22786
22851
  });
@@ -22793,6 +22858,7 @@ function inspectContextFreshness(repo, manifest) {
22793
22858
  kind: snapshot.kind,
22794
22859
  target: snapshot.target,
22795
22860
  severity: "blocking",
22861
+ code: "content-changed",
22796
22862
  reason: "\u77E5\u8BC6\u5185\u5BB9\u5728\u590D\u6838\u540E\u53D1\u751F\u53D8\u5316\uFF0C\u5FC5\u987B\u91CD\u65B0\u8BB0\u5F55\u590D\u6838",
22797
22863
  changedSources: sources2
22798
22864
  });
@@ -22802,6 +22868,7 @@ function inspectContextFreshness(repo, manifest) {
22802
22868
  kind: snapshot.kind,
22803
22869
  target: snapshot.target,
22804
22870
  severity: "blocking",
22871
+ code: "sources-changed",
22805
22872
  reason: `\u7ED1\u5B9A\u6E90\u6587\u4EF6\u5728\u590D\u6838\u540E\u53D1\u751F\u53D8\u5316\uFF08authority: ${snapshot.authority}\uFF09`,
22806
22873
  changedSources: sources2
22807
22874
  });
@@ -22816,6 +22883,7 @@ function inspectContextFreshness(repo, manifest) {
22816
22883
  kind: snapshot.kind,
22817
22884
  target: snapshot.target,
22818
22885
  severity: "blocking",
22886
+ code: review.contentHash !== snapshot.contentHash ? "content-changed" : "sources-changed",
22819
22887
  reason: review.contentHash !== snapshot.contentHash ? "\u4E0A\u4E0B\u6587\u5185\u5BB9\u5728\u590D\u6838\u540E\u53D1\u751F\u53D8\u5316" : "\u7ED1\u5B9A\u6E90\u6587\u4EF6\u5728\u590D\u6838\u540E\u53D1\u751F\u53D8\u5316",
22820
22888
  changedSources: sources2
22821
22889
  });
@@ -22831,6 +22899,7 @@ function inspectContextFreshness(repo, manifest) {
22831
22899
  kind: snapshot.kind,
22832
22900
  target: snapshot.target,
22833
22901
  severity: "advisory",
22902
+ code: "legacy-baseline-changed",
22834
22903
  reason: "legacy freshness baseline changed; record a context review to make it durable",
22835
22904
  changedSources: sources
22836
22905
  });
@@ -22844,12 +22913,53 @@ function inspectContextFreshness(repo, manifest) {
22844
22913
  kind: review.kind,
22845
22914
  target: review.target,
22846
22915
  severity: "blocking",
22916
+ code: "orphan-review",
22847
22917
  reason: "orphan review: \u5DF2\u590D\u6838\u7684 knowledge \u4ECD\u5728 manifest \u4E2D\uFF0C\u4F46\u4E0D\u518D\u58F0\u660E binds/authority\uFF0C\u5DF2\u6709\u590D\u6838\u4E0D\u80FD\u9759\u9ED8\u6D88\u5931",
22848
22918
  changedSources: Object.keys(review.sources ?? {}).sort()
22849
22919
  });
22850
22920
  }
22851
22921
  return issues;
22852
22922
  }
22923
+ function repoRelative(path) {
22924
+ return import_node_path12.posix.normalize(path.split(import_node_path12.sep).join("/")).replace(/^\.\//, "").replace(/\/+$/, "");
22925
+ }
22926
+ function contextPaths(manifest, key) {
22927
+ const paths = [];
22928
+ for (const knowledge of manifest?.knowledge ?? []) {
22929
+ if (knowledgeKey(knowledge) !== key) continue;
22930
+ paths.push(repoRelative(knowledge.root === "repo" ? knowledge.path : `.agents/${knowledge.path}`));
22931
+ paths.push(...(knowledge.binds ?? []).map(repoRelative));
22932
+ }
22933
+ for (const module2 of manifest?.modules ?? []) {
22934
+ if (`module:${module2.name}` === key) paths.push(...(module2.entry ?? []).map(repoRelative));
22935
+ }
22936
+ return paths;
22937
+ }
22938
+ function contextDeclaration(manifest, key) {
22939
+ return JSON.stringify([
22940
+ ...(manifest?.knowledge ?? []).filter((knowledge) => knowledgeKey(knowledge) === key).map((knowledge) => ({ binds: knowledge.binds ?? [], authority: knowledge.authority ?? null })),
22941
+ ...(manifest?.modules ?? []).filter((module2) => `module:${module2.name}` === key).map(moduleContentHash)
22942
+ ]);
22943
+ }
22944
+ function contextReviewEvidence(state, issue) {
22945
+ const legacyKey = issue.kind === "knowledge" ? issue.target : issue.key;
22946
+ return JSON.stringify([state?.reviews?.[issue.key] ?? null, state?.bindings?.[legacyKey] ?? null]);
22947
+ }
22948
+ function inheritedContextKeys(issues, current, base, changedFiles) {
22949
+ const inherited = /* @__PURE__ */ new Set();
22950
+ if (!base.manifest) return inherited;
22951
+ const changed = changedFiles.map(repoRelative);
22952
+ const touches = (path) => changed.some((file) => file === path || file.startsWith(`${path}/`));
22953
+ for (const issue of issues) {
22954
+ if (issue.severity !== "blocking") continue;
22955
+ if (contextDeclaration(current.manifest, issue.key) !== contextDeclaration(base.manifest, issue.key)) continue;
22956
+ if (contextReviewEvidence(current.state, issue) !== contextReviewEvidence(base.state, issue)) continue;
22957
+ const paths = [...contextPaths(current.manifest, issue.key), ...issue.changedSources.map(repoRelative)];
22958
+ if (paths.some(touches)) continue;
22959
+ inherited.add(issue.key);
22960
+ }
22961
+ return inherited;
22962
+ }
22853
22963
  function recordContextReview(repo, manifest, opts) {
22854
22964
  if (!!opts.path === !!opts.module) throw new Error("\u53EA\u80FD\u6307\u5B9A\u4E00\u4E2A --path \u6216 --module");
22855
22965
  const reason = opts.reason?.trim();
@@ -22890,6 +23000,7 @@ var AGENTS_MAX_WORDS = 700;
22890
23000
  function doctorCmd(repo, opts = {}) {
22891
23001
  let problems = 0;
22892
23002
  const m = loadManifest(repo);
23003
+ const render = { harnessVersion: lockedHarnessVersion(repo) };
22893
23004
  info("1) Manifest validation");
22894
23005
  const issues = validateManifest(m);
22895
23006
  if (!issues.length) ok("schema looks good");
@@ -22949,18 +23060,18 @@ function doctorCmd(repo, opts = {}) {
22949
23060
  }
22950
23061
  info("\n2) Referenced paths");
22951
23062
  const checkPath = (rel, label) => {
22952
- if ((0, import_node_fs12.existsSync)((0, import_node_path12.join)(repo, ".agents", rel))) ok(`${label}: ${rel}`);
23063
+ if ((0, import_node_fs13.existsSync)((0, import_node_path13.join)(repo, ".agents", rel))) ok(`${label}: ${rel}`);
22953
23064
  else {
22954
23065
  err(`${label} missing: .agents/${rel}`);
22955
23066
  problems++;
22956
23067
  }
22957
23068
  };
22958
23069
  const checkRepoPath = (rel, label, wantFile = false) => {
22959
- const abs = (0, import_node_path12.join)(repo, rel);
22960
- if (!(0, import_node_fs12.existsSync)(abs)) {
23070
+ const abs = (0, import_node_path13.join)(repo, rel);
23071
+ if (!(0, import_node_fs13.existsSync)(abs)) {
22961
23072
  err(`${label} points at a missing path: ${rel}`);
22962
23073
  problems++;
22963
- } else if (wantFile && (0, import_node_fs12.statSync)(abs).isDirectory()) {
23074
+ } else if (wantFile && (0, import_node_fs13.statSync)(abs).isDirectory()) {
22964
23075
  warn(`${label}: ${rel} is a directory \u2014 entry/binds should be a file (freshness hashes file content)`);
22965
23076
  } else ok(`${label}: ${rel}`);
22966
23077
  };
@@ -22987,7 +23098,7 @@ function doctorCmd(repo, opts = {}) {
22987
23098
  problems++;
22988
23099
  continue;
22989
23100
  }
22990
- if ((0, import_node_fs12.existsSync)(knowledgePath)) ok(`knowledge: ${k.path}`);
23101
+ if ((0, import_node_fs13.existsSync)(knowledgePath)) ok(`knowledge: ${k.path}`);
22991
23102
  else {
22992
23103
  err(`knowledge missing: ${k.root === "repo" ? "" : ".agents/"}${k.path}`);
22993
23104
  problems++;
@@ -23002,11 +23113,11 @@ function doctorCmd(repo, opts = {}) {
23002
23113
  for (const mod of m.modules ?? []) {
23003
23114
  if (!mod.playbook) continue;
23004
23115
  const candidates = [
23005
- m.playbooks?.dir ? (0, import_node_path12.join)(repo, ".agents", m.playbooks.dir, mod.playbook) : "",
23006
- (0, import_node_path12.join)(repo, ".agents", mod.playbook),
23007
- (0, import_node_path12.join)(repo, mod.playbook)
23116
+ m.playbooks?.dir ? (0, import_node_path13.join)(repo, ".agents", m.playbooks.dir, mod.playbook) : "",
23117
+ (0, import_node_path13.join)(repo, ".agents", mod.playbook),
23118
+ (0, import_node_path13.join)(repo, mod.playbook)
23008
23119
  ].filter(Boolean);
23009
- if (candidates.some((c) => (0, import_node_fs12.existsSync)(c))) ok(`module ${mod.name} playbook: ${mod.playbook}`);
23120
+ if (candidates.some((c) => (0, import_node_fs13.existsSync)(c))) ok(`module ${mod.name} playbook: ${mod.playbook}`);
23010
23121
  else {
23011
23122
  err(`module ${mod.name} playbook missing: ${mod.playbook} (looked in ${m.playbooks?.dir ? `.agents/${m.playbooks.dir}/, ` : ""}.agents/, repo root)`);
23012
23123
  problems++;
@@ -23014,7 +23125,7 @@ function doctorCmd(repo, opts = {}) {
23014
23125
  }
23015
23126
  info("\n3) Generated files drift");
23016
23127
  try {
23017
- for (const inspection of inspectManagedFiles(repo, renderTargets(m))) {
23128
+ for (const inspection of inspectManagedFiles(repo, renderTargets(m, render))) {
23018
23129
  if (inspection.kind === "missing") warn(`${inspection.relativePath} not generated yet (run \`harness-kit sync\`)`);
23019
23130
  else if (!inspection.satisfiesDesired) {
23020
23131
  err(`${inspection.relativePath} drifted from manifest (run \`harness-kit sync\`)`);
@@ -23061,7 +23172,7 @@ function doctorCmd(repo, opts = {}) {
23061
23172
  } else info(" details: `harness-kit doctor --details`");
23062
23173
  }
23063
23174
  info("\n6) AGENTS.md size budget (must stay short \u2014 agents read it every session)");
23064
- const agents = renderAgentsMd(m);
23175
+ const agents = renderAgentsMd(m, render);
23065
23176
  const nLines = agents.split("\n").length;
23066
23177
  const nWords = agents.trim().split(/\s+/).length;
23067
23178
  if (nLines > AGENTS_MAX_LINES || nWords > AGENTS_MAX_WORDS) {
@@ -23075,13 +23186,13 @@ function doctorCmd(repo, opts = {}) {
23075
23186
  const hooks = inspectAgentHookStatus(repo);
23076
23187
  const configuredAgents = hooks.configuredAgents.length ? hooks.configuredAgents.join(", ") : "none";
23077
23188
  if (hooks.state === "active") {
23078
- ok(`ACTIVE \u2014 ${hooks.evidenceAgent} produced current run-checks + verify evidence; configured: ${configuredAgents}`);
23189
+ ok(`ACTIVE \u2014 ${hooks.evidenceAgent} observed on Stop; configured: ${configuredAgents} (optional intercept; task gate is deliver)`);
23079
23190
  } else if (hooks.state === "configured") {
23080
- warn(`CONFIGURED \u2014 ${configuredAgents}; start and finish one fresh Agent session to prove the hooks actually execute`);
23191
+ warn(`CONFIGURED \u2014 ${configuredAgents}; optional intercept not yet observed. Task acceptance: harness-kit deliver`);
23081
23192
  } else {
23082
23193
  warn(`DEGRADED \u2014 configured: ${configuredAgents}; ${hooks.issues.join("; ")}`);
23083
23194
  }
23084
- const guidance = buildHarnessGuidance({ manifest: m, hooks });
23195
+ const guidance = buildHarnessGuidance({ manifest: m, hooks, cli: repoHarnessInvocation(repo) });
23085
23196
  const visibleActions = opts.details ? guidance.nextActions : guidance.nextActions.filter((action) => action.priority === "required");
23086
23197
  info("\nNEXT ACTIONS");
23087
23198
  if (!visibleActions.length) ok("nothing required now");
@@ -23111,10 +23222,178 @@ function doctorCmd(repo, opts = {}) {
23111
23222
  // src/commands/verify.ts
23112
23223
  var import_node_child_process5 = require("node:child_process");
23113
23224
 
23225
+ // src/delivery.ts
23226
+ var import_node_crypto7 = require("node:crypto");
23227
+ var import_node_fs14 = require("node:fs");
23228
+ var import_node_path14 = require("node:path");
23229
+ var import_yaml3 = __toESM(require_dist(), 1);
23230
+ function canonicalTarget2(repo) {
23231
+ try {
23232
+ return (0, import_node_fs14.realpathSync)(repo);
23233
+ } catch {
23234
+ return (0, import_node_path14.resolve)(repo);
23235
+ }
23236
+ }
23237
+ function taskStateDir(repo) {
23238
+ return (0, import_node_path14.join)(gitAdminDir(repo), "harness-kit", "task");
23239
+ }
23240
+ function taskPath(repo) {
23241
+ return (0, import_node_path14.join)(taskStateDir(repo), `current-${sha256(canonicalTarget2(repo)).slice(0, 24)}.json`);
23242
+ }
23243
+ function writePrivateJson2(path, value) {
23244
+ (0, import_node_fs14.mkdirSync)((0, import_node_path14.dirname)(path), { recursive: true });
23245
+ const temp = `${path}.${process.pid}.${(0, import_node_crypto7.randomUUID)()}.tmp`;
23246
+ try {
23247
+ (0, import_node_fs14.writeFileSync)(temp, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
23248
+ (0, import_node_fs14.renameSync)(temp, path);
23249
+ (0, import_node_fs14.chmodSync)(path, 384);
23250
+ } catch (error) {
23251
+ try {
23252
+ (0, import_node_fs14.unlinkSync)(temp);
23253
+ } catch {
23254
+ }
23255
+ throw error;
23256
+ }
23257
+ }
23258
+ function readTaskRecord(repoInput) {
23259
+ const repo = gitRoot(repoInput);
23260
+ const raw = readText(taskPath(repo));
23261
+ if (raw === null) return null;
23262
+ try {
23263
+ const value = JSON.parse(raw);
23264
+ if (value?.schema !== "ai-harness/task/v1" || typeof value.baseSha !== "string" || !value.baseSha) return null;
23265
+ return value;
23266
+ } catch {
23267
+ return null;
23268
+ }
23269
+ }
23270
+ function startTaskRecord(args) {
23271
+ const repo = gitRoot(args.repo);
23272
+ const head = collectChanges(repo, "HEAD", { mode: "exact" }).head;
23273
+ const baseSha = args.baseSha ?? head;
23274
+ if (!baseSha) throw new Error("cannot start task: repository has no HEAD commit and no --base was provided");
23275
+ collectChanges(repo, baseSha, { mode: "exact" });
23276
+ const record = {
23277
+ schema: "ai-harness/task/v1",
23278
+ baseSha,
23279
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
23280
+ ...args.note?.trim() ? { note: args.note.trim() } : {},
23281
+ ...args.hostSessionId ? { hostSessionId: args.hostSessionId } : {},
23282
+ ...args.agent ? { agent: args.agent } : {}
23283
+ };
23284
+ writePrivateJson2(taskPath(repo), record);
23285
+ return record;
23286
+ }
23287
+ function resolveChangeScope(repoInput, opts = {}) {
23288
+ const repo = gitRoot(repoInput);
23289
+ if (opts.base !== void 0) {
23290
+ const changes2 = collectChanges(repo, opts.base, { mode: "exact" });
23291
+ return { kind: "explicit-base", base: opts.base, mode: "exact", changes: changes2, task: readTaskRecord(repo) };
23292
+ }
23293
+ const task = readTaskRecord(repo);
23294
+ if (task) {
23295
+ const changes2 = collectChanges(repo, task.baseSha, { mode: "exact" });
23296
+ return { kind: "task", base: task.baseSha, mode: "exact", changes: changes2, task };
23297
+ }
23298
+ const changes = collectChanges(repo, "HEAD", { mode: "exact" });
23299
+ return { kind: "worktree", base: "HEAD", mode: "exact", changes, task: null };
23300
+ }
23301
+ function stampFromEvidence(repo, session) {
23302
+ if (!session?.lastEvidence) {
23303
+ return { status: "missing", found: false, stale: false, valid: false, reason: "no delivery evidence recorded" };
23304
+ }
23305
+ const evidence = session.lastEvidence;
23306
+ const freshness = inspectValidationEvidenceFreshness(repo, evidence);
23307
+ const runChecksValid = (evidence.runChecksStatus !== void 0 ? evidence.runChecksStatus !== "not-verified" : evidence.ok && evidence.status !== "not-verified") && !freshness.stale;
23308
+ const verifyPassed = evidence.verifyPassed === true;
23309
+ const valid = runChecksValid && verifyPassed && !freshness.error;
23310
+ let status;
23311
+ if (freshness.stale || freshness.error) status = "stale";
23312
+ else if (evidence.status === "no-change" && verifyPassed) status = "no-change";
23313
+ else if (valid) status = "accepted";
23314
+ else status = "needs-work";
23315
+ return {
23316
+ status,
23317
+ found: true,
23318
+ fingerprint: evidence.fingerprint,
23319
+ planFingerprint: evidence.planFingerprint,
23320
+ runChecksStatus: evidence.runChecksStatus ?? evidence.status,
23321
+ verifyPassed: evidence.verifyPassed,
23322
+ scopeBase: evidence.resolvedBase ?? evidence.requestedBase,
23323
+ createdAt: evidence.createdAt,
23324
+ session: session.token,
23325
+ stale: freshness.stale || !!freshness.error,
23326
+ valid,
23327
+ reason: freshness.error || void 0
23328
+ };
23329
+ }
23330
+ function inspectDeliveryStamp(repoInput) {
23331
+ const repo = gitRoot(repoInput);
23332
+ try {
23333
+ return stampFromEvidence(repo, readLatestValidationSession(repo));
23334
+ } catch (error) {
23335
+ return {
23336
+ status: "missing",
23337
+ found: false,
23338
+ stale: false,
23339
+ valid: false,
23340
+ reason: `cannot read delivery stamp: ${error.message}`
23341
+ };
23342
+ }
23343
+ }
23344
+ function stampCoversScope(repoInput, scope) {
23345
+ const stamp = inspectDeliveryStamp(repoInput);
23346
+ if (!stamp.found || stamp.stale || !stamp.valid) return false;
23347
+ if (scope.changes.files.length === 0) return stamp.status === "no-change" || stamp.status === "accepted";
23348
+ return stamp.status === "accepted" && stamp.fingerprint === scope.changes.fingerprint;
23349
+ }
23350
+ function inheritedContextIssueKeys(repo, manifest, issues, base) {
23351
+ if (!issues.some((issue) => issue.severity === "blocking")) return /* @__PURE__ */ new Set();
23352
+ const changes = collectChanges(repo, base, { mode: "exact" });
23353
+ if (!changes.resolvedBase) return /* @__PURE__ */ new Set();
23354
+ const manifestText = readFileAtCommit(repo, changes.resolvedBase, MANIFEST_REL);
23355
+ if (manifestText === null) return /* @__PURE__ */ new Set();
23356
+ const parsed = import_yaml3.default.parse(manifestText);
23357
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return /* @__PURE__ */ new Set();
23358
+ const stateText = readFileAtCommit(repo, changes.resolvedBase, STATE_REL);
23359
+ const baseState = stateText ? parseState2(stateText) : null;
23360
+ return inheritedContextKeys(
23361
+ issues,
23362
+ { manifest, state: readState(repo) },
23363
+ { manifest: parsed, state: baseState },
23364
+ changes.files
23365
+ );
23366
+ }
23367
+ function locateHarnessTargets(repoInput) {
23368
+ const repo = (0, import_node_path14.resolve)(repoInput);
23369
+ if ((0, import_node_fs14.existsSync)((0, import_node_path14.join)(repo, MANIFEST_REL))) return { adopted: true, enclosing: null, nested: [] };
23370
+ let root;
23371
+ try {
23372
+ root = canonicalTarget2(gitRoot(repo));
23373
+ } catch {
23374
+ return { adopted: false, enclosing: null, nested: [] };
23375
+ }
23376
+ let enclosing = null;
23377
+ for (let dir = canonicalTarget2(repo); dir !== root && (0, import_node_path14.dirname)(dir) !== dir; ) {
23378
+ dir = (0, import_node_path14.dirname)(dir);
23379
+ if ((0, import_node_fs14.existsSync)((0, import_node_path14.join)(dir, MANIFEST_REL))) {
23380
+ enclosing = dir;
23381
+ break;
23382
+ }
23383
+ }
23384
+ let nested = [];
23385
+ try {
23386
+ const suffix = `/${MANIFEST_REL}`;
23387
+ nested = listWorktreeFiles(repo, `**/${MANIFEST_REL}`).filter((path) => path.endsWith(suffix)).map((path) => (0, import_node_path14.join)(repo, path.slice(0, -suffix.length))).sort();
23388
+ } catch {
23389
+ }
23390
+ return { adopted: false, enclosing, nested };
23391
+ }
23392
+
23114
23393
  // src/enforce.ts
23115
23394
  var import_fast_glob4 = __toESM(require_out4(), 1);
23116
- var import_node_fs13 = require("node:fs");
23117
- var import_node_path13 = require("node:path");
23395
+ var import_node_fs15 = require("node:fs");
23396
+ var import_node_path15 = require("node:path");
23118
23397
  var DEFAULT_IGNORE = ["**/node_modules/**", "**/.git/**", "**/dist/**", "**/.agents/map/**"];
23119
23398
  function runEnforcement(repo, invId, e) {
23120
23399
  const globs = e.path_glob?.length ? e.path_glob : ["**/*"];
@@ -23131,7 +23410,7 @@ function runEnforcement(repo, invId, e) {
23131
23410
  for (const rel of files) {
23132
23411
  let content;
23133
23412
  try {
23134
- content = (0, import_node_fs13.readFileSync)((0, import_node_path13.join)(repo, rel), "utf8");
23413
+ content = (0, import_node_fs15.readFileSync)((0, import_node_path15.join)(repo, rel), "utf8");
23135
23414
  } catch {
23136
23415
  continue;
23137
23416
  }
@@ -23222,7 +23501,7 @@ function verifyInternal(repo, opts) {
23222
23501
  const messages = [];
23223
23502
  let manifestErrors = [];
23224
23503
  const hooks = safeInspectAgentHookStatus(repo);
23225
- const guidance = buildHarnessGuidance({ manifest, hooks });
23504
+ const guidance = buildHarnessGuidance({ manifest, hooks, cli: repoHarnessInvocation(repo) });
23226
23505
  const gaps = guidance.gapDetails.map((gap2) => gap2.legacyText);
23227
23506
  const emit = (level, text) => {
23228
23507
  messages.push({ level, text });
@@ -23295,7 +23574,7 @@ verify: FAILED (${manifestErrors.length} manifest problem(s))`);
23295
23574
  }
23296
23575
  emit("info", "1) Generated files in sync");
23297
23576
  try {
23298
- for (const inspection of inspectManagedFiles(repo, renderTargets(manifest))) {
23577
+ for (const inspection of inspectManagedFiles(repo, renderTargets(manifest, { harnessVersion: lockedHarnessVersion(repo) }))) {
23299
23578
  if (inspection.kind === "missing") {
23300
23579
  emit("error", `${inspection.relativePath} missing (run \`harness-kit sync\`)`);
23301
23580
  failures++;
@@ -23311,14 +23590,29 @@ verify: FAILED (${manifestErrors.length} manifest problem(s))`);
23311
23590
  }
23312
23591
  emit("info", "\n2) Context freshness");
23313
23592
  try {
23314
- for (const issue of inspectContextFreshness(repo, manifest)) {
23315
- context.push(issue);
23593
+ const issues = inspectContextFreshness(repo, manifest);
23594
+ let inherited = /* @__PURE__ */ new Set();
23595
+ if (opts.contextBase !== void 0) {
23596
+ try {
23597
+ inherited = inheritedContextIssueKeys(repo, manifest, issues, opts.contextBase);
23598
+ } catch (error) {
23599
+ emit("warn", `cannot compare context freshness with task base ${opts.contextBase}; treating it as task-scoped (${error.message})`);
23600
+ }
23601
+ }
23602
+ for (const issue of issues) {
23316
23603
  const changed = issue.changedSources.length ? ` -> ${issue.changedSources.join(", ")}` : "";
23317
23604
  const message = `${issue.key}: ${issue.reason}${changed}`;
23318
- if (issue.severity === "blocking") {
23605
+ if (issue.severity === "blocking" && inherited.has(issue.key)) {
23606
+ context.push({ ...issue, inherited: true });
23607
+ emit("warn", `${message} (inherited: already stale on task base ${opts.contextBase}; not introduced by this task)`);
23608
+ } else if (issue.severity === "blocking") {
23609
+ context.push(issue);
23319
23610
  failures++;
23320
23611
  emit("error", message);
23321
- } else emit("warn", message);
23612
+ } else {
23613
+ context.push(issue);
23614
+ emit("warn", message);
23615
+ }
23322
23616
  }
23323
23617
  } catch (error) {
23324
23618
  failures++;
@@ -23406,9 +23700,9 @@ verify: FAILED (${manifestErrors.length} manifest problem(s))`);
23406
23700
  emit("info", "\n5) Agent lifecycle hooks");
23407
23701
  const configuredAgents = hooks.configuredAgents.length ? hooks.configuredAgents.join(", ") : "none";
23408
23702
  if (hooks.state === "active")
23409
- emit("ok", `ACTIVE \u2014 ${hooks.evidenceAgent} produced current run-checks + verify evidence; configured: ${configuredAgents}`);
23703
+ emit("ok", `ACTIVE \u2014 ${hooks.evidenceAgent} observed on Stop; configured: ${configuredAgents} (optional intercept; task gate is deliver)`);
23410
23704
  else if (hooks.state === "configured")
23411
- emit("warn", `CONFIGURED \u2014 ${configuredAgents}; a fresh Agent session has not produced current Stop evidence yet`);
23705
+ emit("warn", `CONFIGURED \u2014 ${configuredAgents}; optional intercept not yet observed. Task acceptance: harness-kit deliver`);
23412
23706
  else emit("warn", `DEGRADED \u2014 configured: ${configuredAgents}; ${hooks.issues.join("; ")}`);
23413
23707
  emit("info", "\n6) Declared verification boundaries");
23414
23708
  if (!guidance.gapSummary.total) emit("ok", "no declared verification boundaries");
@@ -23519,19 +23813,19 @@ function acceptContractCmd(repo, id) {
23519
23813
  }
23520
23814
 
23521
23815
  // src/skill.ts
23522
- var import_node_fs14 = require("node:fs");
23523
- var import_node_path14 = require("node:path");
23816
+ var import_node_fs16 = require("node:fs");
23817
+ var import_node_path16 = require("node:path");
23524
23818
  var import_node_url = require("node:url");
23525
23819
  var import_meta = {};
23526
23820
  function moduleDir() {
23527
23821
  if (typeof __dirname !== "undefined" && __dirname) return __dirname;
23528
- return (0, import_node_path14.dirname)((0, import_node_url.fileURLToPath)(import_meta.url));
23822
+ return (0, import_node_path16.dirname)((0, import_node_url.fileURLToPath)(import_meta.url));
23529
23823
  }
23530
23824
  var HERE = moduleDir();
23531
23825
  function resolveSkill(skillRel) {
23532
- for (const up of [".", "..", (0, import_node_path14.join)("..", "..")]) {
23533
- const p = (0, import_node_path14.join)(HERE, up, skillRel);
23534
- if ((0, import_node_fs14.existsSync)(p)) return p;
23826
+ for (const up of [".", "..", (0, import_node_path16.join)("..", "..")]) {
23827
+ const p = (0, import_node_path16.join)(HERE, up, skillRel);
23828
+ if ((0, import_node_fs16.existsSync)(p)) return p;
23535
23829
  }
23536
23830
  return null;
23537
23831
  }
@@ -23542,7 +23836,7 @@ function printSkill(skillRel, meta = "") {
23542
23836
  return 1;
23543
23837
  }
23544
23838
  if (meta) process.stdout.write(meta);
23545
- process.stdout.write((0, import_node_fs14.readFileSync)(p, "utf8"));
23839
+ process.stdout.write((0, import_node_fs16.readFileSync)(p, "utf8"));
23546
23840
  return 0;
23547
23841
  }
23548
23842
 
@@ -23550,10 +23844,13 @@ function printSkill(skillRel, meta = "") {
23550
23844
  var SKILL_REL = "skills/harness-check-loop/SKILL.md";
23551
23845
  var META = `<!-- harness-kit check-loop -->
23552
23846
  You are an AI agent implementing a requirement or fixing a bug in the CURRENT repo.
23553
- Follow the loop below. Run every harness-kit command through
23554
- \`npx -y @erzhe/harness-kit@latest <cmd>\` unless a local build is available.
23555
- The lifecycle hook records the SessionStart base, then runs \`run-checks + verify\` whenever you try to finish.
23556
- Use \`evidence\` to inspect the durable final result.
23847
+ Follow the loop below. Run every harness-kit command through the pinned
23848
+ \`npx -y @erzhe/harness-kit@<version from .agents/harness.lock.json> <cmd>\`
23849
+ (the "Harness CLI" line in AGENTS.md; \`@latest\` only without a lock) unless a
23850
+ local build is available. A bare \`harness-kit\` is usually not on PATH.
23851
+ Primary finish gate: \`harness-kit deliver\` (scope \u2192 run-checks + verify \u2192 stamp).
23852
+ Optional Stop hooks only check that stamp; they must not demand a new session.
23853
+ Use \`evidence\` to inspect the durable stamp.
23557
23854
 
23558
23855
  ---
23559
23856
 
@@ -23598,7 +23895,7 @@ function evidenceCmd(repo, opts = {}) {
23598
23895
  }
23599
23896
  const hooks = safeHookStatus(repo);
23600
23897
  if (!session?.lastEvidence) {
23601
- const guidance2 = buildHarnessGuidance({ hooks, evidence: { found: false } });
23898
+ const guidance2 = buildHarnessGuidance({ hooks, evidence: { found: false }, cli: repoHarnessInvocation(repo) });
23602
23899
  if (opts.json) {
23603
23900
  process.stdout.write(
23604
23901
  JSON.stringify(
@@ -23630,14 +23927,17 @@ function evidenceCmd(repo, opts = {}) {
23630
23927
  const valid = runChecksValid && evidence.verifyPassed === true;
23631
23928
  const hookConfigurationCurrent = session.agent !== "manual" && !!session.hookConfigFingerprint && agentHookConfigurationFingerprint(repo, session.agent) === session.hookConfigFingerprint;
23632
23929
  const hookActive = valid && hookConfigurationCurrent;
23930
+ const stamp = inspectDeliveryStamp(repo);
23633
23931
  const guidance = buildHarnessGuidance({
23634
23932
  hooks,
23635
- evidence: { found: true, stale, runChecksValid, verifyPassed: evidence.verifyPassed, valid }
23933
+ evidence: { found: true, stale, runChecksValid, verifyPassed: evidence.verifyPassed, valid },
23934
+ cli: repoHarnessInvocation(repo)
23636
23935
  });
23637
23936
  const result = {
23638
23937
  ...body,
23639
23938
  runChecksValid,
23640
23939
  valid,
23940
+ stamp,
23641
23941
  hookActive,
23642
23942
  hookConfigurationCurrent,
23643
23943
  stale,
@@ -23653,16 +23953,16 @@ function evidenceCmd(repo, opts = {}) {
23653
23953
  process.stdout.write(JSON.stringify(result, null, 2) + "\n");
23654
23954
  return valid ? 0 : 1;
23655
23955
  }
23656
- if (valid) ok(evidence.status);
23657
- else if (stale) err("stale evidence \u2014 the change no longer matches this record");
23658
- else if (evidence.verifyPassed !== true) err("delivery evidence incomplete \u2014 matching verify result is missing or failed");
23956
+ if (valid) ok(`stamp: ${stamp.status}`);
23957
+ else if (stale) err("stale stamp \u2014 the change no longer matches this record");
23958
+ else if (evidence.verifyPassed !== true) err("delivery stamp incomplete \u2014 matching verify result is missing or failed");
23659
23959
  else err(evidence.status);
23660
23960
  info(`session: ${session.token}`);
23661
23961
  info(`agent: ${session.agent}`);
23662
- if (session.agent === "manual") warn("manual evidence does not prove that an installed lifecycle hook executed");
23962
+ if (session.agent === "manual") info("stamp source: deliver/manual (not a lifecycle hook proof)");
23663
23963
  info(`base: ${evidence.requestedBase} -> ${evidence.resolvedBase ?? "empty tree"}`);
23664
23964
  info(`fingerprint: ${evidence.fingerprint}`);
23665
- info(`dirty at SessionStart: ${session.initialDirty.length ? session.initialDirty.join(", ") : "(none)"}`);
23965
+ if (session.initialDirty.length) info(`dirty at task/session start: ${session.initialDirty.join(", ")}`);
23666
23966
  if (evidence.verifyPassed !== void 0) info(`verify: ${evidence.verifyPassed ? "passed" : "failed"}`);
23667
23967
  else err("verify: no matching result was recorded");
23668
23968
  if (freshness.error) err(`cannot refresh current validation plan: ${freshness.error}`);
@@ -23676,15 +23976,23 @@ function evidenceCmd(repo, opts = {}) {
23676
23976
  info("errors:");
23677
23977
  for (const message of evidence.errors) err(message);
23678
23978
  }
23979
+ if (hooks.configuredAgents.length) {
23980
+ info(`session intercept: ${hooks.state} (configured: ${hooks.configuredAgents.join(",")})`);
23981
+ } else {
23982
+ info("session intercept: none (cooperative deliver only)");
23983
+ }
23679
23984
  const requiredActions = guidance.nextActions.filter((action) => action.priority === "required");
23680
23985
  printNextActions(requiredActions);
23681
- if (requiredActions.length) warn(`Harness readiness: INCOMPLETE (${requiredActions.length} required action(s) above)`);
23682
- else ok("Harness readiness: READY");
23986
+ if (!valid) warn(`Delivery stamp: NOT READY (${requiredActions.length} required action(s) above)`);
23987
+ else ok("Delivery stamp: READY");
23683
23988
  return valid ? 0 : 1;
23684
23989
  }
23685
23990
 
23686
23991
  // src/commands/hook-event.ts
23687
- var import_node_fs15 = require("node:fs");
23992
+ var import_node_fs17 = require("node:fs");
23993
+
23994
+ // src/commands/deliver.ts
23995
+ var import_node_path17 = require("node:path");
23688
23996
 
23689
23997
  // src/commands/run-checks.ts
23690
23998
  var import_node_child_process6 = require("node:child_process");
@@ -23699,11 +24007,12 @@ function isWaivableGap(gap2) {
23699
24007
  }
23700
24008
  function runOne(repo, cmd, timeoutMs) {
23701
24009
  const started = Date.now();
24010
+ const timeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.max(1, timeoutMs) : void 0;
23702
24011
  const r = (0, import_node_child_process6.spawnSync)(cmd, {
23703
24012
  cwd: repo,
23704
24013
  shell: true,
23705
24014
  encoding: "utf8",
23706
- timeout: Math.max(1, timeoutMs),
24015
+ ...timeout !== void 0 ? { timeout } : {},
23707
24016
  maxBuffer: 32 * 1024 * 1024
23708
24017
  });
23709
24018
  const out = `${r.stdout ?? ""}${r.stderr ?? ""}${r.error ? `
@@ -23810,9 +24119,9 @@ function fallbackChanges(base) {
23810
24119
  function runChecksCmd(repo, opts) {
23811
24120
  const errors = [];
23812
24121
  let session = null;
23813
- const implicitManualBase = !opts.session && opts.base === void 0;
24122
+ const implicitManualBase = !opts.session && opts.base === void 0 && !opts.allowEmptyAsNoChange;
23814
24123
  let base = opts.base ?? "HEAD";
23815
- let mode = "merge-base";
24124
+ let mode = opts.mode ?? "merge-base";
23816
24125
  if (opts.session) {
23817
24126
  try {
23818
24127
  session = readValidationSession(repo, opts.session);
@@ -23905,19 +24214,20 @@ function runChecksCmd(repo, opts) {
23905
24214
  const skipped = [];
23906
24215
  const checks = [];
23907
24216
  const capabilities = manifest?.capabilities ?? {};
23908
- const checkDeadline = Date.now() + CHECK_BUDGET_MS;
24217
+ const unlimitedBudget = opts.budgetMs === 0;
24218
+ const checkDeadline = unlimitedBudget ? Number.POSITIVE_INFINITY : Date.now() + (opts.budgetMs !== void 0 && opts.budgetMs > 0 ? opts.budgetMs : CHECK_BUDGET_MS);
23909
24219
  if (!errors.length) {
23910
24220
  for (const check of plan.checks) {
23911
24221
  const remainingMs = checkDeadline - Date.now();
23912
- if (remainingMs <= 0) {
23913
- const reason = "run-checks \u7684 7 \u5206\u949F\u603B\u68C0\u67E5\u9884\u7B97\u5DF2\u8017\u5C3D";
24222
+ if (!unlimitedBudget && remainingMs <= 0) {
24223
+ const reason = "run-checks \u7684\u68C0\u67E5\u603B\u9884\u7B97\u5DF2\u8017\u5C3D\uFF1B\u590D\u6742\u4EFB\u52A1\u8BF7\u7528 harness-kit deliver\uFF08\u65E0\u7D27\u603B\u9884\u7B97\uFF09";
23914
24224
  skipped.push({ id: check.id, reason });
23915
24225
  checks.push({ id: check.id, status: "not-run", exitCode: 1, durationMs: 0 });
23916
24226
  plan.gaps.push({
23917
24227
  kind: "selected-check-not-run",
23918
24228
  where: check.id,
23919
24229
  why: reason,
23920
- suggestion: "\u62C6\u5206\u5FEB\u901F\u81EA\u52A8\u95E8\u7981\uFF1B\u8D85\u957F\u9A8C\u8BC1\u653E\u5230 routing/manual GAP \u6216\u72EC\u7ACB CI",
24230
+ suggestion: "\u4F7F\u7528 harness-kit deliver \u505A\u4EFB\u52A1\u9A8C\u6536\uFF0C\u6216\u62C6\u5206\u5FEB\u901F\u81EA\u52A8\u95E8\u7981",
23921
24231
  severity: "blocking"
23922
24232
  });
23923
24233
  continue;
@@ -23936,7 +24246,7 @@ function runChecksCmd(repo, opts) {
23936
24246
  });
23937
24247
  continue;
23938
24248
  }
23939
- const result = runOne(repo, cap.run, remainingMs);
24249
+ const result = runOne(repo, cap.run, unlimitedBudget ? 0 : remainingMs);
23940
24250
  checks.push({ id: check.id, status: result.ok ? "passed" : "failed", exitCode: result.code, durationMs: result.durationMs });
23941
24251
  if (result.ok) passed.push(check.id);
23942
24252
  else failed.push({ id: check.id, cmd: cap.run, code: result.code, logTail: result.logTail, durationMs: result.durationMs });
@@ -23974,6 +24284,327 @@ function runChecksCmd(repo, opts) {
23974
24284
  return report.ok ? 0 : 1;
23975
24285
  }
23976
24286
 
24287
+ // src/commands/deliver.ts
24288
+ var DELIVER_NOT_ADOPTED_EXIT_CODE = 3;
24289
+ function captureStdout(fn) {
24290
+ const chunks = [];
24291
+ const original = process.stdout.write.bind(process.stdout);
24292
+ process.stdout.write = (chunk) => {
24293
+ chunks.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));
24294
+ return true;
24295
+ };
24296
+ let code = 1;
24297
+ try {
24298
+ code = fn();
24299
+ } catch (error) {
24300
+ chunks.push(`command threw: ${error.message}
24301
+ `);
24302
+ } finally {
24303
+ process.stdout.write = original;
24304
+ }
24305
+ return { code, output: chunks.join("") };
24306
+ }
24307
+ function parseRunReport(output) {
24308
+ try {
24309
+ return JSON.parse(output);
24310
+ } catch {
24311
+ return null;
24312
+ }
24313
+ }
24314
+ function parseVerifyReport(output) {
24315
+ try {
24316
+ const report = JSON.parse(output);
24317
+ return report?.schema === "ai-harness/verify-report/v1" ? report : null;
24318
+ } catch {
24319
+ return null;
24320
+ }
24321
+ }
24322
+ function shellArg(value) {
24323
+ return /^[A-Za-z0-9_./@:+=,-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
24324
+ }
24325
+ function nextActions(status, report, cli) {
24326
+ if (status === "accepted" || status === "no-change") return [];
24327
+ const next = [];
24328
+ if (report) {
24329
+ for (const failure of report.failed.slice(0, 5)) {
24330
+ next.push(`fix failing check "${failure.id}": ${failure.cmd}`);
24331
+ }
24332
+ for (const gap2 of report.gaps.filter((g) => g.severity === "blocking").slice(0, 5)) {
24333
+ next.push(gap2.suggestion);
24334
+ }
24335
+ for (const skipped of report.skipped.slice(0, 3)) {
24336
+ next.push(`resolve skipped check ${skipped.id}: ${skipped.reason}`);
24337
+ }
24338
+ }
24339
+ next.push(`re-run: ${cli} deliver --repo .`);
24340
+ return next;
24341
+ }
24342
+ function inheritedContextActions(issues, base, cli) {
24343
+ return issues.map((issue) => {
24344
+ const changed = issue.changedSources.length ? ` (${issue.changedSources.join(", ")})` : "";
24345
+ const action = {
24346
+ id: `refresh-inherited-context:${issue.key}`,
24347
+ priority: "recommended",
24348
+ owner: "agent",
24349
+ when: "harness-maintenance",
24350
+ title: `Refresh inherited context review: ${issue.target}`,
24351
+ reason: `${issue.reason}${changed}. It was already stale on task base ${base} and this task did not touch its inputs, so it does not block this delivery. Refresh it in a dedicated Harness-maintenance change, not in this task's diff.`,
24352
+ commands: [],
24353
+ completion: "verify reports no context freshness issue for this item."
24354
+ };
24355
+ if (issue.code === "source-missing") {
24356
+ action.title = `Fix missing bound sources: ${issue.target}`;
24357
+ action.reason += ` Update its binds/entry in .agents/manifest.yaml first; a review cannot be recorded against missing sources.`;
24358
+ return action;
24359
+ }
24360
+ if (issue.code === "orphan-review") {
24361
+ action.title = `Resolve orphan context review: ${issue.target}`;
24362
+ action.reason += ` Restore its binds/authority in .agents/manifest.yaml, or retire the stale review record deliberately.`;
24363
+ return action;
24364
+ }
24365
+ if (issue.changedSources.length) action.commands.push(`git log -n 5 --oneline -- ${issue.changedSources.map(shellArg).join(" ")}`);
24366
+ const selector = issue.kind === "knowledge" ? `--path ${shellArg(issue.target)}` : `--module ${shellArg(issue.target)}`;
24367
+ action.commands.push(`${cli} record-context-review --repo . ${selector} --reason "<what you re-checked>"`);
24368
+ return action;
24369
+ });
24370
+ }
24371
+ function printActions(actions) {
24372
+ for (const action of actions) {
24373
+ warn(`[${action.priority.toUpperCase()} | ${action.owner.toUpperCase()}] ${action.title}`);
24374
+ info(` why: ${action.reason}`);
24375
+ for (const command of action.commands) info(` run: ${command}`);
24376
+ info(` done when: ${action.completion}`);
24377
+ }
24378
+ }
24379
+ function reportHuman2(report, cli) {
24380
+ if (report.status === "not-adopted" || report.harnessTargets) {
24381
+ for (const message of report.errors) err(message);
24382
+ if (report.status === "not-adopted")
24383
+ warn("deliver: NOT-ADOPTED \u2014 no .agents/manifest.yaml covers this directory; harness-kit cannot accept changes here");
24384
+ else err("deliver: NEEDS-WORK \u2014 run deliver at the Harness target root");
24385
+ info("\nNEXT ACTIONS");
24386
+ printActions(report.nextActions);
24387
+ return;
24388
+ }
24389
+ info(`deliver (scope=${report.scope}, base ${report.base}) \u2014 ${report.changed.length} changed file(s)`);
24390
+ if (report.scope === "worktree" && report.status !== "no-change") {
24391
+ info(` using worktree diff vs HEAD (no task base); for committed task range run: ${cli} task-start`);
24392
+ }
24393
+ if (report.runChecks) {
24394
+ info(` run-checks: ${report.runChecks.status} (${report.runChecks.passed.length} passed, ${report.runChecks.failed.length} failed)`);
24395
+ for (const failure of report.runChecks.failed.slice(0, 5)) {
24396
+ err(`${failure.id}: FAILED (exit ${failure.code}) \u2014 ${failure.cmd}`);
24397
+ for (const line of failure.logTail.split("\n")) if (line) info(` ${line}`);
24398
+ }
24399
+ for (const gap2 of report.runChecks.gaps.filter((g) => g.severity === "blocking").slice(0, 8)) {
24400
+ err(`[${gap2.kind}] ${gap2.where ? `${gap2.where} \u2014 ` : ""}${gap2.why}`);
24401
+ info(` -> ${gap2.suggestion}`);
24402
+ }
24403
+ }
24404
+ if (report.verifyPassed) ok("verify: passed");
24405
+ else err("verify: failed");
24406
+ if (report.inheritedContext.length) {
24407
+ warn(
24408
+ `context freshness: ${report.inheritedContext.length} issue(s) already stale on task base ${report.base} \u2014 not introduced by this task, so they do not block acceptance:`
24409
+ );
24410
+ for (const issue of report.inheritedContext) {
24411
+ const changed = issue.changedSources.length ? ` -> ${issue.changedSources.join(", ")}` : "";
24412
+ info(` ${issue.key}: ${issue.reason}${changed}`);
24413
+ }
24414
+ }
24415
+ for (const message of report.errors) err(message);
24416
+ info("");
24417
+ if (report.status === "accepted") ok("deliver: ACCEPTED \u2014 task stamp is valid for this fingerprint");
24418
+ else if (report.status === "no-change") ok("deliver: NO-CHANGE \u2014 no pending worktree changes to accept");
24419
+ else err("deliver: NEEDS-WORK \u2014 fix failures and re-run harness-kit deliver");
24420
+ if (report.next.length) {
24421
+ info("\nNEXT");
24422
+ for (const step of report.next) info(` - ${step}`);
24423
+ }
24424
+ const maintenance = report.nextActions.filter((action) => action.priority === "recommended");
24425
+ if (maintenance.length) {
24426
+ info("\nMAINTENANCE (recommended; keep out of this task's diff unless the task is Harness maintenance)");
24427
+ printActions(maintenance);
24428
+ }
24429
+ }
24430
+ function emitReport(report, json, cli) {
24431
+ if (json) process.stdout.write(JSON.stringify(report, null, 2) + "\n");
24432
+ else reportHuman2(report, cli);
24433
+ if (report.status === "not-adopted") return DELIVER_NOT_ADOPTED_EXIT_CODE;
24434
+ return report.ok ? 0 : 1;
24435
+ }
24436
+ function unadoptedReport(repo, opts, targets) {
24437
+ let scope = null;
24438
+ try {
24439
+ scope = resolveChangeScope(repo, { base: opts.base });
24440
+ } catch {
24441
+ }
24442
+ const base = {
24443
+ schema: "ai-harness/deliver-report/v1",
24444
+ ok: false,
24445
+ scope: scope?.kind ?? "worktree",
24446
+ base: scope?.base ?? opts.base ?? "HEAD",
24447
+ fingerprint: scope?.changes.fingerprint ?? "",
24448
+ changed: scope?.changes.files ?? [],
24449
+ runChecks: null,
24450
+ verifyPassed: false,
24451
+ stamp: { status: "missing", found: false, stale: false, valid: false, reason: "no Harness manifest in this directory" },
24452
+ inheritedContext: [],
24453
+ harnessTargets: { enclosing: targets.enclosing, nested: targets.nested }
24454
+ };
24455
+ if (targets.enclosing) {
24456
+ const command = `${repoHarnessInvocation(targets.enclosing)} deliver --repo ${shellArg(targets.enclosing)}`;
24457
+ return {
24458
+ ...base,
24459
+ status: "needs-work",
24460
+ adopted: true,
24461
+ errors: [`${repo} is inside Harness target ${targets.enclosing}; deliver must run at the target root`],
24462
+ next: [`re-run at the Harness target root: ${command}`],
24463
+ nextActions: [
24464
+ {
24465
+ id: "deliver-at-harness-target-root",
24466
+ priority: "required",
24467
+ owner: "agent",
24468
+ when: "before-finish",
24469
+ title: "Re-run deliver at the Harness target root",
24470
+ reason: `The manifest for this directory lives in ${targets.enclosing}.`,
24471
+ commands: [command],
24472
+ completion: "deliver at the target root reports status=accepted (or no-change on a clean tree)."
24473
+ }
24474
+ ]
24475
+ };
24476
+ }
24477
+ const touched = targets.nested.filter((dir) => base.changed.some((file) => (0, import_node_path17.join)(repo, file).startsWith(`${dir}/`)));
24478
+ const nestedCommands = touched.map((dir) => `${repoHarnessInvocation(dir)} deliver --repo ${shellArg(dir)}`);
24479
+ const nextActions2 = [
24480
+ {
24481
+ id: "validate-with-repository-conventions",
24482
+ priority: "required",
24483
+ owner: "agent",
24484
+ when: "before-finish",
24485
+ title: "Validate with this repository's own conventions",
24486
+ reason: "No .agents/manifest.yaml covers this directory, so harness-kit cannot accept the change and re-running deliver will not help.",
24487
+ commands: [],
24488
+ completion: "The checks this repository documents (README / CONTRIBUTING / package scripts / CI config) pass, and the report names which ones ran."
24489
+ }
24490
+ ];
24491
+ if (nestedCommands.length) {
24492
+ nextActions2.push({
24493
+ id: "deliver-nested-harness-targets",
24494
+ priority: "required",
24495
+ owner: "agent",
24496
+ when: "before-finish",
24497
+ title: "Deliver the changed nested Harness targets",
24498
+ reason: `Changed files fall inside nested Harness targets: ${touched.join(", ")}.`,
24499
+ commands: nestedCommands,
24500
+ completion: "Each listed target reports status=accepted."
24501
+ });
24502
+ }
24503
+ return {
24504
+ ...base,
24505
+ status: "not-adopted",
24506
+ adopted: false,
24507
+ errors: [],
24508
+ next: [
24509
+ "this directory is not adopted by harness-kit (no .agents/manifest.yaml): validate with the repository's own conventions; do not re-run deliver here",
24510
+ ...nestedCommands.map((command) => `changed nested Harness target: ${command}`)
24511
+ ],
24512
+ nextActions: nextActions2
24513
+ };
24514
+ }
24515
+ function deliverCmd(repo, opts = {}) {
24516
+ const cli = repoHarnessInvocation(repo);
24517
+ const targets = locateHarnessTargets(repo);
24518
+ if (!targets.adopted) return emitReport(unadoptedReport(repo, opts, targets), opts.json, cli);
24519
+ const errors = [];
24520
+ let scope;
24521
+ try {
24522
+ scope = resolveChangeScope(repo, { base: opts.base });
24523
+ } catch (error) {
24524
+ err(`deliver cannot resolve change scope: ${error.message}`);
24525
+ return 1;
24526
+ }
24527
+ const run = captureStdout(
24528
+ () => runChecksCmd(repo, {
24529
+ base: scope.base,
24530
+ mode: "exact",
24531
+ budgetMs: 0,
24532
+ allowEmptyAsNoChange: true,
24533
+ profile: opts.profile,
24534
+ json: true
24535
+ })
24536
+ );
24537
+ const runReport = parseRunReport(run.output);
24538
+ if (!runReport) errors.push("run-checks did not return valid JSON evidence");
24539
+ const verify = captureStdout(
24540
+ () => verifyCmd(repo, {
24541
+ recordManualEvidence: true,
24542
+ json: true,
24543
+ contextBase: scope.base,
24544
+ budgetMs: Number(process.env.HARNESS_KIT_DELIVER_VERIFY_BUDGET_MS) || 60 * 60 * 1e3
24545
+ })
24546
+ );
24547
+ const verifyPassed = verify.code === 0;
24548
+ const verifyReport = parseVerifyReport(verify.output);
24549
+ if (!verifyPassed) {
24550
+ const failures = verifyReport ? verifyReport.messages.filter((message) => message.level === "error").map((message) => message.text).slice(0, 8) : verify.output.trim().split("\n").filter(Boolean).slice(-8);
24551
+ if (failures.length) errors.push(`verify failed: ${failures.join(" | ")}`);
24552
+ else errors.push("verify failed");
24553
+ }
24554
+ const inheritedContext = (verifyReport?.context ?? []).filter((issue) => issue.inherited);
24555
+ let fingerprintError = "";
24556
+ if (runReport?.fingerprint) {
24557
+ try {
24558
+ const current = collectChanges(repo, scope.base, { mode: "exact" });
24559
+ if (current.fingerprint !== runReport.fingerprint) {
24560
+ fingerprintError = "change fingerprint changed during delivery; re-run deliver on a stable tree";
24561
+ errors.push(fingerprintError);
24562
+ }
24563
+ } catch (error) {
24564
+ fingerprintError = `final fingerprint failed: ${error.message}`;
24565
+ errors.push(fingerprintError);
24566
+ }
24567
+ }
24568
+ const runOk = run.code === 0 && !!runReport?.ok;
24569
+ const stable = !fingerprintError;
24570
+ let status;
24571
+ if (runOk && verifyPassed && stable && runReport?.status === "no-change") status = "no-change";
24572
+ else if (runOk && verifyPassed && stable) status = "accepted";
24573
+ else status = "needs-work";
24574
+ const actions = inheritedContextActions(inheritedContext, scope.base, cli);
24575
+ if (status === "needs-work") {
24576
+ actions.unshift({
24577
+ id: "fix-delivery-failures",
24578
+ priority: "required",
24579
+ owner: "agent",
24580
+ when: "before-finish",
24581
+ title: "Fix deliver failures and re-run deliver",
24582
+ reason: errors.length ? errors.slice(0, 3).join("; ") : "run-checks did not pass for this change.",
24583
+ commands: [`${cli} deliver --repo .`],
24584
+ completion: "deliver reports status=accepted (or no-change on a clean tree)."
24585
+ });
24586
+ }
24587
+ const stamp = inspectDeliveryStamp(repo);
24588
+ const report = {
24589
+ schema: "ai-harness/deliver-report/v1",
24590
+ status,
24591
+ ok: status === "accepted" || status === "no-change",
24592
+ adopted: true,
24593
+ scope: scope.kind,
24594
+ base: scope.base,
24595
+ fingerprint: runReport?.fingerprint ?? scope.changes.fingerprint,
24596
+ changed: runReport?.changed ?? scope.changes.files,
24597
+ runChecks: runReport,
24598
+ verifyPassed,
24599
+ stamp,
24600
+ inheritedContext,
24601
+ errors,
24602
+ next: nextActions(status, runReport, cli),
24603
+ nextActions: actions
24604
+ };
24605
+ return emitReport(report, opts.json, cli);
24606
+ }
24607
+
23977
24608
  // src/commands/hook-event.ts
23978
24609
  var MAX_HOOK_VERIFY_BUDGET_MS = 2 * 60 * 1e3;
23979
24610
  function hookVerifyBudgetMs() {
@@ -23981,8 +24612,12 @@ function hookVerifyBudgetMs() {
23981
24612
  if (!Number.isFinite(configured) || configured <= 0) return MAX_HOOK_VERIFY_BUDGET_MS;
23982
24613
  return Math.min(configured, MAX_HOOK_VERIFY_BUDGET_MS);
23983
24614
  }
24615
+ function stopMode() {
24616
+ const raw = (process.env.HARNESS_KIT_STOP_MODE ?? "thin").trim().toLowerCase();
24617
+ return raw === "execute" || raw === "thick" ? "execute" : "thin";
24618
+ }
23984
24619
  function readPayload() {
23985
- const raw = (0, import_node_fs15.readFileSync)(0, "utf8").trim();
24620
+ const raw = (0, import_node_fs17.readFileSync)(0, "utf8").trim();
23986
24621
  if (!raw) return {};
23987
24622
  const value = JSON.parse(raw);
23988
24623
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("hook stdin must be a JSON object");
@@ -23991,7 +24626,7 @@ function readPayload() {
23991
24626
  function sessionId(payload) {
23992
24627
  return payload.session_id ?? payload.conversation_id ?? payload.turn_id ?? null;
23993
24628
  }
23994
- function captureStdout(fn) {
24629
+ function captureStdout2(fn) {
23995
24630
  const chunks = [];
23996
24631
  const original = process.stdout.write.bind(process.stdout);
23997
24632
  process.stdout.write = (chunk) => {
@@ -24025,14 +24660,24 @@ function block(agent, event, reason) {
24025
24660
  process.stderr.write(reason.trimEnd() + "\n");
24026
24661
  return 2;
24027
24662
  }
24028
- function parseRunReport(output) {
24663
+ function parseRunReport2(output) {
24029
24664
  try {
24030
24665
  return JSON.parse(output);
24031
24666
  } catch {
24032
24667
  return null;
24033
24668
  }
24034
24669
  }
24035
- function failureMessage(report, verifyOutput, token) {
24670
+ function deliverBlockMessage(cli, extra = "") {
24671
+ const lines = [
24672
+ "harness-kit: delivery is not verified; continue working before stopping.",
24673
+ `Run: ${cli} deliver --repo .`,
24674
+ "Only status=accepted (or no-change with a clean tree) may finish.",
24675
+ "Fix failures from deliver, then finish again."
24676
+ ];
24677
+ if (extra.trim()) lines.splice(1, 0, extra.trim());
24678
+ return lines.join("\n");
24679
+ }
24680
+ function failureMessage(report, verifyOutput, token, cli) {
24036
24681
  const lines = ["harness-kit: delivery is not verified; continue working before stopping."];
24037
24682
  if (!report) lines.push("run-checks did not return valid evidence.");
24038
24683
  else {
@@ -24055,80 +24700,84 @@ function failureMessage(report, verifyOutput, token) {
24055
24700
  const actionable = outputLines.filter((line) => /\bERR\b|timed out|budget exhausted|verify: FAILED/.test(line));
24056
24701
  lines.push(`- verify: ${(actionable.length ? actionable.slice(-8) : outputLines.slice(-8)).join(" | ")}`);
24057
24702
  }
24058
- lines.push("Fix the failures, then finish again; every Stop attempt is re-checked.");
24703
+ lines.push(`Prefer: ${cli} deliver --repo . (then finish again)`);
24059
24704
  lines.push(
24060
- `For a genuine non-goal, only an eligible coverage gap may be waived: harness-kit run-checks --repo . --session ${token} --waive <kind> --where <scope> --reason "<why>"`
24705
+ `For a genuine non-goal coverage gap only: ${cli} run-checks --repo . --session ${token} --waive <kind> --where <scope> --reason "<why>"`
24061
24706
  );
24062
24707
  return lines.join("\n");
24063
24708
  }
24064
- function hookEventCmd(repoInput, opts) {
24065
- let payload;
24709
+ function thinStop(repo, agent) {
24710
+ const cli = repoHarnessInvocation(repo);
24711
+ let scope;
24066
24712
  try {
24067
- payload = readPayload();
24713
+ scope = resolveChangeScope(repo);
24068
24714
  } catch (error) {
24069
- return block(opts.agent, opts.event, `harness-kit hook input invalid: ${error.message}`);
24070
- }
24071
- const id = sessionId(payload);
24072
- if (!id) return block(opts.agent, opts.event, "harness-kit hook input has no session/conversation id");
24073
- let repo;
24074
- try {
24075
- repo = gitRoot(repoInput);
24076
- } catch (error) {
24077
- return block(opts.agent, opts.event, `harness-kit cannot resolve repository root: ${error.message}`);
24078
- }
24079
- if (opts.event === "session-start") {
24080
- try {
24081
- const initial = collectChanges(repo, "HEAD", { mode: "exact" });
24082
- startValidationSession({
24083
- repo,
24084
- agent: opts.agent,
24085
- sessionId: id,
24086
- baseSha: initial.head,
24087
- initialFingerprint: initial.fingerprint,
24088
- initialDirty: initial.files,
24089
- hookConfigFingerprint: agentHookConfigurationFingerprint(repo, opts.agent) ?? void 0
24090
- });
24091
- return allow(opts.agent);
24092
- } catch (error) {
24093
- return block(opts.agent, opts.event, `harness-kit could not capture the session baseline: ${error.message}`);
24094
- }
24095
- }
24096
- if (opts.agent === "cursor" && ["aborted", "error"].includes(payload.status ?? "")) return allow(opts.agent);
24097
- const token = validationSessionToken(opts.agent, id);
24715
+ return block(agent, "stop", deliverBlockMessage(cli, `cannot resolve changes: ${error.message}`));
24716
+ }
24717
+ if (scope.changes.files.length === 0) return allow(agent);
24718
+ if (stampCoversScope(repo, scope)) return allow(agent);
24719
+ return block(
24720
+ agent,
24721
+ "stop",
24722
+ deliverBlockMessage(
24723
+ cli,
24724
+ `scope=${scope.kind} base=${scope.base} changed=${scope.changes.files.length} file(s); no matching accepted delivery stamp.`
24725
+ )
24726
+ );
24727
+ }
24728
+ function executeStop(repo, agent, id) {
24729
+ const cli = repoHarnessInvocation(repo);
24730
+ const token = validationSessionToken(agent, id);
24098
24731
  let session;
24099
24732
  try {
24100
24733
  session = readValidationSession(repo, token);
24101
24734
  } catch (error) {
24102
- return block(opts.agent, opts.event, `harness-kit validation session is unreadable: ${error.message}`);
24735
+ return block(agent, "stop", deliverBlockMessage(cli, `validation session unreadable: ${error.message}`));
24103
24736
  }
24104
24737
  if (!session) {
24105
- return block(
24106
- opts.agent,
24107
- opts.event,
24108
- "harness-kit has no SessionStart baseline for this conversation. Start a new agent session after installing hooks; refusing to guess and miss committed changes."
24109
- );
24738
+ const delivered = captureStdout2(() => deliverCmd(repo, { json: true }));
24739
+ if (delivered.code === 0) return allow(agent);
24740
+ let detail = "";
24741
+ try {
24742
+ const body = JSON.parse(delivered.output);
24743
+ detail = `deliver status=${body.status ?? "needs-work"}; ${(body.errors ?? []).slice(0, 3).join("; ")}`;
24744
+ } catch {
24745
+ detail = delivered.output.trim().slice(0, 500);
24746
+ }
24747
+ return block(agent, "stop", deliverBlockMessage(cli, detail));
24110
24748
  }
24111
- if (session.hookConfigFingerprint && agentHookConfigurationFingerprint(repo, opts.agent) !== session.hookConfigFingerprint) {
24749
+ if (session.hookConfigFingerprint && agentHookConfigurationFingerprint(repo, agent) !== session.hookConfigFingerprint) {
24750
+ const delivered = captureStdout2(() => deliverCmd(repo, { json: true }));
24751
+ if (delivered.code === 0) return allow(agent);
24112
24752
  return block(
24113
- opts.agent,
24114
- opts.event,
24115
- "harness-kit project hook configuration changed after SessionStart. Start a new agent session before delivery; refusing to trust evidence from another hook configuration."
24753
+ agent,
24754
+ "stop",
24755
+ deliverBlockMessage(
24756
+ cli,
24757
+ "project hook configuration changed after SessionStart; lifecycle proof was discarded. Run deliver to re-accept the current change."
24758
+ )
24116
24759
  );
24117
24760
  }
24118
24761
  try {
24119
24762
  clearValidationEvidence(repo, session);
24120
24763
  } catch (error) {
24121
- return block(opts.agent, opts.event, `harness-kit could not start a fresh validation attempt: ${error.message}`);
24122
- }
24123
- const run = captureStdout(() => runChecksCmd(repo, { session: token, json: true }));
24124
- const report = parseRunReport(run.output);
24125
- const verify = captureStdout(() => verifyCmd(repo, { budgetMs: hookVerifyBudgetMs(), recordManualEvidence: false }));
24764
+ return block(agent, "stop", deliverBlockMessage(cli, `could not start a fresh validation attempt: ${error.message}`));
24765
+ }
24766
+ const run = captureStdout2(() => runChecksCmd(repo, { session: token, json: true, budgetMs: 0 }));
24767
+ const report = parseRunReport2(run.output);
24768
+ const verify = captureStdout2(
24769
+ () => verifyCmd(repo, {
24770
+ budgetMs: hookVerifyBudgetMs(),
24771
+ recordManualEvidence: false,
24772
+ ...session.baseSha ? { contextBase: session.baseSha } : {}
24773
+ })
24774
+ );
24126
24775
  let finalFingerprintError = "";
24127
24776
  if (report?.fingerprint) {
24128
24777
  try {
24129
24778
  const current = collectChanges(repo, session.baseSha ?? EMPTY_TREE_BASE, { mode: "exact" });
24130
24779
  if (current.fingerprint !== report.fingerprint)
24131
- finalFingerprintError = "change fingerprint changed during final verification; rerun both gates on the stable change";
24780
+ finalFingerprintError = "change fingerprint changed during final verification; rerun deliver on the stable change";
24132
24781
  } catch (error) {
24133
24782
  finalFingerprintError = `final fingerprint failed: ${error.message}`;
24134
24783
  }
@@ -24138,21 +24787,69 @@ function hookEventCmd(repoInput, opts) {
24138
24787
  try {
24139
24788
  evidencePersisted = markLatestVerifyResult(repo, token, verifyPassed, report?.fingerprint, report?.planFingerprint);
24140
24789
  } catch (error) {
24141
- return block(opts.agent, opts.event, `harness-kit could not persist the final verify result: ${error.message}`);
24790
+ return block(agent, "stop", deliverBlockMessage(cli, `could not persist verify result: ${error.message}`));
24142
24791
  }
24143
- if (run.code === 0 && report?.ok && verifyPassed && evidencePersisted) return allow(opts.agent);
24792
+ if (run.code === 0 && report?.ok && verifyPassed && evidencePersisted) return allow(agent);
24144
24793
  const verifyDetails = [
24145
24794
  verify.code === 0 ? "" : verify.output.trim(),
24146
24795
  finalFingerprintError,
24147
24796
  evidencePersisted ? "" : "matching final evidence was not persisted; refusing to allow Stop"
24148
24797
  ].filter(Boolean).join("\n");
24149
- return block(opts.agent, opts.event, failureMessage(report, verifyDetails, token));
24798
+ return block(agent, "stop", failureMessage(report, verifyDetails, token, cli));
24799
+ }
24800
+ function hookEventCmd(repoInput, opts) {
24801
+ let payload;
24802
+ try {
24803
+ payload = readPayload();
24804
+ } catch (error) {
24805
+ return block(opts.agent, opts.event, `harness-kit hook input invalid: ${error.message}`);
24806
+ }
24807
+ const id = sessionId(payload);
24808
+ if (!id) return block(opts.agent, opts.event, "harness-kit hook input has no session/conversation id");
24809
+ let repo;
24810
+ try {
24811
+ repo = gitRoot(repoInput);
24812
+ } catch (error) {
24813
+ return block(opts.agent, opts.event, `harness-kit cannot resolve repository root: ${error.message}`);
24814
+ }
24815
+ if (opts.event === "session-start") {
24816
+ try {
24817
+ const initial = collectChanges(repo, "HEAD", { mode: "exact" });
24818
+ startValidationSession({
24819
+ repo,
24820
+ agent: opts.agent,
24821
+ sessionId: id,
24822
+ baseSha: initial.head,
24823
+ initialFingerprint: initial.fingerprint,
24824
+ initialDirty: initial.files,
24825
+ hookConfigFingerprint: agentHookConfigurationFingerprint(repo, opts.agent) ?? void 0
24826
+ });
24827
+ if (initial.head) {
24828
+ try {
24829
+ startTaskRecord({
24830
+ repo,
24831
+ baseSha: initial.head,
24832
+ hostSessionId: id,
24833
+ agent: opts.agent,
24834
+ note: "auto from SessionStart"
24835
+ });
24836
+ } catch {
24837
+ }
24838
+ }
24839
+ return allow(opts.agent);
24840
+ } catch (error) {
24841
+ return block(opts.agent, opts.event, `harness-kit could not capture the session baseline: ${error.message}`);
24842
+ }
24843
+ }
24844
+ if (opts.agent === "cursor" && ["aborted", "error"].includes(payload.status ?? "")) return allow(opts.agent);
24845
+ if (stopMode() === "thin") return thinStop(repo, opts.agent);
24846
+ return executeStop(repo, opts.agent, id);
24150
24847
  }
24151
24848
 
24152
24849
  // src/commands/install-hooks.ts
24153
24850
  var import_node_child_process7 = require("node:child_process");
24154
- var import_node_fs16 = require("node:fs");
24155
- var import_node_path15 = require("node:path");
24851
+ var import_node_fs18 = require("node:fs");
24852
+ var import_node_path18 = require("node:path");
24156
24853
  var MARK = "harness-kit-managed-hook";
24157
24854
  function git2(repo, args) {
24158
24855
  const result = (0, import_node_child_process7.spawnSync)("git", args, { cwd: repo, encoding: "utf8" });
@@ -24194,9 +24891,9 @@ function inspectGitHookScope(repo) {
24194
24891
  }
24195
24892
  ];
24196
24893
  });
24197
- const hooksDir = (0, import_node_path15.resolve)(repo, hooks.stdout.trim());
24198
- const commonDir = (0, import_node_path15.resolve)(repo, common.stdout.trim());
24199
- const gitDir = (0, import_node_path15.resolve)(repo, current.stdout.trim());
24894
+ const hooksDir = (0, import_node_path18.resolve)(repo, hooks.stdout.trim());
24895
+ const commonDir = (0, import_node_path18.resolve)(repo, common.stdout.trim());
24896
+ const gitDir = (0, import_node_path18.resolve)(repo, current.stdout.trim());
24200
24897
  return {
24201
24898
  scope: {
24202
24899
  hooksDir,
@@ -24205,21 +24902,21 @@ function inspectGitHookScope(repo) {
24205
24902
  worktrees,
24206
24903
  hooksPathConfigs,
24207
24904
  hooksPathConfigRaw,
24208
- defaultHooksDirMatches: hooksDir === (0, import_node_path15.join)(commonDir, "hooks")
24905
+ defaultHooksDirMatches: hooksDir === (0, import_node_path18.join)(commonDir, "hooks")
24209
24906
  }
24210
24907
  };
24211
24908
  }
24212
24909
  function hookOwnership(path) {
24213
24910
  try {
24214
- if (!(0, import_node_fs16.lstatSync)(path).isFile()) return "foreign";
24215
- return (0, import_node_fs16.readFileSync)(path, "utf8").includes(MARK) ? "managed" : "foreign";
24911
+ if (!(0, import_node_fs18.lstatSync)(path).isFile()) return "foreign";
24912
+ return (0, import_node_fs18.readFileSync)(path, "utf8").includes(MARK) ? "managed" : "foreign";
24216
24913
  } catch (error) {
24217
24914
  return error.code === "ENOENT" ? "missing" : "foreign";
24218
24915
  }
24219
24916
  }
24220
24917
  function hooksPathReason(scope) {
24221
24918
  if (!scope.hooksPathConfigRaw.length) {
24222
- return scope.defaultHooksDirMatches ? null : `resolved hooks directory does not match ${(0, import_node_path15.join)(scope.commonDir, "hooks")}; core.hooksPath origin is ambiguous`;
24919
+ return scope.defaultHooksDirMatches ? null : `resolved hooks directory does not match ${(0, import_node_path18.join)(scope.commonDir, "hooks")}; core.hooksPath origin is ambiguous`;
24223
24920
  }
24224
24921
  if (scope.hooksPathConfigs.length !== 1 || scope.hooksPathConfigRaw.length !== 1) {
24225
24922
  return `core.hooksPath is ambiguous: ${scope.hooksPathConfigRaw.join("; ")}`;
@@ -24270,7 +24967,7 @@ function installGitHooks(repo, force, allowSharedGitHooks) {
24270
24967
  ["pre-commit", preCommit()],
24271
24968
  ["pre-push", prePush()]
24272
24969
  ];
24273
- const ownership = new Map(targets.map(([name]) => [name, hookOwnership((0, import_node_path15.join)(scope.hooksDir, name))]));
24970
+ const ownership = new Map(targets.map(([name]) => [name, hookOwnership((0, import_node_path18.join)(scope.hooksDir, name))]));
24274
24971
  const reasons = [];
24275
24972
  const configuredPathReason = hooksPathReason(scope);
24276
24973
  if (configuredPathReason) reasons.push(configuredPathReason);
@@ -24293,10 +24990,10 @@ function installGitHooks(repo, force, allowSharedGitHooks) {
24293
24990
  );
24294
24991
  }
24295
24992
  for (const [name, body] of targets) {
24296
- const p = (0, import_node_path15.join)(scope.hooksDir, name);
24993
+ const p = (0, import_node_path18.join)(scope.hooksDir, name);
24297
24994
  const wasManaged = ownership.get(name) === "managed";
24298
24995
  writeText(p, body);
24299
- (0, import_node_fs16.chmodSync)(p, 493);
24996
+ (0, import_node_fs18.chmodSync)(p, 493);
24300
24997
  ok(`${wasManaged ? force ? "refreshed" : "updated" : "installed"} ${name}`);
24301
24998
  }
24302
24999
  info(`
@@ -24409,10 +25106,10 @@ function recordContextReviewCmd(repo, opts) {
24409
25106
  }
24410
25107
 
24411
25108
  // src/commands/prepare-adoption.ts
24412
- var import_node_path16 = require("node:path");
25109
+ var import_node_path19 = require("node:path");
24413
25110
  function prepareAdoptionCmd(repo, opts) {
24414
25111
  if (!opts.output?.trim()) throw new Error("candidate output directory is required");
24415
- const output = (0, import_node_path16.resolve)(opts.output);
25112
+ const output = (0, import_node_path19.resolve)(opts.output);
24416
25113
  const candidate = prepareAdoptionCandidate(repo, output);
24417
25114
  const result = {
24418
25115
  ok: true,
@@ -24430,15 +25127,15 @@ function prepareAdoptionCmd(repo, opts) {
24430
25127
  }
24431
25128
 
24432
25129
  // src/commands/record-adoption-audit.ts
24433
- var import_node_path17 = require("node:path");
25130
+ var import_node_path20 = require("node:path");
24434
25131
  function recordAdoptionAuditCmd(repo, opts) {
24435
25132
  if (!opts.candidate?.trim()) throw new Error("candidate directory is required");
24436
25133
  if (!opts.report?.trim()) throw new Error("audit report path is required");
24437
- const recorded = recordAdoptionAudit(repo, (0, import_node_path17.resolve)(opts.candidate), {
25134
+ const recorded = recordAdoptionAudit(repo, (0, import_node_path20.resolve)(opts.candidate), {
24438
25135
  verdict: opts.verdict,
24439
25136
  reason: opts.reason,
24440
- reportPath: (0, import_node_path17.resolve)(opts.report),
24441
- receiptPath: opts.receipt ? (0, import_node_path17.resolve)(opts.receipt) : void 0
25137
+ reportPath: (0, import_node_path20.resolve)(opts.report),
25138
+ receiptPath: opts.receipt ? (0, import_node_path20.resolve)(opts.receipt) : void 0
24442
25139
  });
24443
25140
  const result = {
24444
25141
  ok: true,
@@ -24547,6 +25244,41 @@ function upgradeCmd(repo, options = {}) {
24547
25244
  return 0;
24548
25245
  }
24549
25246
 
25247
+ // src/commands/task.ts
25248
+ function taskStartCmd(repo, opts = {}) {
25249
+ try {
25250
+ const record = startTaskRecord({ repo, baseSha: opts.base, note: opts.note });
25251
+ if (opts.json) {
25252
+ process.stdout.write(JSON.stringify(record, null, 2) + "\n");
25253
+ } else {
25254
+ ok(`task started at base ${record.baseSha}`);
25255
+ if (record.note) info(`note: ${record.note}`);
25256
+ info(`run ${repoHarnessInvocation(repo)} deliver when ready to accept this task's changes`);
25257
+ }
25258
+ return 0;
25259
+ } catch (error) {
25260
+ err(`task start failed: ${error.message}`);
25261
+ return 1;
25262
+ }
25263
+ }
25264
+ function taskStatusCmd(repo, opts = {}) {
25265
+ const record = readTaskRecord(repo);
25266
+ if (opts.json) {
25267
+ process.stdout.write(JSON.stringify({ schema: "ai-harness/task-status/v1", found: !!record, task: record }, null, 2) + "\n");
25268
+ return record ? 0 : 1;
25269
+ }
25270
+ if (!record) {
25271
+ err("no active task record for this worktree");
25272
+ info(`run: ${repoHarnessInvocation(repo)} task-start --repo .`);
25273
+ info("without a task base, deliver falls back to worktree diff vs HEAD");
25274
+ return 1;
25275
+ }
25276
+ ok(`active task base ${record.baseSha}`);
25277
+ info(`created: ${record.createdAt}`);
25278
+ if (record.note) info(`note: ${record.note}`);
25279
+ return 0;
25280
+ }
25281
+
24550
25282
  // src/cli.ts
24551
25283
  function guard(fn) {
24552
25284
  try {
@@ -24559,7 +25291,7 @@ function guard(fn) {
24559
25291
  }
24560
25292
  var program2 = new Command();
24561
25293
  program2.name("harness-kit").description("AI-friendly repo harness").version(package_default.version);
24562
- var repoOf = (o) => (0, import_node_path18.resolve)(o.repo ?? process.cwd());
25294
+ var repoOf = (o) => (0, import_node_path21.resolve)(o.repo ?? process.cwd());
24563
25295
  function agentList(value) {
24564
25296
  const agents = value.split(",").map((item) => item.trim()).filter(Boolean);
24565
25297
  const invalid = agents.filter((agent) => !ALL_AGENTS.includes(agent));
@@ -24593,6 +25325,17 @@ program2.command("record-adoption-audit").description("record a declared pass/fa
24593
25325
  program2.command("doctor").description("dev-time health check: completeness, drift, freshness, tech debt").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--details", "show every declared verification boundary and maintenance action", false).action((o) => guard(() => doctorCmd(repoOf(o), { details: o.details })));
24594
25326
  program2.command("verify").description("CI gate: run enforceable invariants + contracts + drift; nonzero on failure").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--json", "machine-readable output", false).option("--details", "show every declared verification boundary and maintenance action", false).action((o) => guard(() => verifyCmd(repoOf(o), { json: o.json, details: o.details })));
24595
25327
  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 })));
25328
+ 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 })));
25329
+ 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 })));
25330
+ 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(
25331
+ (o) => guard(
25332
+ () => deliverCmd(repoOf(o), {
25333
+ base: o.base,
25334
+ profile: o.profile,
25335
+ json: o.json
25336
+ })
25337
+ )
25338
+ );
24596
25339
  program2.command("run-checks").description("plan + run resolved checks; record evidence; nonzero on failure/unresolved blocking gap").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--base <ref>", "task-start ref; required for manual proof after task changes were committed").option("--profile <checkset>", "use a validation.checksets entry instead of per-module checks").option("--waive <kind>", "waive one eligible coverage gap for this exact change fingerprint").option("--where <scope>", "exact gap scope; required when a kind matches multiple gaps").option("--reason <text>", "reason recorded with --waive").option("--session <token>", "validation session token (normally supplied by an agent hook)").option("--json", "machine-readable output", false).action(
24597
25340
  (o) => guard(
24598
25341
  () => runChecksCmd(repoOf(o), {
@@ -24606,7 +25349,7 @@ program2.command("run-checks").description("plan + run resolved checks; record e
24606
25349
  })
24607
25350
  )
24608
25351
  );
24609
- program2.command("evidence").description("show the latest durable run-checks evidence for this worktree/session").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--session <token>", "specific validation session token").option("--json", "machine-readable output", false).action((o) => guard(() => evidenceCmd(repoOf(o), { session: o.session, json: o.json })));
25352
+ program2.command("evidence").description("show the latest durable delivery stamp / run-checks evidence for this worktree/session").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--session <token>", "specific validation session token").option("--json", "machine-readable output", false).action((o) => guard(() => evidenceCmd(repoOf(o), { session: o.session, json: o.json })));
24610
25353
  program2.command("record-context-review").description("record an Agent's completed review of one knowledge item or module against its bound sources").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--path <knowledge-path>", "exact knowledge.path from the manifest").option("--module <name>", "exact module name (mutually exclusive with --path)").requiredOption("--reason <text>", "what was reviewed and why the context remains correct").option("--session <token>", "Agent/session identifier to keep with the review evidence").option("--json", "machine-readable output", false).action(
24611
25354
  (o) => guard(
24612
25355
  () => recordContextReviewCmd(repoOf(o), {