@erzhe/harness-kit 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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) {
@@ -4942,9 +4942,9 @@ var require_picomatch = __commonJS({
4942
4942
  var utils = require_utils();
4943
4943
  var constants3 = require_constants();
4944
4944
  var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
4945
- var picomatch4 = (glob, options, returnState = false) => {
4945
+ var picomatch5 = (glob, options, returnState = false) => {
4946
4946
  if (Array.isArray(glob)) {
4947
- const fns = glob.map((input) => picomatch4(input, options, returnState));
4947
+ const fns = glob.map((input) => picomatch5(input, options, returnState));
4948
4948
  const arrayMatcher = (str) => {
4949
4949
  for (const isMatch of fns) {
4950
4950
  const state2 = isMatch(str);
@@ -4959,18 +4959,18 @@ 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;
4963
- const regex = isState ? picomatch4.compileRe(glob, options) : picomatch4.makeRe(glob, options, false, true);
4962
+ const posix2 = opts.windows;
4963
+ const regex = isState ? picomatch5.compileRe(glob, options) : picomatch5.makeRe(glob, options, false, true);
4964
4964
  const state = regex.state;
4965
4965
  delete regex.state;
4966
4966
  let isIgnored = () => false;
4967
4967
  if (opts.ignore) {
4968
4968
  const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
4969
- isIgnored = picomatch4(opts.ignore, ignoreOpts, returnState);
4969
+ isIgnored = picomatch5(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 } = picomatch5.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
+ picomatch5.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,24 +5012,24 @@ 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 = picomatch5.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) => {
5023
- const regex = glob instanceof RegExp ? glob : picomatch4.makeRe(glob, options);
5024
- return regex.test(utils.basename(input, { windows: posix }));
5022
+ picomatch5.matchBase = (input, glob, options, posix2 = options && options.windows) => {
5023
+ const regex = glob instanceof RegExp ? glob : picomatch5.makeRe(glob, options);
5024
+ return regex.test(utils.basename(input, { windows: posix2 }));
5025
5025
  };
5026
- picomatch4.isMatch = (str, patterns, options) => picomatch4(patterns, options)(str);
5027
- picomatch4.parse = (pattern, options) => {
5028
- if (Array.isArray(pattern)) return pattern.map((p) => picomatch4.parse(p, options));
5026
+ picomatch5.isMatch = (str, patterns, options) => picomatch5(patterns, options)(str);
5027
+ picomatch5.parse = (pattern, options) => {
5028
+ if (Array.isArray(pattern)) return pattern.map((p) => picomatch5.parse(p, options));
5029
5029
  return parse(pattern, { ...options, fastpaths: false });
5030
5030
  };
5031
- picomatch4.scan = (input, options) => scan(input, options);
5032
- picomatch4.compileRe = (state, options, returnOutput = false, returnState = false) => {
5031
+ picomatch5.scan = (input, options) => scan(input, options);
5032
+ picomatch5.compileRe = (state, options, returnOutput = false, returnState = false) => {
5033
5033
  if (returnOutput === true) {
5034
5034
  return state.output;
5035
5035
  }
@@ -5040,13 +5040,13 @@ var require_picomatch = __commonJS({
5040
5040
  if (state && state.negated === true) {
5041
5041
  source = `^(?!${source}).*$`;
5042
5042
  }
5043
- const regex = picomatch4.toRegex(source, options);
5043
+ const regex = picomatch5.toRegex(source, options);
5044
5044
  if (returnState === true) {
5045
5045
  regex.state = state;
5046
5046
  }
5047
5047
  return regex;
5048
5048
  };
5049
- picomatch4.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
5049
+ picomatch5.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
5050
5050
  if (!input || typeof input !== "string") {
5051
5051
  throw new TypeError("Expected a non-empty string");
5052
5052
  }
@@ -5057,9 +5057,9 @@ var require_picomatch = __commonJS({
5057
5057
  if (!parsed.output) {
5058
5058
  parsed = parse(input, options);
5059
5059
  }
5060
- return picomatch4.compileRe(parsed, options, returnOutput, returnState);
5060
+ return picomatch5.compileRe(parsed, options, returnOutput, returnState);
5061
5061
  };
5062
- picomatch4.toRegex = (source, options) => {
5062
+ picomatch5.toRegex = (source, options) => {
5063
5063
  try {
5064
5064
  const opts = options || {};
5065
5065
  return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
@@ -5068,8 +5068,8 @@ var require_picomatch = __commonJS({
5068
5068
  return /$^/;
5069
5069
  }
5070
5070
  };
5071
- picomatch4.constants = constants3;
5072
- module2.exports = picomatch4;
5071
+ picomatch5.constants = constants3;
5072
+ module2.exports = picomatch5;
5073
5073
  }
5074
5074
  });
5075
5075
 
@@ -5079,14 +5079,14 @@ var require_picomatch2 = __commonJS({
5079
5079
  "use strict";
5080
5080
  var pico = require_picomatch();
5081
5081
  var utils = require_utils();
5082
- function picomatch4(glob, options, returnState = false) {
5082
+ function picomatch5(glob, options, returnState = false) {
5083
5083
  if (options && (options.windows === null || options.windows === void 0)) {
5084
5084
  options = { ...options, windows: utils.isWindows() };
5085
5085
  }
5086
5086
  return pico(glob, options, returnState);
5087
5087
  }
5088
- Object.assign(picomatch4, pico);
5089
- module2.exports = picomatch4;
5088
+ Object.assign(picomatch5, pico);
5089
+ module2.exports = picomatch5;
5090
5090
  }
5091
5091
  });
5092
5092
 
@@ -6733,7 +6733,7 @@ var require_log = __commonJS({
6733
6733
  if (logLevel === "debug")
6734
6734
  console.log(...messages);
6735
6735
  }
6736
- function warn3(logLevel, warning) {
6736
+ function warn2(logLevel, warning) {
6737
6737
  if (logLevel === "debug" || logLevel === "warn") {
6738
6738
  if (typeof node_process.emitWarning === "function")
6739
6739
  node_process.emitWarning(warning);
@@ -6742,7 +6742,7 @@ var require_log = __commonJS({
6742
6742
  }
6743
6743
  }
6744
6744
  exports2.debug = debug;
6745
- exports2.warn = warn3;
6745
+ exports2.warn = warn2;
6746
6746
  }
6747
6747
  });
6748
6748
 
@@ -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) {
@@ -15398,9 +15398,9 @@ var require_picomatch3 = __commonJS({
15398
15398
  var utils = require_utils3();
15399
15399
  var constants3 = require_constants3();
15400
15400
  var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
15401
- var picomatch4 = (glob, options, returnState = false) => {
15401
+ var picomatch5 = (glob, options, returnState = false) => {
15402
15402
  if (Array.isArray(glob)) {
15403
- const fns = glob.map((input) => picomatch4(input, options, returnState));
15403
+ const fns = glob.map((input) => picomatch5(input, options, returnState));
15404
15404
  const arrayMatcher = (str) => {
15405
15405
  for (const isMatch of fns) {
15406
15406
  const state2 = isMatch(str);
@@ -15415,18 +15415,18 @@ 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);
15419
- const regex = isState ? picomatch4.compileRe(glob, options) : picomatch4.makeRe(glob, options, false, true);
15418
+ const posix2 = utils.isWindows(options);
15419
+ const regex = isState ? picomatch5.compileRe(glob, options) : picomatch5.makeRe(glob, options, false, true);
15420
15420
  const state = regex.state;
15421
15421
  delete regex.state;
15422
15422
  let isIgnored = () => false;
15423
15423
  if (opts.ignore) {
15424
15424
  const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
15425
- isIgnored = picomatch4(opts.ignore, ignoreOpts, returnState);
15425
+ isIgnored = picomatch5(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 } = picomatch5.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
+ picomatch5.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,24 +15468,24 @@ 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 = picomatch5.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)) => {
15479
- const regex = glob instanceof RegExp ? glob : picomatch4.makeRe(glob, options);
15478
+ picomatch5.matchBase = (input, glob, options, posix2 = utils.isWindows(options)) => {
15479
+ const regex = glob instanceof RegExp ? glob : picomatch5.makeRe(glob, options);
15480
15480
  return regex.test(path.basename(input));
15481
15481
  };
15482
- picomatch4.isMatch = (str, patterns, options) => picomatch4(patterns, options)(str);
15483
- picomatch4.parse = (pattern, options) => {
15484
- if (Array.isArray(pattern)) return pattern.map((p) => picomatch4.parse(p, options));
15482
+ picomatch5.isMatch = (str, patterns, options) => picomatch5(patterns, options)(str);
15483
+ picomatch5.parse = (pattern, options) => {
15484
+ if (Array.isArray(pattern)) return pattern.map((p) => picomatch5.parse(p, options));
15485
15485
  return parse(pattern, { ...options, fastpaths: false });
15486
15486
  };
15487
- picomatch4.scan = (input, options) => scan(input, options);
15488
- picomatch4.compileRe = (state, options, returnOutput = false, returnState = false) => {
15487
+ picomatch5.scan = (input, options) => scan(input, options);
15488
+ picomatch5.compileRe = (state, options, returnOutput = false, returnState = false) => {
15489
15489
  if (returnOutput === true) {
15490
15490
  return state.output;
15491
15491
  }
@@ -15496,13 +15496,13 @@ var require_picomatch3 = __commonJS({
15496
15496
  if (state && state.negated === true) {
15497
15497
  source = `^(?!${source}).*$`;
15498
15498
  }
15499
- const regex = picomatch4.toRegex(source, options);
15499
+ const regex = picomatch5.toRegex(source, options);
15500
15500
  if (returnState === true) {
15501
15501
  regex.state = state;
15502
15502
  }
15503
15503
  return regex;
15504
15504
  };
15505
- picomatch4.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
15505
+ picomatch5.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
15506
15506
  if (!input || typeof input !== "string") {
15507
15507
  throw new TypeError("Expected a non-empty string");
15508
15508
  }
@@ -15513,9 +15513,9 @@ var require_picomatch3 = __commonJS({
15513
15513
  if (!parsed.output) {
15514
15514
  parsed = parse(input, options);
15515
15515
  }
15516
- return picomatch4.compileRe(parsed, options, returnOutput, returnState);
15516
+ return picomatch5.compileRe(parsed, options, returnOutput, returnState);
15517
15517
  };
15518
- picomatch4.toRegex = (source, options) => {
15518
+ picomatch5.toRegex = (source, options) => {
15519
15519
  try {
15520
15520
  const opts = options || {};
15521
15521
  return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
@@ -15524,8 +15524,8 @@ var require_picomatch3 = __commonJS({
15524
15524
  return /$^/;
15525
15525
  }
15526
15526
  };
15527
- picomatch4.constants = constants3;
15528
- module2.exports = picomatch4;
15527
+ picomatch5.constants = constants3;
15528
+ module2.exports = picomatch5;
15529
15529
  }
15530
15530
  });
15531
15531
 
@@ -15543,7 +15543,7 @@ var require_micromatch = __commonJS({
15543
15543
  "use strict";
15544
15544
  var util = require("util");
15545
15545
  var braces = require_braces();
15546
- var picomatch4 = require_picomatch4();
15546
+ var picomatch5 = require_picomatch4();
15547
15547
  var utils = require_utils3();
15548
15548
  var isEmptyString = (v) => v === "" || v === "./";
15549
15549
  var hasBraces = (v) => {
@@ -15564,7 +15564,7 @@ var require_micromatch = __commonJS({
15564
15564
  }
15565
15565
  };
15566
15566
  for (let i = 0; i < patterns.length; i++) {
15567
- let isMatch = picomatch4(String(patterns[i]), { ...options, onResult }, true);
15567
+ let isMatch = picomatch5(String(patterns[i]), { ...options, onResult }, true);
15568
15568
  let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
15569
15569
  if (negated) negatives++;
15570
15570
  for (let item of list) {
@@ -15592,8 +15592,8 @@ var require_micromatch = __commonJS({
15592
15592
  return matches;
15593
15593
  };
15594
15594
  micromatch.match = micromatch;
15595
- micromatch.matcher = (pattern, options) => picomatch4(pattern, options);
15596
- micromatch.isMatch = (str, patterns, options) => picomatch4(patterns, options)(str);
15595
+ micromatch.matcher = (pattern, options) => picomatch5(pattern, options);
15596
+ micromatch.isMatch = (str, patterns, options) => picomatch5(patterns, options)(str);
15597
15597
  micromatch.any = micromatch.isMatch;
15598
15598
  micromatch.not = (list, patterns, options = {}) => {
15599
15599
  patterns = [].concat(patterns).map(String);
@@ -15640,7 +15640,7 @@ var require_micromatch = __commonJS({
15640
15640
  micromatch.some = (list, patterns, options) => {
15641
15641
  let items = [].concat(list);
15642
15642
  for (let pattern of [].concat(patterns)) {
15643
- let isMatch = picomatch4(String(pattern), options);
15643
+ let isMatch = picomatch5(String(pattern), options);
15644
15644
  if (items.some((item) => isMatch(item))) {
15645
15645
  return true;
15646
15646
  }
@@ -15650,7 +15650,7 @@ var require_micromatch = __commonJS({
15650
15650
  micromatch.every = (list, patterns, options) => {
15651
15651
  let items = [].concat(list);
15652
15652
  for (let pattern of [].concat(patterns)) {
15653
- let isMatch = picomatch4(String(pattern), options);
15653
+ let isMatch = picomatch5(String(pattern), options);
15654
15654
  if (!items.every((item) => isMatch(item))) {
15655
15655
  return false;
15656
15656
  }
@@ -15661,23 +15661,23 @@ var require_micromatch = __commonJS({
15661
15661
  if (typeof str !== "string") {
15662
15662
  throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
15663
15663
  }
15664
- return [].concat(patterns).every((p) => picomatch4(p, options)(str));
15664
+ return [].concat(patterns).every((p) => picomatch5(p, options)(str));
15665
15665
  };
15666
15666
  micromatch.capture = (glob, input, options) => {
15667
- let posix = utils.isWindows(options);
15668
- let regex = picomatch4.makeRe(String(glob), { ...options, capture: true });
15669
- let match = regex.exec(posix ? utils.toPosixSlashes(input) : input);
15667
+ let posix2 = utils.isWindows(options);
15668
+ let regex = picomatch5.makeRe(String(glob), { ...options, capture: true });
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
  }
15673
15673
  };
15674
- micromatch.makeRe = (...args) => picomatch4.makeRe(...args);
15675
- micromatch.scan = (...args) => picomatch4.scan(...args);
15674
+ micromatch.makeRe = (...args) => picomatch5.makeRe(...args);
15675
+ micromatch.scan = (...args) => picomatch5.scan(...args);
15676
15676
  micromatch.parse = (patterns, options) => {
15677
15677
  let res = [];
15678
15678
  for (let pattern of [].concat(patterns || [])) {
15679
15679
  for (let str of braces(String(pattern), options)) {
15680
- res.push(picomatch4.parse(str, options));
15680
+ res.push(picomatch5.parse(str, options));
15681
15681
  }
15682
15682
  }
15683
15683
  return res;
@@ -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_path19 = 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.6.0",
18188
+ version: "0.7.1",
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,20 +18250,45 @@ 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
+
18256
+ // src/harness-cli.ts
18257
+ var import_node_fs = require("node:fs");
18258
+ var import_node_path = require("node:path");
18259
+ var HARNESS_LOCK_REL = ".agents/harness.lock.json";
18260
+ var HARNESS_PACKAGE = package_default.name;
18261
+ var SAFE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
18262
+ function lockedHarnessVersion(repo) {
18263
+ const path = (0, import_node_path.join)(repo, HARNESS_LOCK_REL);
18264
+ try {
18265
+ if (!(0, import_node_fs.lstatSync)(path).isFile()) return null;
18266
+ const value = JSON.parse((0, import_node_fs.readFileSync)(path, "utf8"));
18267
+ if (value?.package !== HARNESS_PACKAGE || typeof value.version !== "string") return null;
18268
+ return SAFE_VERSION.test(value.version) ? value.version : null;
18269
+ } catch {
18270
+ return null;
18271
+ }
18272
+ }
18273
+ function harnessInvocation(version) {
18274
+ const pinned = version && SAFE_VERSION.test(version) ? version : "latest";
18275
+ return `npx -y ${HARNESS_PACKAGE}@${pinned}`;
18276
+ }
18277
+ function repoHarnessInvocation(repo) {
18278
+ return harnessInvocation(lockedHarnessVersion(repo));
18279
+ }
18255
18280
 
18256
18281
  // src/manifest.ts
18257
- var import_node_fs2 = require("node:fs");
18258
- var import_node_path2 = require("node:path");
18282
+ var import_node_fs3 = require("node:fs");
18283
+ var import_node_path3 = require("node:path");
18259
18284
  var import_picomatch = __toESM(require_picomatch2(), 1);
18260
18285
  var import_yaml = __toESM(require_dist(), 1);
18261
18286
 
18262
18287
  // src/contracts.ts
18263
18288
  var import_node_child_process = require("node:child_process");
18264
18289
  var import_node_crypto = require("node:crypto");
18265
- var import_node_fs = require("node:fs");
18266
- var import_node_path = require("node:path");
18290
+ var import_node_fs2 = require("node:fs");
18291
+ var import_node_path2 = require("node:path");
18267
18292
  var CONTRACT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
18268
18293
  var WINDOWS_RESERVED_STEM_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;
18269
18294
  var CONTRACTS_REL = ".agents/contracts";
@@ -18275,11 +18300,11 @@ function assertSafeContractId(id) {
18275
18300
  throw new Error(`unsafe contract id "${id}": use a portable 1-128 character ASCII filename (letters, digits, dot, underscore, or hyphen; no reserved device stem)`);
18276
18301
  }
18277
18302
  function contractsDirectory(repo) {
18278
- return (0, import_node_path.resolve)(repo, CONTRACTS_REL);
18303
+ return (0, import_node_path2.resolve)(repo, CONTRACTS_REL);
18279
18304
  }
18280
18305
  function lstatIfExists(path) {
18281
18306
  try {
18282
- return (0, import_node_fs.lstatSync)(path);
18307
+ return (0, import_node_fs2.lstatSync)(path);
18283
18308
  } catch (error) {
18284
18309
  if (error.code === "ENOENT") return null;
18285
18310
  throw error;
@@ -18289,26 +18314,26 @@ function safeDirectory(path, label, create) {
18289
18314
  let stat = lstatIfExists(path);
18290
18315
  if (!stat) {
18291
18316
  if (!create) return false;
18292
- (0, import_node_fs.mkdirSync)(path);
18293
- stat = (0, import_node_fs.lstatSync)(path);
18317
+ (0, import_node_fs2.mkdirSync)(path);
18318
+ stat = (0, import_node_fs2.lstatSync)(path);
18294
18319
  }
18295
18320
  if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`${label} must be a real directory, not a symlink or other file`);
18296
18321
  return true;
18297
18322
  }
18298
18323
  function ensureSafeContractDirectory(repo, create) {
18299
- const repoRoot = (0, import_node_path.resolve)(repo);
18300
- const agents = (0, import_node_path.resolve)(repoRoot, ".agents");
18324
+ const repoRoot = (0, import_node_path2.resolve)(repo);
18325
+ const agents = (0, import_node_path2.resolve)(repoRoot, ".agents");
18301
18326
  if (!safeDirectory(agents, ".agents", create)) return null;
18302
18327
  const contracts = contractsDirectory(repoRoot);
18303
- if ((0, import_node_path.dirname)(contracts) !== agents) throw new Error("contract storage escaped .agents");
18328
+ if ((0, import_node_path2.dirname)(contracts) !== agents) throw new Error("contract storage escaped .agents");
18304
18329
  if (!safeDirectory(contracts, CONTRACTS_REL, create)) return null;
18305
18330
  return contracts;
18306
18331
  }
18307
18332
  function baselinePath(repo, id) {
18308
18333
  assertSafeContractId(id);
18309
18334
  const root = contractsDirectory(repo);
18310
- const candidate = (0, import_node_path.resolve)(root, `${id}.snapshot`);
18311
- if ((0, import_node_path.dirname)(candidate) !== root) throw new Error(`contract baseline escaped ${CONTRACTS_REL}`);
18335
+ const candidate = (0, import_node_path2.resolve)(root, `${id}.snapshot`);
18336
+ if ((0, import_node_path2.dirname)(candidate) !== root) throw new Error(`contract baseline escaped ${CONTRACTS_REL}`);
18312
18337
  return candidate;
18313
18338
  }
18314
18339
  var DEFAULT_COMMAND_TIMEOUT_MS = 2 * 60 * 1e3;
@@ -18334,7 +18359,7 @@ function readBaseline(repo, id) {
18334
18359
  const stat = lstatIfExists(path);
18335
18360
  if (!stat) return null;
18336
18361
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`${CONTRACTS_REL}/${id}.snapshot must be a regular file`);
18337
- return (0, import_node_fs.readFileSync)(path, "utf8");
18362
+ return (0, import_node_fs2.readFileSync)(path, "utf8");
18338
18363
  }
18339
18364
  function writeBaseline(repo, id, content) {
18340
18365
  const path = baselinePath(repo, id);
@@ -18344,14 +18369,14 @@ function writeBaseline(repo, id, content) {
18344
18369
  const stat = existing;
18345
18370
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`${CONTRACTS_REL}/${id}.snapshot must be a regular file`);
18346
18371
  }
18347
- const temp = (0, import_node_path.resolve)(directory, `.${(0, import_node_path.basename)(path)}.tmp-${process.pid}-${(0, import_node_crypto.randomBytes)(8).toString("hex")}`);
18348
- if ((0, import_node_path.dirname)(temp) !== directory) throw new Error(`temporary contract baseline escaped ${CONTRACTS_REL}`);
18372
+ const temp = (0, import_node_path2.resolve)(directory, `.${(0, import_node_path2.basename)(path)}.tmp-${process.pid}-${(0, import_node_crypto.randomBytes)(8).toString("hex")}`);
18373
+ if ((0, import_node_path2.dirname)(temp) !== directory) throw new Error(`temporary contract baseline escaped ${CONTRACTS_REL}`);
18349
18374
  try {
18350
- (0, import_node_fs.writeFileSync)(temp, content, { encoding: "utf8", flag: "wx" });
18351
- (0, import_node_fs.renameSync)(temp, path);
18375
+ (0, import_node_fs2.writeFileSync)(temp, content, { encoding: "utf8", flag: "wx" });
18376
+ (0, import_node_fs2.renameSync)(temp, path);
18352
18377
  } finally {
18353
18378
  try {
18354
- (0, import_node_fs.unlinkSync)(temp);
18379
+ (0, import_node_fs2.unlinkSync)(temp);
18355
18380
  } catch {
18356
18381
  }
18357
18382
  }
@@ -18362,14 +18387,14 @@ var MANIFEST_REL = ".agents/manifest.yaml";
18362
18387
  var SUPPORTED_MANIFEST_SPECS = ["ai-harness/v0", "ai-harness/v1"];
18363
18388
  var MAX_GLOB_PATTERN_LENGTH = 4096;
18364
18389
  function manifestPath(repo) {
18365
- return (0, import_node_path2.join)(repo, MANIFEST_REL);
18390
+ return (0, import_node_path3.join)(repo, MANIFEST_REL);
18366
18391
  }
18367
18392
  function loadManifest(repo) {
18368
18393
  const p = manifestPath(repo);
18369
- if (!(0, import_node_fs2.existsSync)(p)) {
18394
+ if (!(0, import_node_fs3.existsSync)(p)) {
18370
18395
  throw new Error(`\u672A\u627E\u5230 ${MANIFEST_REL}\uFF08\u5728 ${repo}\uFF09\u3002\u5148\u8DD1 \`harness-kit init\`\u3002`);
18371
18396
  }
18372
- const parsed = import_yaml.default.parse((0, import_node_fs2.readFileSync)(p, "utf8"));
18397
+ const parsed = import_yaml.default.parse((0, import_node_fs3.readFileSync)(p, "utf8"));
18373
18398
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`${MANIFEST_REL} \u6839\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61`);
18374
18399
  return parsed;
18375
18400
  }
@@ -18447,7 +18472,7 @@ function validateManifest(m) {
18447
18472
  function checkRelativePath(value, prefix) {
18448
18473
  if (typeof value !== "string") return;
18449
18474
  const components = value.split(/[\\/]/);
18450
- if (!value || value.includes("\0") || (0, import_node_path2.isAbsolute)(value) || components.includes(".."))
18475
+ if (!value || value.includes("\0") || (0, import_node_path3.isAbsolute)(value) || components.includes(".."))
18451
18476
  issues.push({ level: "error", msg: `${prefix} \u5FC5\u987B\u662F\u58F0\u660E\u6839\u76EE\u5F55\u5185\u7684\u975E\u7A7A\u76F8\u5BF9\u8DEF\u5F84\uFF0C\u4E0D\u80FD\u8D8A\u754C: ${value}` });
18452
18477
  }
18453
18478
  function checkRelativePaths(value, prefix) {
@@ -18761,8 +18786,8 @@ function validateManifest(m) {
18761
18786
 
18762
18787
  // src/managed-files.ts
18763
18788
  var import_node_crypto2 = require("node:crypto");
18764
- var import_node_fs3 = require("node:fs");
18765
- var import_node_path3 = require("node:path");
18789
+ var import_node_fs4 = require("node:fs");
18790
+ var import_node_path4 = require("node:path");
18766
18791
  function isErrno(error, code) {
18767
18792
  return error?.code === code;
18768
18793
  }
@@ -18783,29 +18808,29 @@ function sameIdentity(left, right) {
18783
18808
  return left.dev === right.dev && left.ino === right.ino && left.mode === right.mode && left.size === right.size && left.mtimeMs === right.mtimeMs;
18784
18809
  }
18785
18810
  function inside(root, candidate) {
18786
- const rel = (0, import_node_path3.relative)(root, candidate);
18787
- return rel === "" || rel !== ".." && !rel.startsWith(`..${import_node_path3.sep}`) && !(0, import_node_path3.isAbsolute)(rel);
18811
+ const rel = (0, import_node_path4.relative)(root, candidate);
18812
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${import_node_path4.sep}`) && !(0, import_node_path4.isAbsolute)(rel);
18788
18813
  }
18789
18814
  function repositoryRoot(repo) {
18790
18815
  let root;
18791
18816
  try {
18792
- root = (0, import_node_fs3.realpathSync)(repo);
18817
+ root = (0, import_node_fs4.realpathSync)(repo);
18793
18818
  } catch (error) {
18794
18819
  throw new Error(`cannot resolve repository root ${repo}: ${errorMessage(error)}`);
18795
18820
  }
18796
- if (!(0, import_node_fs3.statSync)(root).isDirectory()) throw new Error(`repository root is not a directory: ${repo}`);
18821
+ if (!(0, import_node_fs4.statSync)(root).isDirectory()) throw new Error(`repository root is not a directory: ${repo}`);
18797
18822
  return root;
18798
18823
  }
18799
18824
  function targetPath(root, relativePath) {
18800
18825
  if (typeof relativePath !== "string" || relativePath.length === 0 || relativePath.includes("\0")) {
18801
18826
  throw new Error("generated target path must be a non-empty string");
18802
18827
  }
18803
- if ((0, import_node_path3.isAbsolute)(relativePath)) throw new Error(`generated target path must be relative: ${relativePath}`);
18804
- const normalized = (0, import_node_path3.normalize)(relativePath);
18805
- if (normalized === ".." || normalized.startsWith(`..${import_node_path3.sep}`)) {
18828
+ if ((0, import_node_path4.isAbsolute)(relativePath)) throw new Error(`generated target path must be relative: ${relativePath}`);
18829
+ const normalized = (0, import_node_path4.normalize)(relativePath);
18830
+ if (normalized === ".." || normalized.startsWith(`..${import_node_path4.sep}`)) {
18806
18831
  throw new Error(`generated target path escapes repository: ${relativePath}`);
18807
18832
  }
18808
- const absolutePath = (0, import_node_path3.resolve)(root, relativePath);
18833
+ const absolutePath = (0, import_node_path4.resolve)(root, relativePath);
18809
18834
  if (absolutePath === root || !inside(root, absolutePath)) {
18810
18835
  throw new Error(`generated target path escapes repository: ${relativePath}`);
18811
18836
  }
@@ -18816,12 +18841,12 @@ function preflightParent(root, parent, relativePath) {
18816
18841
  while (true) {
18817
18842
  let stat;
18818
18843
  try {
18819
- stat = (0, import_node_fs3.lstatSync)(cursor);
18844
+ stat = (0, import_node_fs4.lstatSync)(cursor);
18820
18845
  } catch (error) {
18821
18846
  if (!isErrno(error, "ENOENT")) {
18822
18847
  throw new Error(`cannot inspect parent for ${relativePath}: ${errorMessage(error)}`);
18823
18848
  }
18824
- const next = (0, import_node_path3.dirname)(cursor);
18849
+ const next = (0, import_node_path4.dirname)(cursor);
18825
18850
  if (next === cursor || !inside(root, next)) {
18826
18851
  throw new Error(`target ${relativePath} parent escapes repository`);
18827
18852
  }
@@ -18830,7 +18855,7 @@ function preflightParent(root, parent, relativePath) {
18830
18855
  }
18831
18856
  let resolvedParent;
18832
18857
  try {
18833
- resolvedParent = (0, import_node_fs3.realpathSync)(cursor);
18858
+ resolvedParent = (0, import_node_fs4.realpathSync)(cursor);
18834
18859
  } catch (error) {
18835
18860
  throw new Error(`cannot resolve parent for ${relativePath}: ${errorMessage(error)}`);
18836
18861
  }
@@ -18843,37 +18868,37 @@ function preflightParent(root, parent, relativePath) {
18843
18868
  if (!stat.isDirectory()) {
18844
18869
  throw new Error(`target ${relativePath} parent is not a directory`);
18845
18870
  }
18846
- if (!(0, import_node_fs3.statSync)(resolvedParent).isDirectory()) {
18871
+ if (!(0, import_node_fs4.statSync)(resolvedParent).isDirectory()) {
18847
18872
  throw new Error(`target ${relativePath} parent is not a directory`);
18848
18873
  }
18849
18874
  return;
18850
18875
  }
18851
18876
  }
18852
18877
  function ensureSafeParent(root, parent, relativePath) {
18853
- const rel = (0, import_node_path3.relative)(root, parent);
18878
+ const rel = (0, import_node_path4.relative)(root, parent);
18854
18879
  if (!inside(root, parent)) throw new Error(`target ${relativePath} parent escapes repository`);
18855
18880
  let cursor = root;
18856
- for (const component of rel.split(import_node_path3.sep).filter(Boolean)) {
18857
- cursor = (0, import_node_path3.join)(cursor, component);
18881
+ for (const component of rel.split(import_node_path4.sep).filter(Boolean)) {
18882
+ cursor = (0, import_node_path4.join)(cursor, component);
18858
18883
  let stat;
18859
18884
  try {
18860
- stat = (0, import_node_fs3.lstatSync)(cursor);
18885
+ stat = (0, import_node_fs4.lstatSync)(cursor);
18861
18886
  } catch (error) {
18862
18887
  if (!isErrno(error, "ENOENT")) {
18863
18888
  throw new Error(`cannot inspect parent for ${relativePath}: ${errorMessage(error)}`);
18864
18889
  }
18865
18890
  try {
18866
- (0, import_node_fs3.mkdirSync)(cursor);
18891
+ (0, import_node_fs4.mkdirSync)(cursor);
18867
18892
  } catch (mkdirError) {
18868
18893
  if (!isErrno(mkdirError, "EEXIST")) {
18869
18894
  throw new Error(`cannot create parent for ${relativePath}: ${errorMessage(mkdirError)}`);
18870
18895
  }
18871
18896
  }
18872
- stat = (0, import_node_fs3.lstatSync)(cursor);
18897
+ stat = (0, import_node_fs4.lstatSync)(cursor);
18873
18898
  }
18874
18899
  let resolvedParent;
18875
18900
  try {
18876
- resolvedParent = (0, import_node_fs3.realpathSync)(cursor);
18901
+ resolvedParent = (0, import_node_fs4.realpathSync)(cursor);
18877
18902
  } catch (error) {
18878
18903
  throw new Error(`cannot resolve parent for ${relativePath}: ${errorMessage(error)}`);
18879
18904
  }
@@ -18886,37 +18911,37 @@ function ensureSafeParent(root, parent, relativePath) {
18886
18911
  if (!stat.isDirectory()) {
18887
18912
  throw new Error(`target ${relativePath} parent is not a directory`);
18888
18913
  }
18889
- if (!(0, import_node_fs3.statSync)(resolvedParent).isDirectory()) {
18914
+ if (!(0, import_node_fs4.statSync)(resolvedParent).isDirectory()) {
18890
18915
  throw new Error(`target ${relativePath} parent is not a directory`);
18891
18916
  }
18892
18917
  }
18893
18918
  }
18894
18919
  function openRegularNoFollow(path, expected) {
18895
- const fd = (0, import_node_fs3.openSync)(path, import_node_fs3.constants.O_RDONLY | import_node_fs3.constants.O_NOFOLLOW);
18920
+ const fd = (0, import_node_fs4.openSync)(path, import_node_fs4.constants.O_RDONLY | import_node_fs4.constants.O_NOFOLLOW);
18896
18921
  try {
18897
- const opened = (0, import_node_fs3.fstatSync)(fd);
18922
+ const opened = (0, import_node_fs4.fstatSync)(fd);
18898
18923
  if (!opened.isFile()) throw new Error("target is no longer a regular file");
18899
18924
  const identity = identityOf(opened);
18900
18925
  if (!sameIdentity(expected, identity)) throw new Error("target changed during preflight");
18901
18926
  return { fd, identity };
18902
18927
  } catch (error) {
18903
- (0, import_node_fs3.closeSync)(fd);
18928
+ (0, import_node_fs4.closeSync)(fd);
18904
18929
  throw error;
18905
18930
  }
18906
18931
  }
18907
18932
  function allowedClaudeAlias(root, absolutePath, linkTarget) {
18908
- if (absolutePath !== (0, import_node_path3.join)(root, "CLAUDE.md") || (0, import_node_path3.isAbsolute)(linkTarget)) return false;
18909
- const normalized = (0, import_node_path3.normalize)(linkTarget);
18910
- if (normalized === ".." || normalized.startsWith(`..${import_node_path3.sep}`)) return false;
18911
- return (0, import_node_path3.resolve)((0, import_node_path3.dirname)(absolutePath), linkTarget) === (0, import_node_path3.join)(root, "AGENTS.md");
18933
+ if (absolutePath !== (0, import_node_path4.join)(root, "CLAUDE.md") || (0, import_node_path4.isAbsolute)(linkTarget)) return false;
18934
+ const normalized = (0, import_node_path4.normalize)(linkTarget);
18935
+ if (normalized === ".." || normalized.startsWith(`..${import_node_path4.sep}`)) return false;
18936
+ return (0, import_node_path4.resolve)((0, import_node_path4.dirname)(absolutePath), linkTarget) === (0, import_node_path4.join)(root, "AGENTS.md");
18912
18937
  }
18913
18938
  function inspectOne(root, relativePath, content) {
18914
18939
  if (typeof content !== "string") throw new Error(`generated content for ${relativePath} must be a string`);
18915
18940
  const absolutePath = targetPath(root, relativePath);
18916
- preflightParent(root, (0, import_node_path3.dirname)(absolutePath), relativePath);
18941
+ preflightParent(root, (0, import_node_path4.dirname)(absolutePath), relativePath);
18917
18942
  let stat;
18918
18943
  try {
18919
- stat = (0, import_node_fs3.lstatSync)(absolutePath);
18944
+ stat = (0, import_node_fs4.lstatSync)(absolutePath);
18920
18945
  } catch (error) {
18921
18946
  if (isErrno(error, "ENOENT")) {
18922
18947
  return {
@@ -18934,7 +18959,7 @@ function inspectOne(root, relativePath, content) {
18934
18959
  }
18935
18960
  const identity = identityOf(stat);
18936
18961
  if (stat.isSymbolicLink()) {
18937
- const linkTarget = (0, import_node_fs3.readlinkSync)(absolutePath);
18962
+ const linkTarget = (0, import_node_fs4.readlinkSync)(absolutePath);
18938
18963
  if (!allowedClaudeAlias(root, absolutePath, linkTarget)) {
18939
18964
  throw new Error(`target ${relativePath} is an unsafe symlink; only CLAUDE.md -> AGENTS.md is allowed`);
18940
18965
  }
@@ -18953,7 +18978,7 @@ function inspectOne(root, relativePath, content) {
18953
18978
  if (!stat.isFile()) throw new Error(`target ${relativePath} is not a regular file`);
18954
18979
  const opened = openRegularNoFollow(absolutePath, identity);
18955
18980
  try {
18956
- const currentContent = (0, import_node_fs3.readFileSync)(opened.fd, "utf8");
18981
+ const currentContent = (0, import_node_fs4.readFileSync)(opened.fd, "utf8");
18957
18982
  return {
18958
18983
  relativePath,
18959
18984
  absolutePath,
@@ -18965,7 +18990,7 @@ function inspectOne(root, relativePath, content) {
18965
18990
  identity: opened.identity
18966
18991
  };
18967
18992
  } finally {
18968
- (0, import_node_fs3.closeSync)(opened.fd);
18993
+ (0, import_node_fs4.closeSync)(opened.fd);
18969
18994
  }
18970
18995
  }
18971
18996
  function preflightTargets(repo, targets) {
@@ -18994,18 +19019,18 @@ function inspectManagedFiles(repo, targets) {
18994
19019
  return preflightTargets(repo, targets).targets.map(publicInspection);
18995
19020
  }
18996
19021
  function siblingArtifact(path, role) {
18997
- return (0, import_node_path3.join)((0, import_node_path3.dirname)(path), `.${(0, import_node_path3.basename)(path)}.harness-kit-${process.pid}-${(0, import_node_crypto2.randomUUID)()}.${role}`);
19022
+ return (0, import_node_path4.join)((0, import_node_path4.dirname)(path), `.${(0, import_node_path4.basename)(path)}.harness-kit-${process.pid}-${(0, import_node_crypto2.randomUUID)()}.${role}`);
18998
19023
  }
18999
19024
  function writeExclusive(path, content, mode) {
19000
- const fd = (0, import_node_fs3.openSync)(
19025
+ const fd = (0, import_node_fs4.openSync)(
19001
19026
  path,
19002
- import_node_fs3.constants.O_WRONLY | import_node_fs3.constants.O_CREAT | import_node_fs3.constants.O_EXCL | import_node_fs3.constants.O_NOFOLLOW,
19027
+ import_node_fs4.constants.O_WRONLY | import_node_fs4.constants.O_CREAT | import_node_fs4.constants.O_EXCL | import_node_fs4.constants.O_NOFOLLOW,
19003
19028
  mode & 511
19004
19029
  );
19005
19030
  try {
19006
- (0, import_node_fs3.writeFileSync)(fd, content);
19031
+ (0, import_node_fs4.writeFileSync)(fd, content);
19007
19032
  } finally {
19008
- (0, import_node_fs3.closeSync)(fd);
19033
+ (0, import_node_fs4.closeSync)(fd);
19009
19034
  }
19010
19035
  }
19011
19036
  function unchanged(previous, current) {
@@ -19026,7 +19051,7 @@ function assertTargetStillCurrent(root, target) {
19026
19051
  }
19027
19052
  function removeBestEffort(path) {
19028
19053
  try {
19029
- (0, import_node_fs3.unlinkSync)(path);
19054
+ (0, import_node_fs4.unlinkSync)(path);
19030
19055
  } catch (error) {
19031
19056
  if (!isErrno(error, "ENOENT")) {
19032
19057
  }
@@ -19034,7 +19059,7 @@ function removeBestEffort(path) {
19034
19059
  }
19035
19060
  function currentIdentity(path) {
19036
19061
  try {
19037
- return identityOf((0, import_node_fs3.lstatSync)(path));
19062
+ return identityOf((0, import_node_fs4.lstatSync)(path));
19038
19063
  } catch (error) {
19039
19064
  if (isErrno(error, "ENOENT")) return null;
19040
19065
  throw error;
@@ -19046,10 +19071,10 @@ function restoreDisplacedRegular(item) {
19046
19071
  if (current !== null) {
19047
19072
  if (item.installedIdentity === null || !sameIdentity(item.installedIdentity, current))
19048
19073
  throw new Error("target changed during transaction; preserving the newer path and rollback backup");
19049
- (0, import_node_fs3.unlinkSync)(item.target.absolutePath);
19074
+ (0, import_node_fs4.unlinkSync)(item.target.absolutePath);
19050
19075
  }
19051
- (0, import_node_fs3.linkSync)(item.backupPath, item.target.absolutePath);
19052
- (0, import_node_fs3.unlinkSync)(item.backupPath);
19076
+ (0, import_node_fs4.linkSync)(item.backupPath, item.target.absolutePath);
19077
+ (0, import_node_fs4.unlinkSync)(item.backupPath);
19053
19078
  item.backupCreated = false;
19054
19079
  item.installedIdentity = null;
19055
19080
  }
@@ -19072,7 +19097,7 @@ function rollback(staged) {
19072
19097
  throw new Error("target changed after transaction write; preserving the newer path and rollback backup");
19073
19098
  if (item.target.kind === "missing") {
19074
19099
  try {
19075
- (0, import_node_fs3.unlinkSync)(item.target.absolutePath);
19100
+ (0, import_node_fs4.unlinkSync)(item.target.absolutePath);
19076
19101
  } catch (error) {
19077
19102
  if (!isErrno(error, "ENOENT")) throw error;
19078
19103
  }
@@ -19101,10 +19126,10 @@ function assertInstalledTargetsStillCurrent(staged) {
19101
19126
  throw new Error(`generated target changed during transaction: ${item.target.relativePath}`);
19102
19127
  const opened = openRegularNoFollow(item.target.absolutePath, item.installedIdentity);
19103
19128
  try {
19104
- if ((0, import_node_fs3.readFileSync)(opened.fd, "utf8") !== item.target.content)
19129
+ if ((0, import_node_fs4.readFileSync)(opened.fd, "utf8") !== item.target.content)
19105
19130
  throw new Error(`generated target content changed during transaction: ${item.target.relativePath}`);
19106
19131
  } finally {
19107
- (0, import_node_fs3.closeSync)(opened.fd);
19132
+ (0, import_node_fs4.closeSync)(opened.fd);
19108
19133
  }
19109
19134
  }
19110
19135
  }
@@ -19115,22 +19140,22 @@ function writeManagedFiles(repo, targets, options = {}) {
19115
19140
  (target) => target.kind !== "allowed-alias" && !target.satisfiesDesired
19116
19141
  );
19117
19142
  const staged = [];
19118
- const rename = options.rename ?? import_node_fs3.renameSync;
19119
- const link = options.link ?? import_node_fs3.linkSync;
19143
+ const rename = options.rename ?? import_node_fs4.renameSync;
19144
+ const link = options.link ?? import_node_fs4.linkSync;
19120
19145
  try {
19121
19146
  for (const target of writable) {
19122
- ensureSafeParent(preflight.root, (0, import_node_path3.dirname)(target.absolutePath), target.relativePath);
19147
+ ensureSafeParent(preflight.root, (0, import_node_path4.dirname)(target.absolutePath), target.relativePath);
19123
19148
  const tempPath = siblingArtifact(target.absolutePath, "tmp");
19124
19149
  const backupPath = target.kind === "regular" ? siblingArtifact(target.absolutePath, "backup") : null;
19125
19150
  const mode = target.identity?.mode ?? 438;
19126
19151
  writeExclusive(tempPath, target.content, mode);
19127
- if (target.identity !== null) (0, import_node_fs3.chmodSync)(tempPath, target.identity.mode & 511);
19152
+ if (target.identity !== null) (0, import_node_fs4.chmodSync)(tempPath, target.identity.mode & 511);
19128
19153
  const item = {
19129
19154
  target,
19130
19155
  tempPath,
19131
19156
  backupPath,
19132
19157
  backupCreated: false,
19133
- replacementIdentity: identityOf((0, import_node_fs3.lstatSync)(tempPath)),
19158
+ replacementIdentity: identityOf((0, import_node_fs4.lstatSync)(tempPath)),
19134
19159
  installedIdentity: null
19135
19160
  };
19136
19161
  staged.push(item);
@@ -19141,19 +19166,19 @@ function writeManagedFiles(repo, targets, options = {}) {
19141
19166
  if (item.target.kind === "missing") {
19142
19167
  link(item.tempPath, item.target.absolutePath);
19143
19168
  item.installedIdentity = item.replacementIdentity;
19144
- (0, import_node_fs3.unlinkSync)(item.tempPath);
19169
+ (0, import_node_fs4.unlinkSync)(item.tempPath);
19145
19170
  } else {
19146
19171
  if (item.backupPath === null || item.target.identity === null)
19147
19172
  throw new Error(`regular target has no displacement backup: ${item.target.relativePath}`);
19148
19173
  rename(item.target.absolutePath, item.backupPath);
19149
19174
  item.backupCreated = true;
19150
- const displacedIdentity = identityOf((0, import_node_fs3.lstatSync)(item.backupPath));
19151
- const displacedContent = (0, import_node_fs3.readFileSync)(item.backupPath, "utf8");
19175
+ const displacedIdentity = identityOf((0, import_node_fs4.lstatSync)(item.backupPath));
19176
+ const displacedContent = (0, import_node_fs4.readFileSync)(item.backupPath, "utf8");
19152
19177
  if (!sameIdentity(item.target.identity, displacedIdentity) || displacedContent !== item.target.currentContent)
19153
19178
  throw new Error(`generated target changed during commit: ${item.target.relativePath}`);
19154
19179
  link(item.tempPath, item.target.absolutePath);
19155
19180
  item.installedIdentity = item.replacementIdentity;
19156
- (0, import_node_fs3.unlinkSync)(item.tempPath);
19181
+ (0, import_node_fs4.unlinkSync)(item.tempPath);
19157
19182
  }
19158
19183
  }
19159
19184
  assertInstalledTargetsStillCurrent(staged);
@@ -19173,25 +19198,25 @@ function writeManagedFiles(repo, targets, options = {}) {
19173
19198
 
19174
19199
  // src/util.ts
19175
19200
  var import_node_crypto3 = require("node:crypto");
19176
- var import_node_fs4 = require("node:fs");
19177
- var import_node_path4 = require("node:path");
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,19 +19265,19 @@ 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(" Prefer `harness-kit task start` before editing so committed work stays in the deliver scope.");
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
19272
  if (hasImpactMap) {
19243
19273
  L.push(
19244
- "3. Run `harness-kit deliver` (impact-driven checks + verify + stamp). Only `status=accepted` (or clean `no-change`) means the task is done. If `needs-work`, fix and re-run \u2014 do not claim completion without an accepted stamp."
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.`
19245
19275
  );
19246
19276
  L.push(
19247
- " Optional: `harness-kit task start` before editing so later commits stay in scope; without it, deliver falls back to the current worktree git diff vs HEAD."
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.`
19248
19278
  );
19249
19279
  } else {
19250
- L.push("3. Run `harness-kit deliver` (or at least `harness-kit verify`). Do not claim completion without a passing stamp/verify.");
19280
+ L.push(`3. Run \`${hk} deliver\` (or at least \`${hk} verify\`). Do not claim completion without a passing stamp/verify.`);
19251
19281
  }
19252
19282
  L.push(
19253
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."
@@ -19300,7 +19330,7 @@ function renderAgentsMd(m) {
19300
19330
  const how = inv.enforcement ? "enforced" : inv.check ? "checked" : "manual";
19301
19331
  L.push(`- ${inv.rule} [${how}]`);
19302
19332
  }
19303
- L.push("", "Run `harness-kit verify` to check the enforceable ones.", "");
19333
+ L.push("", `Run \`${hk} verify\` to check the enforceable ones.`, "");
19304
19334
  }
19305
19335
  L.push("## Knowledge & maps (load on demand)", "");
19306
19336
  if (!m.knowledge?.length || m.knowledge.some((knowledge) => (knowledge.root ?? "agents") === "agents"))
@@ -19311,7 +19341,7 @@ function renderAgentsMd(m) {
19311
19341
  L.push("- Full commands, environment, and registered knowledge catalog: `.agents/reference.md`");
19312
19342
  if (m.routing?.length) L.push("- Change-type routing (read before editing): `.agents/routing.md`");
19313
19343
  if (m.modules?.length) L.push("- Module map + common pitfalls: `.agents/modules.md`");
19314
- 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\``);
19315
19345
  L.push("- Tooling adoption log (earn heavier tooling): `.agents/adoption.md`");
19316
19346
  if (m.playbooks?.dir) L.push(`- Task playbooks: \`.agents/${m.playbooks.dir}\``);
19317
19347
  L.push("");
@@ -19417,6 +19447,9 @@ var DOCUMENT_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".mdx", ".markdown", "
19417
19447
  var ALWAYS_PRUNED_DIRECTORY_NAMES = /* @__PURE__ */ new Set([".git", ".hg", ".svn"]);
19418
19448
  var GENERATED_MARKER = "<!-- GENERATED by ai-harness \u2014 DO NOT EDIT.";
19419
19449
  var CANDIDATE_METADATA = "candidate.json";
19450
+ var LANDING_ROOT = ".agents";
19451
+ var LANDING_EXCLUDED_FILES = /* @__PURE__ */ new Set([MANIFEST_REL, HARNESS_LOCK_REL, ".agents/.harness-state.json", ...MANAGED_ENTRY_PATHS]);
19452
+ var LANDING_EXCLUDED_DIRECTORIES = /* @__PURE__ */ new Set([".agents/adoption", ".agents/hooks"]);
19420
19453
  var RECEIPT_DEFAULT = "adoption-audit-receipt.json";
19421
19454
  var ADOPTION_CANDIDATE_SCHEMA = "ai-harness/adoption-candidate/v1";
19422
19455
  var ADOPTION_RECEIPT_SCHEMA = "ai-harness/adoption-audit-receipt/v1";
@@ -19428,7 +19461,7 @@ function validPermissionMode(mode) {
19428
19461
  }
19429
19462
  function safeEvidencePath(path) {
19430
19463
  try {
19431
- return safeRelativePath(path, "legacy evidence") === path && !path.startsWith(`${LEGACY_DIR_REL}${import_node_path5.sep}`);
19464
+ return safeRelativePath(path, "legacy evidence") === path && !path.startsWith(`${LEGACY_DIR_REL}${import_node_path6.sep}`);
19432
19465
  } catch {
19433
19466
  return false;
19434
19467
  }
@@ -19438,39 +19471,39 @@ function isErrno2(error, code) {
19438
19471
  }
19439
19472
  function ensureNoSymlinkDirectoryChain(root, directory, label, create) {
19440
19473
  if (!inside2(root, directory)) throw new Error(`${label} parent escapes the repository`);
19441
- const rel = (0, import_node_path5.relative)(root, directory);
19474
+ const rel = (0, import_node_path6.relative)(root, directory);
19442
19475
  let cursor = root;
19443
- for (const component of rel.split(import_node_path5.sep).filter(Boolean)) {
19444
- cursor = (0, import_node_path5.join)(cursor, component);
19476
+ for (const component of rel.split(import_node_path6.sep).filter(Boolean)) {
19477
+ cursor = (0, import_node_path6.join)(cursor, component);
19445
19478
  let stat;
19446
19479
  try {
19447
- stat = (0, import_node_fs5.lstatSync)(cursor);
19480
+ stat = (0, import_node_fs6.lstatSync)(cursor);
19448
19481
  } catch (error) {
19449
19482
  if (!isErrno2(error, "ENOENT")) throw new Error(`cannot inspect ${label} parent ${cursor}: ${errorMessage2(error)}`);
19450
19483
  if (!create) return false;
19451
19484
  try {
19452
- (0, import_node_fs5.mkdirSync)(cursor);
19485
+ (0, import_node_fs6.mkdirSync)(cursor);
19453
19486
  } catch (mkdirError) {
19454
19487
  if (!isErrno2(mkdirError, "EEXIST"))
19455
19488
  throw new Error(`cannot create ${label} parent ${cursor}: ${errorMessage2(mkdirError)}`);
19456
19489
  }
19457
- stat = (0, import_node_fs5.lstatSync)(cursor);
19490
+ stat = (0, import_node_fs6.lstatSync)(cursor);
19458
19491
  }
19459
19492
  if (stat.isSymbolicLink()) throw new Error(`${label} parent must not be a symlink: ${cursor}`);
19460
19493
  if (!stat.isDirectory()) throw new Error(`${label} parent must be a directory: ${cursor}`);
19461
- const resolved = (0, import_node_fs5.realpathSync)(cursor);
19494
+ const resolved = (0, import_node_fs6.realpathSync)(cursor);
19462
19495
  if (!inside2(root, resolved)) throw new Error(`${label} parent resolves outside the repository: ${cursor}`);
19463
19496
  }
19464
19497
  return true;
19465
19498
  }
19466
19499
  function readOptionalRepositoryFile(repoRoot, relativePath, label, afterLstat) {
19467
19500
  const normalized = safeRelativePath(relativePath, label);
19468
- const absolute = (0, import_node_path5.resolve)(repoRoot, normalized);
19501
+ const absolute = (0, import_node_path6.resolve)(repoRoot, normalized);
19469
19502
  if (!inside2(repoRoot, absolute) || absolute === repoRoot) throw new Error(`${label} path escapes the repository`);
19470
- if (!ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path5.dirname)(absolute), label, false)) return null;
19503
+ if (!ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)(absolute), label, false)) return null;
19471
19504
  let before;
19472
19505
  try {
19473
- before = (0, import_node_fs5.lstatSync)(absolute);
19506
+ before = (0, import_node_fs6.lstatSync)(absolute);
19474
19507
  } catch (error) {
19475
19508
  if (isErrno2(error, "ENOENT")) return null;
19476
19509
  throw new Error(`cannot inspect ${label}: ${errorMessage2(error)}`);
@@ -19479,22 +19512,22 @@ function readOptionalRepositoryFile(repoRoot, relativePath, label, afterLstat) {
19479
19512
  afterLstat?.(normalized);
19480
19513
  let fd;
19481
19514
  try {
19482
- fd = (0, import_node_fs5.openSync)(absolute, import_node_fs5.constants.O_RDONLY | import_node_fs5.constants.O_NOFOLLOW);
19515
+ fd = (0, import_node_fs6.openSync)(absolute, import_node_fs6.constants.O_RDONLY | import_node_fs6.constants.O_NOFOLLOW);
19483
19516
  } catch (error) {
19484
19517
  throw new Error(`cannot open ${label} without following links: ${errorMessage2(error)}`);
19485
19518
  }
19486
19519
  try {
19487
- const opened = (0, import_node_fs5.fstatSync)(fd);
19520
+ const opened = (0, import_node_fs6.fstatSync)(fd);
19488
19521
  if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino)
19489
19522
  throw new Error(`${label} changed while it was being inspected: ${relativePath}`);
19490
19523
  return {
19491
- bytes: (0, import_node_fs5.readFileSync)(fd),
19524
+ bytes: (0, import_node_fs6.readFileSync)(fd),
19492
19525
  mode: permissionMode(opened.mode),
19493
19526
  dev: opened.dev,
19494
19527
  ino: opened.ino
19495
19528
  };
19496
19529
  } finally {
19497
- (0, import_node_fs5.closeSync)(fd);
19530
+ (0, import_node_fs6.closeSync)(fd);
19498
19531
  }
19499
19532
  }
19500
19533
  function parseAdoptionIndex(raw) {
@@ -19512,7 +19545,7 @@ function parseAdoptionIndex(raw) {
19512
19545
  throw new Error(`${INDEX_REL} \u683C\u5F0F\u65E0\u6548\uFF1Aentry path \u4E0D\u5B89\u5168\u6216\u91CD\u590D`);
19513
19546
  seen.add(entry.path);
19514
19547
  if (entry.type === "file") {
19515
- const expectedSnapshot = (0, import_node_path5.join)(LEGACY_DIR_REL, snapshotName(entry.path));
19548
+ const expectedSnapshot = (0, import_node_path6.join)(LEGACY_DIR_REL, snapshotName(entry.path));
19516
19549
  if (!/^[a-f0-9]{64}$/.test(entry.sha256 ?? "") || entry.snapshot !== expectedSnapshot || !validPermissionMode(entry.mode))
19517
19550
  throw new Error(`${INDEX_REL} \u683C\u5F0F\u65E0\u6548\uFF1A${entry.path} snapshot/mode/hash \u65E0\u6548`);
19518
19551
  } else if (entry.type === "symlink") {
@@ -19533,15 +19566,15 @@ function readAdoptionIndex(repo) {
19533
19566
  }
19534
19567
  function verifyAdoptionEntry(repo, entry) {
19535
19568
  const root = repositoryRoot2(repo);
19536
- const path = (0, import_node_path5.join)(root, entry.path);
19569
+ const path = (0, import_node_path6.join)(root, entry.path);
19537
19570
  let stat;
19538
19571
  try {
19539
- if (!ensureNoSymlinkDirectoryChain(root, (0, import_node_path5.dirname)(path), `legacy source ${entry.path}`, false)) return false;
19540
- stat = (0, import_node_fs5.lstatSync)(path);
19572
+ if (!ensureNoSymlinkDirectoryChain(root, (0, import_node_path6.dirname)(path), `legacy source ${entry.path}`, false)) return false;
19573
+ stat = (0, import_node_fs6.lstatSync)(path);
19541
19574
  } catch {
19542
19575
  return false;
19543
19576
  }
19544
- if (entry.type === "symlink") return stat.isSymbolicLink() && (0, import_node_fs5.readlinkSync)(path) === entry.linkTarget;
19577
+ if (entry.type === "symlink") return stat.isSymbolicLink() && (0, import_node_fs6.readlinkSync)(path) === entry.linkTarget;
19545
19578
  if (!stat.isFile() || stat.isSymbolicLink() || !entry.sha256 || !entry.snapshot || !validPermissionMode(entry.mode)) return false;
19546
19579
  try {
19547
19580
  const source = readOptionalRepositoryFile(root, entry.path, `legacy source ${entry.path}`);
@@ -19555,22 +19588,22 @@ function snapshotName(path) {
19555
19588
  return path.replaceAll("/", "__") + ".pre-harness";
19556
19589
  }
19557
19590
  function captureEntry(repo, path) {
19558
- const absolute = (0, import_node_path5.join)(repo, path);
19591
+ const absolute = (0, import_node_path6.join)(repo, path);
19559
19592
  let stat;
19560
19593
  try {
19561
- stat = (0, import_node_fs5.lstatSync)(absolute);
19594
+ stat = (0, import_node_fs6.lstatSync)(absolute);
19562
19595
  } catch (error) {
19563
19596
  if (isErrno2(error, "ENOENT")) return { entry: null };
19564
19597
  throw error;
19565
19598
  }
19566
- if (stat.isSymbolicLink()) return { entry: { path, type: "symlink", linkTarget: (0, import_node_fs5.readlinkSync)(absolute) } };
19599
+ if (stat.isSymbolicLink()) return { entry: { path, type: "symlink", linkTarget: (0, import_node_fs6.readlinkSync)(absolute) } };
19567
19600
  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`);
19568
19601
  const source = readOptionalRepositoryFile(repo, path, `legacy source ${path}`);
19569
19602
  if (!source) return { entry: null };
19570
19603
  const content = source.bytes;
19571
19604
  if (content.toString("utf8").startsWith(GENERATED_MARKER)) return { entry: null };
19572
19605
  const mode = source.mode;
19573
- const snapshot = (0, import_node_path5.join)(LEGACY_DIR_REL, snapshotName(path));
19606
+ const snapshot = (0, import_node_path6.join)(LEGACY_DIR_REL, snapshotName(path));
19574
19607
  const existing = readOptionalRepositoryFile(repo, snapshot, `legacy snapshot ${path}`);
19575
19608
  if (existing && (sha256(existing.bytes) !== sha256(content) || existing.mode !== mode))
19576
19609
  throw new Error(`\u5DF2\u6709 legacy snapshot \u5185\u5BB9\u6216 mode \u4E0D\u5339\u914D\uFF0C\u62D2\u7EDD\u8986\u76D6: ${snapshot}`);
@@ -19589,25 +19622,25 @@ function findAgentEntryPaths(repo) {
19589
19622
  maxBuffer: 32 * 1024 * 1024
19590
19623
  });
19591
19624
  for (const path of tracked.split("\0").filter(Boolean)) {
19592
- const normalized = (0, import_node_path5.normalize)(path);
19593
- 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);
19625
+ const normalized = (0, import_node_path6.normalize)(path);
19626
+ 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);
19594
19627
  }
19595
19628
  } catch {
19596
19629
  }
19597
19630
  const walk = (directory, prefix) => {
19598
- const directoryStat = (0, import_node_fs5.lstatSync)(directory);
19599
- if (directoryStat.isSymbolicLink() || !directoryStat.isDirectory() || !inside2(repo, (0, import_node_fs5.realpathSync)(directory)))
19631
+ const directoryStat = (0, import_node_fs6.lstatSync)(directory);
19632
+ if (directoryStat.isSymbolicLink() || !directoryStat.isDirectory() || !inside2(repo, (0, import_node_fs6.realpathSync)(directory)))
19600
19633
  throw new Error(`guidance scan directory is unsafe or outside the repository: ${directory}`);
19601
- for (const item of (0, import_node_fs5.readdirSync)(directory, { withFileTypes: true })) {
19602
- const path = prefix ? (0, import_node_path5.join)(prefix, item.name) : item.name;
19603
- const absolute = (0, import_node_path5.join)(directory, item.name);
19604
- const stat = (0, import_node_fs5.lstatSync)(absolute);
19634
+ for (const item of (0, import_node_fs6.readdirSync)(directory, { withFileTypes: true })) {
19635
+ const path = prefix ? (0, import_node_path6.join)(prefix, item.name) : item.name;
19636
+ const absolute = (0, import_node_path6.join)(directory, item.name);
19637
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19605
19638
  if (stat.isSymbolicLink()) {
19606
19639
  if (AGENT_ENTRY_NAMES.has(item.name)) entries.add(path);
19607
19640
  continue;
19608
19641
  }
19609
19642
  if (stat.isDirectory()) {
19610
- const adoptionEvidence = item.name === "adoption" && (0, import_node_path5.basename)(prefix) === ".agents";
19643
+ const adoptionEvidence = item.name === "adoption" && (0, import_node_path6.basename)(prefix) === ".agents";
19611
19644
  if (ALWAYS_PRUNED_DIRECTORY_NAMES.has(item.name) || adoptionEvidence) continue;
19612
19645
  walk(absolute, path);
19613
19646
  continue;
@@ -19627,35 +19660,35 @@ function installPendingSnapshots(repoRoot, pending) {
19627
19660
  let tempPath = null;
19628
19661
  try {
19629
19662
  for (const snapshot of pending) {
19630
- const absolute = (0, import_node_path5.resolve)(repoRoot, snapshot.relativePath);
19631
- ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path5.dirname)(absolute), `legacy snapshot ${snapshot.relativePath}`, true);
19632
- tempPath = (0, import_node_path5.join)(
19633
- (0, import_node_path5.dirname)(absolute),
19634
- `.${(0, import_node_path5.basename)(absolute)}.harness-kit-adoption-${process.pid}-${(0, import_node_crypto4.randomUUID)()}.tmp`
19663
+ const absolute = (0, import_node_path6.resolve)(repoRoot, snapshot.relativePath);
19664
+ ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)(absolute), `legacy snapshot ${snapshot.relativePath}`, true);
19665
+ tempPath = (0, import_node_path6.join)(
19666
+ (0, import_node_path6.dirname)(absolute),
19667
+ `.${(0, import_node_path6.basename)(absolute)}.harness-kit-adoption-${process.pid}-${(0, import_node_crypto4.randomUUID)()}.tmp`
19635
19668
  );
19636
- const fd = (0, import_node_fs5.openSync)(
19669
+ const fd = (0, import_node_fs6.openSync)(
19637
19670
  tempPath,
19638
- import_node_fs5.constants.O_WRONLY | import_node_fs5.constants.O_CREAT | import_node_fs5.constants.O_EXCL | import_node_fs5.constants.O_NOFOLLOW,
19671
+ import_node_fs6.constants.O_WRONLY | import_node_fs6.constants.O_CREAT | import_node_fs6.constants.O_EXCL | import_node_fs6.constants.O_NOFOLLOW,
19639
19672
  snapshot.mode & 511
19640
19673
  );
19641
19674
  try {
19642
- (0, import_node_fs5.writeFileSync)(fd, snapshot.bytes);
19643
- (0, import_node_fs5.fchmodSync)(fd, snapshot.mode);
19644
- const stat = (0, import_node_fs5.fstatSync)(fd);
19675
+ (0, import_node_fs6.writeFileSync)(fd, snapshot.bytes);
19676
+ (0, import_node_fs6.fchmodSync)(fd, snapshot.mode);
19677
+ const stat = (0, import_node_fs6.fstatSync)(fd);
19645
19678
  if (!stat.isFile()) throw new Error(`staged legacy snapshot is not a regular file: ${snapshot.relativePath}`);
19646
19679
  } finally {
19647
- (0, import_node_fs5.closeSync)(fd);
19680
+ (0, import_node_fs6.closeSync)(fd);
19648
19681
  }
19649
- (0, import_node_fs5.linkSync)(tempPath, absolute);
19682
+ (0, import_node_fs6.linkSync)(tempPath, absolute);
19650
19683
  installed.push({ absolutePath: absolute });
19651
- (0, import_node_fs5.unlinkSync)(tempPath);
19684
+ (0, import_node_fs6.unlinkSync)(tempPath);
19652
19685
  tempPath = null;
19653
19686
  }
19654
19687
  return installed;
19655
19688
  } catch (error) {
19656
19689
  if (tempPath) {
19657
19690
  try {
19658
- (0, import_node_fs5.unlinkSync)(tempPath);
19691
+ (0, import_node_fs6.unlinkSync)(tempPath);
19659
19692
  } catch (cleanupError) {
19660
19693
  if (!isErrno2(cleanupError, "ENOENT")) {
19661
19694
  }
@@ -19666,7 +19699,7 @@ function installPendingSnapshots(repoRoot, pending) {
19666
19699
  }
19667
19700
  function entryExists(path) {
19668
19701
  try {
19669
- (0, import_node_fs5.lstatSync)(path);
19702
+ (0, import_node_fs6.lstatSync)(path);
19670
19703
  return true;
19671
19704
  } catch {
19672
19705
  return false;
@@ -19676,8 +19709,8 @@ function textCanContainReferences(bytes) {
19676
19709
  return !bytes.includes(0);
19677
19710
  }
19678
19711
  function isLegacyEntry(repoRoot, path, testHooks) {
19679
- const absolute = (0, import_node_path5.join)(repoRoot, path);
19680
- const stat = (0, import_node_fs5.lstatSync)(absolute);
19712
+ const absolute = (0, import_node_path6.join)(repoRoot, path);
19713
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19681
19714
  if (stat.isSymbolicLink() || !stat.isFile()) return true;
19682
19715
  const source = readOptionalRepositoryFile(
19683
19716
  repoRoot,
@@ -19689,7 +19722,7 @@ function isLegacyEntry(repoRoot, path, testHooks) {
19689
19722
  return !source.bytes.toString("utf8").startsWith(GENERATED_MARKER);
19690
19723
  }
19691
19724
  function documentLike(path) {
19692
- return AGENT_ENTRY_NAMES.has((0, import_node_path5.basename)(path)) || DOCUMENT_EXTENSIONS.has((0, import_node_path5.extname)(path).toLowerCase());
19725
+ return AGENT_ENTRY_NAMES.has((0, import_node_path6.basename)(path)) || DOCUMENT_EXTENSIONS.has((0, import_node_path6.extname)(path).toLowerCase());
19693
19726
  }
19694
19727
  function cleanReference(raw) {
19695
19728
  let value = raw.trim();
@@ -19723,15 +19756,15 @@ function explicitReferences(content) {
19723
19756
  return [...references];
19724
19757
  }
19725
19758
  function resolveGuidanceReference(repoRoot, sourcePath, reference, testHooks) {
19726
- 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)];
19759
+ 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)];
19727
19760
  for (const absolute of candidates) {
19728
19761
  if (!inside2(repoRoot, absolute) || !entryExists(absolute)) continue;
19729
19762
  let stat;
19730
19763
  try {
19731
- const path2 = (0, import_node_path5.relative)(repoRoot, absolute);
19732
- if (!safeEvidencePath(path2) || !ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path5.dirname)(absolute), `guidance ${path2}`, false))
19764
+ const path2 = (0, import_node_path6.relative)(repoRoot, absolute);
19765
+ if (!safeEvidencePath(path2) || !ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)(absolute), `guidance ${path2}`, false))
19733
19766
  continue;
19734
- stat = (0, import_node_fs5.lstatSync)(absolute);
19767
+ stat = (0, import_node_fs6.lstatSync)(absolute);
19735
19768
  if (!stat.isSymbolicLink() && !stat.isFile()) continue;
19736
19769
  if (stat.isFile()) {
19737
19770
  const source = readOptionalRepositoryFile(
@@ -19745,19 +19778,19 @@ function resolveGuidanceReference(repoRoot, sourcePath, reference, testHooks) {
19745
19778
  } catch {
19746
19779
  continue;
19747
19780
  }
19748
- const path = (0, import_node_path5.relative)(repoRoot, absolute);
19781
+ const path = (0, import_node_path6.relative)(repoRoot, absolute);
19749
19782
  if (safeEvidencePath(path)) return path;
19750
19783
  }
19751
19784
  return null;
19752
19785
  }
19753
19786
  function resolveGuidanceSymlinkTarget(repoRoot, sourcePath, linkTarget, testHooks) {
19754
- 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);
19787
+ 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);
19755
19788
  if (!inside2(repoRoot, absolute) || !entryExists(absolute)) return null;
19756
19789
  try {
19757
- const path2 = (0, import_node_path5.relative)(repoRoot, absolute);
19758
- if (!safeEvidencePath(path2) || !ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path5.dirname)(absolute), `guidance ${path2}`, false))
19790
+ const path2 = (0, import_node_path6.relative)(repoRoot, absolute);
19791
+ if (!safeEvidencePath(path2) || !ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)(absolute), `guidance ${path2}`, false))
19759
19792
  return null;
19760
- const stat = (0, import_node_fs5.lstatSync)(absolute);
19793
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19761
19794
  if (!stat.isSymbolicLink() && !stat.isFile()) return null;
19762
19795
  if (stat.isFile()) {
19763
19796
  const source = readOptionalRepositoryFile(
@@ -19771,17 +19804,17 @@ function resolveGuidanceSymlinkTarget(repoRoot, sourcePath, linkTarget, testHook
19771
19804
  } catch {
19772
19805
  return null;
19773
19806
  }
19774
- const path = (0, import_node_path5.relative)(repoRoot, absolute);
19807
+ const path = (0, import_node_path6.relative)(repoRoot, absolute);
19775
19808
  return safeEvidencePath(path) ? path : null;
19776
19809
  }
19777
19810
  function liveGuidanceEvidence(repoRoot, path, testHooks) {
19778
- const absolute = (0, import_node_path5.join)(repoRoot, path);
19779
- if (!ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path5.dirname)(absolute), `guidance ${path}`, false))
19811
+ const absolute = (0, import_node_path6.join)(repoRoot, path);
19812
+ if (!ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)(absolute), `guidance ${path}`, false))
19780
19813
  throw new Error(`guidance disappeared while it was being inspected: ${path}`);
19781
- const stat = (0, import_node_fs5.lstatSync)(absolute);
19814
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19782
19815
  const mode = permissionMode(stat.mode);
19783
19816
  if (stat.isSymbolicLink()) {
19784
- const linkTarget = (0, import_node_fs5.readlinkSync)(absolute);
19817
+ const linkTarget = (0, import_node_fs6.readlinkSync)(absolute);
19785
19818
  if (!resolveGuidanceSymlinkTarget(repoRoot, path, linkTarget, testHooks))
19786
19819
  throw new Error(`guidance symlink cannot be resolved to a safe in-repo text file: ${path}`);
19787
19820
  return { path, type: "symlink", mode, linkTarget };
@@ -19802,13 +19835,13 @@ function discoverGuidance(repo, testHooks = {}) {
19802
19835
  const all = findAgentEntryPaths(root);
19803
19836
  const entryPaths = /* @__PURE__ */ new Set();
19804
19837
  for (const path of all) {
19805
- if (!AGENT_ENTRY_NAMES.has((0, import_node_path5.basename)(path)) || !safeEvidencePath(path)) continue;
19806
- const absolute = (0, import_node_path5.join)(root, path);
19838
+ if (!AGENT_ENTRY_NAMES.has((0, import_node_path6.basename)(path)) || !safeEvidencePath(path)) continue;
19839
+ const absolute = (0, import_node_path6.join)(root, path);
19807
19840
  if (entryExists(absolute) && isLegacyEntry(root, path, testHooks)) entryPaths.add(path);
19808
19841
  }
19809
19842
  for (const path of MANAGED_ENTRY_PATHS) {
19810
- if (!AGENT_ENTRY_NAMES.has((0, import_node_path5.basename)(path))) continue;
19811
- const absolute = (0, import_node_path5.join)(root, path);
19843
+ if (!AGENT_ENTRY_NAMES.has((0, import_node_path6.basename)(path))) continue;
19844
+ const absolute = (0, import_node_path6.join)(root, path);
19812
19845
  if (entryExists(absolute) && isLegacyEntry(root, path, testHooks)) entryPaths.add(path);
19813
19846
  }
19814
19847
  const evidence = new Set([...entryPaths].filter((path) => !MANAGED_ENTRY_PATHS.includes(path)));
@@ -19819,12 +19852,12 @@ function discoverGuidance(repo, testHooks = {}) {
19819
19852
  const sourcePath = queue.shift();
19820
19853
  if (reviewed.has(sourcePath)) continue;
19821
19854
  reviewed.add(sourcePath);
19822
- const absolute = (0, import_node_path5.join)(root, sourcePath);
19823
- if (!ensureNoSymlinkDirectoryChain(root, (0, import_node_path5.dirname)(absolute), `guidance ${sourcePath}`, false))
19855
+ const absolute = (0, import_node_path6.join)(root, sourcePath);
19856
+ if (!ensureNoSymlinkDirectoryChain(root, (0, import_node_path6.dirname)(absolute), `guidance ${sourcePath}`, false))
19824
19857
  throw new Error(`guidance disappeared while it was being inspected: ${sourcePath}`);
19825
- const stat = (0, import_node_fs5.lstatSync)(absolute);
19858
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19826
19859
  if (stat.isSymbolicLink()) {
19827
- const target = resolveGuidanceSymlinkTarget(root, sourcePath, (0, import_node_fs5.readlinkSync)(absolute), testHooks);
19860
+ const target = resolveGuidanceSymlinkTarget(root, sourcePath, (0, import_node_fs6.readlinkSync)(absolute), testHooks);
19828
19861
  if (!target) throw new Error(`guidance symlink cannot be resolved to a safe in-repo text file: ${sourcePath}`);
19829
19862
  if (!MANAGED_ENTRY_PATHS.includes(target)) evidence.add(target);
19830
19863
  if (!reviewed.has(target) && !queued.has(target)) {
@@ -19853,6 +19886,47 @@ function discoverGuidance(repo, testHooks = {}) {
19853
19886
  }
19854
19887
  return [...evidence].sort().map((path) => liveGuidanceEvidence(root, path, testHooks));
19855
19888
  }
19889
+ function posixPath(path) {
19890
+ return path.split(import_node_path6.sep).join("/");
19891
+ }
19892
+ function liveLandingEvidence(repoRoot, path) {
19893
+ const absolute = (0, import_node_path6.join)(repoRoot, path);
19894
+ if (!ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)(absolute), `landing ${path}`, false))
19895
+ throw new Error(`landing disappeared while it was being inspected: ${path}`);
19896
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19897
+ if (stat.isSymbolicLink()) return { path, type: "symlink", mode: permissionMode(stat.mode), linkTarget: (0, import_node_fs6.readlinkSync)(absolute) };
19898
+ const source = readOptionalRepositoryFile(repoRoot, path, `landing ${path}`);
19899
+ if (!source) throw new Error(`landing disappeared while it was being inspected: ${path}`);
19900
+ return { path, type: "file", mode: source.mode, bytes: source.bytes };
19901
+ }
19902
+ function discoverLanding(repoRoot, manifest) {
19903
+ const paths = /* @__PURE__ */ new Set();
19904
+ const walk = (relativePath) => {
19905
+ const absolute = (0, import_node_path6.join)(repoRoot, relativePath);
19906
+ if (!entryExists(absolute)) return;
19907
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19908
+ const key = posixPath(relativePath);
19909
+ if (stat.isSymbolicLink() || stat.isFile()) {
19910
+ if (!LANDING_EXCLUDED_FILES.has(key)) paths.add(relativePath);
19911
+ return;
19912
+ }
19913
+ if (!stat.isDirectory()) throw new Error(`landing must be a regular file, symlink, or directory: ${key}`);
19914
+ if (LANDING_EXCLUDED_DIRECTORIES.has(key) || ALWAYS_PRUNED_DIRECTORY_NAMES.has((0, import_node_path6.basename)(relativePath))) return;
19915
+ if (!inside2(repoRoot, (0, import_node_fs6.realpathSync)(absolute))) throw new Error(`landing directory resolves outside the repository: ${key}`);
19916
+ for (const name of (0, import_node_fs6.readdirSync)(absolute).sort()) walk((0, import_node_path6.join)(relativePath, name));
19917
+ };
19918
+ walk(LANDING_ROOT);
19919
+ for (const knowledge of manifest.knowledge ?? []) {
19920
+ if (knowledge.root !== "repo" || typeof knowledge.path !== "string") continue;
19921
+ const relativePath = safeRelativePath(knowledge.path.replace(/\/+$/, ""), "repo knowledge");
19922
+ if (!ensureNoSymlinkDirectoryChain(repoRoot, (0, import_node_path6.dirname)((0, import_node_path6.join)(repoRoot, relativePath)), `landing ${relativePath}`, false)) continue;
19923
+ walk(relativePath);
19924
+ }
19925
+ return [...paths].sort().map((path) => liveLandingEvidence(repoRoot, path));
19926
+ }
19927
+ function landingEvidenceArtifact(evidence) {
19928
+ return evidence.type === "file" ? (0, import_node_path6.join)("landing", evidence.path) : (0, import_node_path6.join)("landing-links", `${sha256(evidence.path)}.symlink.json`);
19929
+ }
19856
19930
  function captureLegacyEntries(repo, testHooks = {}) {
19857
19931
  const repoRoot = repositoryRoot2(repo);
19858
19932
  const previousSource = readAdoptionIndexSource(repoRoot);
@@ -19902,17 +19976,17 @@ function errorMessage2(error) {
19902
19976
  return error instanceof Error ? error.message : String(error);
19903
19977
  }
19904
19978
  function inside2(root, candidate) {
19905
- const rel = (0, import_node_path5.relative)(root, candidate);
19906
- return rel === "" || rel !== ".." && !rel.startsWith(`..${import_node_path5.sep}`) && !(0, import_node_path5.isAbsolute)(rel);
19979
+ const rel = (0, import_node_path6.relative)(root, candidate);
19980
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${import_node_path6.sep}`) && !(0, import_node_path6.isAbsolute)(rel);
19907
19981
  }
19908
19982
  function repositoryRoot2(repo) {
19909
19983
  let root;
19910
19984
  try {
19911
- root = (0, import_node_fs5.realpathSync)(repo);
19985
+ root = (0, import_node_fs6.realpathSync)(repo);
19912
19986
  } catch (error) {
19913
19987
  throw new Error(`cannot resolve repository root ${repo}: ${errorMessage2(error)}`);
19914
19988
  }
19915
- if (!(0, import_node_fs5.statSync)(root).isDirectory()) throw new Error(`repository root is not a directory: ${repo}`);
19989
+ if (!(0, import_node_fs6.statSync)(root).isDirectory()) throw new Error(`repository root is not a directory: ${repo}`);
19916
19990
  return root;
19917
19991
  }
19918
19992
  function canonicalJson(value) {
@@ -19928,102 +20002,102 @@ function isSha256(value) {
19928
20002
  return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
19929
20003
  }
19930
20004
  function safeRelativePath(path, label) {
19931
- if (!path || path.includes("\0") || (0, import_node_path5.isAbsolute)(path)) throw new Error(`${label} path is unsafe: ${path}`);
19932
- const normalized = (0, import_node_path5.normalize)(path);
19933
- if (normalized === "." || normalized === ".." || normalized.startsWith(`..${import_node_path5.sep}`))
20005
+ if (!path || path.includes("\0") || (0, import_node_path6.isAbsolute)(path)) throw new Error(`${label} path is unsafe: ${path}`);
20006
+ const normalized = (0, import_node_path6.normalize)(path);
20007
+ if (normalized === "." || normalized === ".." || normalized.startsWith(`..${import_node_path6.sep}`))
19934
20008
  throw new Error(`${label} path escapes its bundle: ${path}`);
19935
20009
  return normalized;
19936
20010
  }
19937
20011
  function existingAncestor(path) {
19938
20012
  const suffix = [];
19939
20013
  let cursor = path;
19940
- while (!(0, import_node_fs5.existsSync)(cursor)) {
19941
- const parent = (0, import_node_path5.dirname)(cursor);
20014
+ while (!(0, import_node_fs6.existsSync)(cursor)) {
20015
+ const parent = (0, import_node_path6.dirname)(cursor);
19942
20016
  if (parent === cursor) throw new Error(`cannot resolve destination parent: ${path}`);
19943
- suffix.unshift(cursor.slice(parent.length + (parent.endsWith(import_node_path5.sep) ? 0 : 1)));
20017
+ suffix.unshift(cursor.slice(parent.length + (parent.endsWith(import_node_path6.sep) ? 0 : 1)));
19944
20018
  cursor = parent;
19945
20019
  }
19946
20020
  return { ancestor: cursor, suffix };
19947
20021
  }
19948
20022
  function prospectiveRealPath(path) {
19949
20023
  const { ancestor, suffix } = existingAncestor(path);
19950
- const stat = (0, import_node_fs5.lstatSync)(ancestor);
20024
+ const stat = (0, import_node_fs6.lstatSync)(ancestor);
19951
20025
  if (!stat.isDirectory() && !stat.isSymbolicLink()) throw new Error(`destination parent is not a directory: ${ancestor}`);
19952
- const resolvedAncestor = (0, import_node_fs5.realpathSync)(ancestor);
19953
- if (!(0, import_node_fs5.statSync)(resolvedAncestor).isDirectory()) throw new Error(`destination parent is not a directory: ${ancestor}`);
19954
- return (0, import_node_path5.resolve)(resolvedAncestor, ...suffix);
20026
+ const resolvedAncestor = (0, import_node_fs6.realpathSync)(ancestor);
20027
+ if (!(0, import_node_fs6.statSync)(resolvedAncestor).isDirectory()) throw new Error(`destination parent is not a directory: ${ancestor}`);
20028
+ return (0, import_node_path6.resolve)(resolvedAncestor, ...suffix);
19955
20029
  }
19956
20030
  function assertExternalPath(repoRoot, requestedPath, label) {
19957
- const absolute = (0, import_node_path5.resolve)(requestedPath);
19958
- const resolved = (0, import_node_fs5.existsSync)(absolute) ? (0, import_node_fs5.realpathSync)(absolute) : prospectiveRealPath(absolute);
20031
+ const absolute = (0, import_node_path6.resolve)(requestedPath);
20032
+ const resolved = (0, import_node_fs6.existsSync)(absolute) ? (0, import_node_fs6.realpathSync)(absolute) : prospectiveRealPath(absolute);
19959
20033
  if (inside2(repoRoot, resolved)) throw new Error(`${label} must be outside the repository: ${absolute}`);
19960
20034
  return resolved;
19961
20035
  }
19962
20036
  function prepareEmptyExternalDirectory(repoRoot, outputDir) {
19963
- const absolute = (0, import_node_path5.resolve)(outputDir);
19964
- if ((0, import_node_fs5.existsSync)(absolute)) {
19965
- const stat2 = (0, import_node_fs5.lstatSync)(absolute);
20037
+ const absolute = (0, import_node_path6.resolve)(outputDir);
20038
+ if ((0, import_node_fs6.existsSync)(absolute)) {
20039
+ const stat2 = (0, import_node_fs6.lstatSync)(absolute);
19966
20040
  if (stat2.isSymbolicLink()) throw new Error(`candidate output must not be a symlink: ${absolute}`);
19967
20041
  if (!stat2.isDirectory()) throw new Error(`candidate output must be a directory: ${absolute}`);
19968
- if ((0, import_node_fs5.readdirSync)(absolute).length > 0) throw new Error(`candidate output must be empty: ${absolute}`);
20042
+ if ((0, import_node_fs6.readdirSync)(absolute).length > 0) throw new Error(`candidate output must be empty: ${absolute}`);
19969
20043
  }
19970
20044
  const expected = assertExternalPath(repoRoot, absolute, "candidate output");
19971
- if (!(0, import_node_fs5.existsSync)(absolute)) (0, import_node_fs5.mkdirSync)(absolute, { recursive: true, mode: 448 });
19972
- const stat = (0, import_node_fs5.lstatSync)(absolute);
20045
+ if (!(0, import_node_fs6.existsSync)(absolute)) (0, import_node_fs6.mkdirSync)(absolute, { recursive: true, mode: 448 });
20046
+ const stat = (0, import_node_fs6.lstatSync)(absolute);
19973
20047
  if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`candidate output is unsafe: ${absolute}`);
19974
- const actual = (0, import_node_fs5.realpathSync)(absolute);
20048
+ const actual = (0, import_node_fs6.realpathSync)(absolute);
19975
20049
  if (actual !== expected || inside2(repoRoot, actual)) throw new Error(`candidate output changed or escaped: ${absolute}`);
19976
- (0, import_node_fs5.chmodSync)(actual, 448);
20050
+ (0, import_node_fs6.chmodSync)(actual, 448);
19977
20051
  return actual;
19978
20052
  }
19979
20053
  function ensurePrivateDirectory(bundleRoot, directory) {
19980
- const rel = (0, import_node_path5.relative)(bundleRoot, directory);
19981
- if (rel === ".." || rel.startsWith(`..${import_node_path5.sep}`) || (0, import_node_path5.isAbsolute)(rel)) throw new Error(`bundle directory escapes: ${directory}`);
20054
+ const rel = (0, import_node_path6.relative)(bundleRoot, directory);
20055
+ if (rel === ".." || rel.startsWith(`..${import_node_path6.sep}`) || (0, import_node_path6.isAbsolute)(rel)) throw new Error(`bundle directory escapes: ${directory}`);
19982
20056
  let cursor = bundleRoot;
19983
- for (const component of rel.split(import_node_path5.sep).filter(Boolean)) {
19984
- cursor = (0, import_node_path5.join)(cursor, component);
19985
- if (!(0, import_node_fs5.existsSync)(cursor)) (0, import_node_fs5.mkdirSync)(cursor, { mode: 448 });
19986
- const stat = (0, import_node_fs5.lstatSync)(cursor);
20057
+ for (const component of rel.split(import_node_path6.sep).filter(Boolean)) {
20058
+ cursor = (0, import_node_path6.join)(cursor, component);
20059
+ if (!(0, import_node_fs6.existsSync)(cursor)) (0, import_node_fs6.mkdirSync)(cursor, { mode: 448 });
20060
+ const stat = (0, import_node_fs6.lstatSync)(cursor);
19987
20061
  if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`bundle directory is unsafe: ${cursor}`);
19988
- (0, import_node_fs5.chmodSync)(cursor, 448);
20062
+ (0, import_node_fs6.chmodSync)(cursor, 448);
19989
20063
  }
19990
20064
  }
19991
20065
  function bundleFilePath(bundleRoot, relativePath) {
19992
20066
  const normalized = safeRelativePath(relativePath, "bundle artifact");
19993
- const absolute = (0, import_node_path5.resolve)(bundleRoot, normalized);
20067
+ const absolute = (0, import_node_path6.resolve)(bundleRoot, normalized);
19994
20068
  if (!inside2(bundleRoot, absolute) || absolute === bundleRoot) throw new Error(`bundle artifact escapes: ${relativePath}`);
19995
20069
  return absolute;
19996
20070
  }
19997
20071
  function privateWriteBundleFile(bundleRoot, relativePath, content) {
19998
20072
  const absolute = bundleFilePath(bundleRoot, relativePath);
19999
- ensurePrivateDirectory(bundleRoot, (0, import_node_path5.dirname)(absolute));
20000
- (0, import_node_fs5.writeFileSync)(absolute, content, { flag: "wx", mode: 384 });
20001
- (0, import_node_fs5.chmodSync)(absolute, 384);
20073
+ ensurePrivateDirectory(bundleRoot, (0, import_node_path6.dirname)(absolute));
20074
+ (0, import_node_fs6.writeFileSync)(absolute, content, { flag: "wx", mode: 384 });
20075
+ (0, import_node_fs6.chmodSync)(absolute, 384);
20002
20076
  return absolute;
20003
20077
  }
20004
20078
  function readRegularFile(path, label) {
20005
20079
  let stat;
20006
20080
  try {
20007
- stat = (0, import_node_fs5.lstatSync)(path);
20081
+ stat = (0, import_node_fs6.lstatSync)(path);
20008
20082
  } catch (error) {
20009
20083
  throw new Error(`${label} is missing or unreadable at ${path}: ${errorMessage2(error)}`);
20010
20084
  }
20011
20085
  if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`${label} must be a regular file: ${path}`);
20012
- const fd = (0, import_node_fs5.openSync)(path, import_node_fs5.constants.O_RDONLY | import_node_fs5.constants.O_NOFOLLOW);
20086
+ const fd = (0, import_node_fs6.openSync)(path, import_node_fs6.constants.O_RDONLY | import_node_fs6.constants.O_NOFOLLOW);
20013
20087
  try {
20014
- if (!(0, import_node_fs5.fstatSync)(fd).isFile()) throw new Error(`${label} must be a regular file: ${path}`);
20015
- return (0, import_node_fs5.readFileSync)(fd);
20088
+ if (!(0, import_node_fs6.fstatSync)(fd).isFile()) throw new Error(`${label} must be a regular file: ${path}`);
20089
+ return (0, import_node_fs6.readFileSync)(fd);
20016
20090
  } finally {
20017
- (0, import_node_fs5.closeSync)(fd);
20091
+ (0, import_node_fs6.closeSync)(fd);
20018
20092
  }
20019
20093
  }
20020
20094
  function readBundleFile(bundleRoot, relativePath, label) {
20021
20095
  const absolute = bundleFilePath(bundleRoot, relativePath);
20022
- const parentRel = (0, import_node_path5.relative)(bundleRoot, (0, import_node_path5.dirname)(absolute));
20096
+ const parentRel = (0, import_node_path6.relative)(bundleRoot, (0, import_node_path6.dirname)(absolute));
20023
20097
  let cursor = bundleRoot;
20024
- for (const component of parentRel.split(import_node_path5.sep).filter(Boolean)) {
20025
- cursor = (0, import_node_path5.join)(cursor, component);
20026
- const stat = (0, import_node_fs5.lstatSync)(cursor);
20098
+ for (const component of parentRel.split(import_node_path6.sep).filter(Boolean)) {
20099
+ cursor = (0, import_node_path6.join)(cursor, component);
20100
+ const stat = (0, import_node_fs6.lstatSync)(cursor);
20027
20101
  if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`${label} parent is unsafe: ${cursor}`);
20028
20102
  }
20029
20103
  return readRegularFile(absolute, label);
@@ -20039,15 +20113,15 @@ function parseJsonRecord(bytes, label) {
20039
20113
  return value;
20040
20114
  }
20041
20115
  function readLiveIndexBytes(repoRoot) {
20042
- const bytes = readRegularFile((0, import_node_path5.join)(repoRoot, INDEX_REL), "legacy adoption index");
20116
+ const bytes = readRegularFile((0, import_node_path6.join)(repoRoot, INDEX_REL), "legacy adoption index");
20043
20117
  if (!readAdoptionIndex(repoRoot)) throw new Error(`${INDEX_REL} is required before preparing an adoption candidate`);
20044
20118
  return bytes;
20045
20119
  }
20046
20120
  function legacyEvidenceArtifact(entry) {
20047
- return entry.type === "file" ? (0, import_node_path5.join)("legacy", snapshotName(entry.path)) : (0, import_node_path5.join)("legacy", `${sha256(entry.path)}.symlink.json`);
20121
+ return entry.type === "file" ? (0, import_node_path6.join)("legacy", snapshotName(entry.path)) : (0, import_node_path6.join)("legacy", `${sha256(entry.path)}.symlink.json`);
20048
20122
  }
20049
20123
  function guidanceEvidenceArtifact(evidence) {
20050
- return (0, import_node_path5.join)("guidance", `${sha256(evidence.path)}.${evidence.type === "file" ? "document" : "symlink.json"}`);
20124
+ return (0, import_node_path6.join)("guidance", `${sha256(evidence.path)}.${evidence.type === "file" ? "document" : "symlink.json"}`);
20051
20125
  }
20052
20126
  function guidanceEvidenceBytes(evidence) {
20053
20127
  if (evidence.type === "file") return evidence.bytes;
@@ -20063,6 +20137,8 @@ function validateCandidateMetadata(value) {
20063
20137
  if (value.schema !== ADOPTION_CANDIDATE_SCHEMA || value.assurance !== "declared" || value.independence !== "unverified" || !isSha256(value.candidateHash) || !value.source || typeof value.source !== "object" || Array.isArray(value.source) || !Array.isArray(value.legacy) || !Array.isArray(value.guidance) || !Array.isArray(value.targets)) {
20064
20138
  throw new Error(`${CANDIDATE_METADATA} format is invalid`);
20065
20139
  }
20140
+ if (!Array.isArray(value.landing))
20141
+ throw new Error(`${CANDIDATE_METADATA} has no landing evidence; this bundle predates landing binding, run prepare-adoption into a new empty directory`);
20066
20142
  const source = value.source;
20067
20143
  const manifest = source.manifest;
20068
20144
  const legacyIndex = source.legacyIndex;
@@ -20093,6 +20169,17 @@ function validateCandidateMetadata(value) {
20093
20169
  if (item.type === "symlink" && typeof item.linkTarget !== "string")
20094
20170
  throw new Error(`${CANDIDATE_METADATA} guidance symlink evidence is invalid: ${item.path}`);
20095
20171
  }
20172
+ const landingPaths = /* @__PURE__ */ new Set();
20173
+ for (const raw of value.landing) {
20174
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${CANDIDATE_METADATA} landing metadata is invalid`);
20175
+ const item = raw;
20176
+ if (typeof item.path !== "string" || !safeEvidencePath(item.path) || LANDING_EXCLUDED_FILES.has(posixPath(item.path)) || landingPaths.has(item.path) || item.type !== "file" && item.type !== "symlink" || typeof item.artifact !== "string" || !isSha256(item.sha256) || !validPermissionMode(item.mode)) {
20177
+ throw new Error(`${CANDIDATE_METADATA} landing metadata is invalid`);
20178
+ }
20179
+ landingPaths.add(item.path);
20180
+ if (item.type === "symlink" && typeof item.linkTarget !== "string")
20181
+ throw new Error(`${CANDIDATE_METADATA} landing symlink evidence is invalid: ${item.path}`);
20182
+ }
20096
20183
  const targetPaths = /* @__PURE__ */ new Set();
20097
20184
  for (const raw of value.targets) {
20098
20185
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${CANDIDATE_METADATA} target metadata is invalid`);
@@ -20107,6 +20194,7 @@ function validateCandidateMetadata(value) {
20107
20194
  safeRelativePath(legacyIndex.artifact, "legacy index artifact");
20108
20195
  for (const raw of value.legacy) safeRelativePath(raw.artifact, "legacy artifact");
20109
20196
  for (const raw of value.guidance) safeRelativePath(raw.artifact, "guidance artifact");
20197
+ for (const raw of value.landing) safeRelativePath(raw.artifact, "landing artifact");
20110
20198
  for (const raw of value.targets) safeRelativePath(raw.artifact, "generated artifact");
20111
20199
  const metadata = value;
20112
20200
  if (expectedCandidateHash(metadata) !== metadata.candidateHash)
@@ -20114,11 +20202,11 @@ function validateCandidateMetadata(value) {
20114
20202
  return metadata;
20115
20203
  }
20116
20204
  function readCandidateBundle(repoRoot, candidateDir) {
20117
- const requested = (0, import_node_path5.resolve)(candidateDir);
20118
- if (!(0, import_node_fs5.existsSync)(requested)) throw new Error(`candidate bundle is missing: ${requested}`);
20119
- const stat = (0, import_node_fs5.lstatSync)(requested);
20205
+ const requested = (0, import_node_path6.resolve)(candidateDir);
20206
+ if (!(0, import_node_fs6.existsSync)(requested)) throw new Error(`candidate bundle is missing: ${requested}`);
20207
+ const stat = (0, import_node_fs6.lstatSync)(requested);
20120
20208
  if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`candidate bundle must be a regular directory: ${requested}`);
20121
- const root = (0, import_node_fs5.realpathSync)(requested);
20209
+ const root = (0, import_node_fs6.realpathSync)(requested);
20122
20210
  if (inside2(repoRoot, root)) throw new Error(`candidate bundle must be outside the repository: ${requested}`);
20123
20211
  const metadata = validateCandidateMetadata(parseJsonRecord(readBundleFile(root, CANDIDATE_METADATA, "candidate metadata"), "candidate metadata"));
20124
20212
  const artifacts = [
@@ -20126,6 +20214,7 @@ function readCandidateBundle(repoRoot, candidateDir) {
20126
20214
  { path: metadata.source.legacyIndex.artifact, hash: metadata.source.legacyIndex.sha256, label: "candidate legacy index" },
20127
20215
  ...metadata.legacy.map((item) => ({ path: item.artifact, hash: item.sha256, label: `legacy evidence ${item.path}` })),
20128
20216
  ...metadata.guidance.map((item) => ({ path: item.artifact, hash: item.sha256, label: `guidance evidence ${item.path}` })),
20217
+ ...metadata.landing.map((item) => ({ path: item.artifact, hash: item.sha256, label: `landing evidence ${item.path}` })),
20129
20218
  ...metadata.targets.map((item) => ({ path: item.artifact, hash: item.sha256, label: `generated candidate ${item.path}` }))
20130
20219
  ];
20131
20220
  const artifactPaths = /* @__PURE__ */ new Set();
@@ -20148,18 +20237,19 @@ function prepareAdoptionCandidate(repo, outputDir, testHooks = {}) {
20148
20237
  const invalidLegacy = index.entries.find((entry) => !verifyAdoptionEntry(repoRoot, entry));
20149
20238
  if (invalidLegacy) throw new Error(`legacy evidence is stale for ${invalidLegacy.path}; prepare refused`);
20150
20239
  const liveGuidance = discoverGuidance(repoRoot, testHooks);
20240
+ const liveLanding = discoverLanding(repoRoot, manifest);
20151
20241
  const root = prepareEmptyExternalDirectory(repoRoot, outputDir);
20152
- const manifestBytes = readRegularFile((0, import_node_path5.join)(repoRoot, MANIFEST_REL), "manifest");
20242
+ const manifestBytes = readRegularFile((0, import_node_path6.join)(repoRoot, MANIFEST_REL), "manifest");
20153
20243
  const indexBytes = readLiveIndexBytes(repoRoot);
20154
- const manifestArtifact = (0, import_node_path5.join)("source", "manifest.yaml");
20155
- const indexArtifact = (0, import_node_path5.join)("source", "legacy-index.json");
20244
+ const manifestArtifact = (0, import_node_path6.join)("source", "manifest.yaml");
20245
+ const indexArtifact = (0, import_node_path6.join)("source", "legacy-index.json");
20156
20246
  privateWriteBundleFile(root, manifestArtifact, manifestBytes);
20157
20247
  privateWriteBundleFile(root, indexArtifact, indexBytes);
20158
20248
  const legacy = [];
20159
20249
  for (const entry of index.entries) {
20160
20250
  const artifact = legacyEvidenceArtifact(entry);
20161
20251
  if (entry.type === "file") {
20162
- const snapshot = readRegularFile((0, import_node_path5.join)(repoRoot, entry.snapshot), `legacy snapshot ${entry.path}`);
20252
+ const snapshot = readRegularFile((0, import_node_path6.join)(repoRoot, entry.snapshot), `legacy snapshot ${entry.path}`);
20163
20253
  privateWriteBundleFile(root, artifact, snapshot);
20164
20254
  legacy.push({
20165
20255
  path: entry.path,
@@ -20195,9 +20285,23 @@ function prepareAdoptionCandidate(repo, outputDir, testHooks = {}) {
20195
20285
  ...evidence.type === "symlink" ? { linkTarget: evidence.linkTarget } : {}
20196
20286
  });
20197
20287
  }
20288
+ const landing = [];
20289
+ for (const evidence of liveLanding) {
20290
+ const artifact = landingEvidenceArtifact(evidence);
20291
+ const bytes = guidanceEvidenceBytes(evidence);
20292
+ privateWriteBundleFile(root, artifact, bytes);
20293
+ landing.push({
20294
+ path: evidence.path,
20295
+ type: evidence.type,
20296
+ artifact,
20297
+ sha256: sha256(bytes),
20298
+ mode: evidence.mode,
20299
+ ...evidence.type === "symlink" ? { linkTarget: evidence.linkTarget } : {}
20300
+ });
20301
+ }
20198
20302
  const targets = [];
20199
- for (const [path, content] of renderTargets(manifest)) {
20200
- const artifact = (0, import_node_path5.join)("generated", path);
20303
+ for (const [path, content] of renderTargets(manifest, { harnessVersion: lockedHarnessVersion(repoRoot) })) {
20304
+ const artifact = (0, import_node_path6.join)("generated", path);
20201
20305
  const bytes = Buffer.from(content, "utf8");
20202
20306
  privateWriteBundleFile(root, artifact, bytes);
20203
20307
  targets.push({ path, artifact, sha256: sha256(bytes) });
@@ -20212,6 +20316,7 @@ function prepareAdoptionCandidate(repo, outputDir, testHooks = {}) {
20212
20316
  },
20213
20317
  legacy,
20214
20318
  guidance,
20319
+ landing,
20215
20320
  targets
20216
20321
  };
20217
20322
  const metadata = { ...unsigned, candidateHash: candidateDigest(unsigned) };
@@ -20219,15 +20324,15 @@ function prepareAdoptionCandidate(repo, outputDir, testHooks = {}) {
20219
20324
  return metadata;
20220
20325
  }
20221
20326
  function externalReceiptPath(repoRoot, candidateRoot, requested) {
20222
- const absolute = (0, import_node_path5.resolve)(requested ?? (0, import_node_path5.join)(candidateRoot, RECEIPT_DEFAULT));
20223
- const parent = (0, import_node_path5.dirname)(absolute);
20224
- if (!(0, import_node_fs5.existsSync)(parent)) throw new Error(`receipt parent must already exist: ${parent}`);
20225
- const parentStat = (0, import_node_fs5.lstatSync)(parent);
20327
+ const absolute = (0, import_node_path6.resolve)(requested ?? (0, import_node_path6.join)(candidateRoot, RECEIPT_DEFAULT));
20328
+ const parent = (0, import_node_path6.dirname)(absolute);
20329
+ if (!(0, import_node_fs6.existsSync)(parent)) throw new Error(`receipt parent must already exist: ${parent}`);
20330
+ const parentStat = (0, import_node_fs6.lstatSync)(parent);
20226
20331
  if (parentStat.isSymbolicLink() || !parentStat.isDirectory()) throw new Error(`receipt parent is unsafe: ${parent}`);
20227
- const resolvedParent = (0, import_node_fs5.realpathSync)(parent);
20228
- const resolved = (0, import_node_path5.join)(resolvedParent, (0, import_node_path5.relative)(parent, absolute));
20332
+ const resolvedParent = (0, import_node_fs6.realpathSync)(parent);
20333
+ const resolved = (0, import_node_path6.join)(resolvedParent, (0, import_node_path6.relative)(parent, absolute));
20229
20334
  if (inside2(repoRoot, resolved)) throw new Error(`receipt must be outside the repository: ${absolute}`);
20230
- if ((0, import_node_fs5.existsSync)(absolute)) throw new Error(`receipt already exists: ${absolute}`);
20335
+ if ((0, import_node_fs6.existsSync)(absolute)) throw new Error(`receipt already exists: ${absolute}`);
20231
20336
  return resolved;
20232
20337
  }
20233
20338
  function recordAdoptionAudit(repo, candidateDir, options) {
@@ -20236,9 +20341,9 @@ function recordAdoptionAudit(repo, candidateDir, options) {
20236
20341
  const reason = options.reason?.trim();
20237
20342
  if (!reason) throw new Error("audit reason must not be empty");
20238
20343
  const candidate = readCandidateBundle(repoRoot, candidateDir);
20239
- const reportRequested = (0, import_node_path5.resolve)(options.reportPath);
20344
+ const reportRequested = (0, import_node_path6.resolve)(options.reportPath);
20240
20345
  const reportBytes = readRegularFile(reportRequested, "audit report");
20241
- const reportPath = (0, import_node_fs5.realpathSync)(reportRequested);
20346
+ const reportPath = (0, import_node_fs6.realpathSync)(reportRequested);
20242
20347
  const receiptPath = externalReceiptPath(repoRoot, candidate.root, options.receiptPath);
20243
20348
  const receipt = {
20244
20349
  schema: ADOPTION_RECEIPT_SCHEMA,
@@ -20251,20 +20356,20 @@ function recordAdoptionAudit(repo, candidateDir, options) {
20251
20356
  assurance: "declared",
20252
20357
  independence: "unverified"
20253
20358
  };
20254
- (0, import_node_fs5.writeFileSync)(receiptPath, canonicalJson(receipt) + "\n", { flag: "wx", mode: 384 });
20255
- (0, import_node_fs5.chmodSync)(receiptPath, 384);
20359
+ (0, import_node_fs6.writeFileSync)(receiptPath, canonicalJson(receipt) + "\n", { flag: "wx", mode: 384 });
20360
+ (0, import_node_fs6.chmodSync)(receiptPath, 384);
20256
20361
  return { receipt, receiptPath };
20257
20362
  }
20258
20363
  function readReceipt(repoRoot, receiptPath) {
20259
- const requested = (0, import_node_path5.resolve)(receiptPath);
20364
+ const requested = (0, import_node_path6.resolve)(receiptPath);
20260
20365
  const resolved = assertExternalPath(repoRoot, requested, "receipt");
20261
- if (resolved !== (0, import_node_fs5.realpathSync)(requested)) throw new Error(`receipt path changed: ${requested}`);
20366
+ if (resolved !== (0, import_node_fs6.realpathSync)(requested)) throw new Error(`receipt path changed: ${requested}`);
20262
20367
  const value = parseJsonRecord(readRegularFile(requested, "adoption audit receipt"), "adoption audit receipt");
20263
20368
  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)) {
20264
20369
  throw new Error(`adoption audit receipt format is invalid: ${requested}`);
20265
20370
  }
20266
20371
  const report = value.report;
20267
- if (typeof report.path !== "string" || !(0, import_node_path5.isAbsolute)(report.path) || !isSha256(report.sha256))
20372
+ if (typeof report.path !== "string" || !(0, import_node_path6.isAbsolute)(report.path) || !isSha256(report.sha256))
20268
20373
  throw new Error(`adoption audit receipt report binding is invalid: ${requested}`);
20269
20374
  return value;
20270
20375
  }
@@ -20298,7 +20403,7 @@ function assertManagedFileAdoptionReceipt(repo, inspections, candidateDir, recei
20298
20403
  if (entry.type !== evidence.type) throw new Error(`candidate legacy type changed for ${entry.path}`);
20299
20404
  const artifact = readBundleFile(candidate.root, evidence.artifact, `legacy evidence ${entry.path}`);
20300
20405
  if (entry.type === "file") {
20301
- const liveSnapshot = readRegularFile((0, import_node_path5.join)(repoRoot, entry.snapshot), `legacy snapshot ${entry.path}`);
20406
+ const liveSnapshot = readRegularFile((0, import_node_path6.join)(repoRoot, entry.snapshot), `legacy snapshot ${entry.path}`);
20302
20407
  if (evidence.sourceSha256 !== entry.sha256 || evidence.mode !== entry.mode || !artifact.equals(liveSnapshot))
20303
20408
  throw new Error(`candidate legacy bytes or mode changed for ${entry.path}`);
20304
20409
  } else {
@@ -20322,18 +20427,29 @@ function assertManagedFileAdoptionReceipt(repo, inspections, candidateDir, recei
20322
20427
  if (receipt.candidatePath !== candidate.root || receipt.candidateHash !== metadata.candidateHash)
20323
20428
  throw new Error(`receipt does not bind candidate ${metadata.candidateHash}`);
20324
20429
  if (receipt.verdict !== "pass") throw new Error(`adoption audit verdict is ${receipt.verdict}; pass is required`);
20325
- const reportPath = (0, import_node_path5.resolve)(receipt.report.path);
20326
- if ((0, import_node_fs5.realpathSync)(reportPath) !== receipt.report.path) throw new Error(`audit report path changed: ${reportPath}`);
20430
+ const reportPath = (0, import_node_path6.resolve)(receipt.report.path);
20431
+ if ((0, import_node_fs6.realpathSync)(reportPath) !== receipt.report.path) throw new Error(`audit report path changed: ${reportPath}`);
20327
20432
  if (sha256(readRegularFile(reportPath, "audit report")) !== receipt.report.sha256)
20328
20433
  throw new Error(`audit report hash mismatch: ${receipt.report.sha256}`);
20329
- const manifestBytes = readRegularFile((0, import_node_path5.join)(repoRoot, MANIFEST_REL), "manifest");
20434
+ const manifestBytes = readRegularFile((0, import_node_path6.join)(repoRoot, MANIFEST_REL), "manifest");
20330
20435
  if (metadata.source.manifest.sha256 !== sha256(manifestBytes)) throw new Error("manifest changed after candidate preparation");
20331
20436
  if (!readBundleFile(candidate.root, metadata.source.manifest.artifact, "candidate manifest").equals(manifestBytes))
20332
20437
  throw new Error("candidate manifest no longer matches the live manifest");
20333
20438
  const manifest = loadManifest(repoRoot);
20334
20439
  const errors = validateManifest(manifest).filter((issue) => issue.level === "error");
20335
20440
  if (errors.length) throw new Error(`manifest invalid: ${errors.map((issue) => issue.msg).join("; ")}`);
20336
- const rendered = renderTargets(manifest);
20441
+ const liveLanding = discoverLanding(repoRoot, manifest);
20442
+ if (!samePathList(metadata.landing.map((item) => item.path), liveLanding.map((item) => item.path)))
20443
+ throw new Error("live landing inventory changed after candidate preparation");
20444
+ for (let i = 0; i < liveLanding.length; i++) {
20445
+ const live = liveLanding[i];
20446
+ const evidence = metadata.landing[i];
20447
+ if (evidence.type !== live.type || evidence.mode !== live.mode || live.type === "symlink" && evidence.linkTarget !== live.linkTarget)
20448
+ throw new Error(`live landing topology or mode changed for ${live.path}`);
20449
+ const artifact = readBundleFile(candidate.root, evidence.artifact, `landing evidence ${live.path}`);
20450
+ if (!artifact.equals(guidanceEvidenceBytes(live))) throw new Error(`live landing bytes changed for ${live.path}`);
20451
+ }
20452
+ const rendered = renderTargets(manifest, { harnessVersion: lockedHarnessVersion(repoRoot) });
20337
20453
  if (!samePathList(metadata.targets.map((target) => target.path), rendered.map(([path]) => path)))
20338
20454
  throw new Error("current render target list differs from the audited candidate");
20339
20455
  if (!samePathList(inspections.map((inspection) => inspection.relativePath), rendered.map(([path]) => path)))
@@ -20362,8 +20478,8 @@ var import_yaml2 = __toESM(require_dist(), 1);
20362
20478
  // src/git.ts
20363
20479
  var import_node_child_process3 = require("node:child_process");
20364
20480
  var import_node_crypto5 = require("node:crypto");
20365
- var import_node_fs6 = require("node:fs");
20366
- var import_node_path6 = require("node:path");
20481
+ var import_node_fs7 = require("node:fs");
20482
+ var import_node_path7 = require("node:path");
20367
20483
  var GitDiffError = class extends Error {
20368
20484
  constructor(kind, message) {
20369
20485
  super(message);
@@ -20451,17 +20567,17 @@ function nulList(raw) {
20451
20567
  }
20452
20568
  function canonicalPath(path) {
20453
20569
  try {
20454
- return (0, import_node_fs6.realpathSync)(path);
20570
+ return (0, import_node_fs7.realpathSync)(path);
20455
20571
  } catch {
20456
- return (0, import_node_path6.resolve)(path);
20572
+ return (0, import_node_path7.resolve)(path);
20457
20573
  }
20458
20574
  }
20459
20575
  function targetPrefix(root, target) {
20460
- const native = (0, import_node_path6.relative)(root, target);
20576
+ const native = (0, import_node_path7.relative)(root, target);
20461
20577
  if (!native) return "";
20462
- if ((0, import_node_path6.isAbsolute)(native) || native === ".." || native.startsWith(`..${import_node_path6.sep}`))
20578
+ if ((0, import_node_path7.isAbsolute)(native) || native === ".." || native.startsWith(`..${import_node_path7.sep}`))
20463
20579
  throw new GitDiffError("not-a-repo", `target is outside its Git worktree: ${target}`);
20464
- return native.split(import_node_path6.sep).join("/");
20580
+ return native.split(import_node_path7.sep).join("/");
20465
20581
  }
20466
20582
  function scopeEntries(entries, prefix) {
20467
20583
  if (!prefix) return entries;
@@ -20469,10 +20585,10 @@ function scopeEntries(entries, prefix) {
20469
20585
  return entries.filter((entry) => entry.path.startsWith(start)).map((entry) => ({ ...entry, path: entry.path.slice(start.length) }));
20470
20586
  }
20471
20587
  function digestPath(repo, rel) {
20472
- const abs = (0, import_node_path6.join)(repo, rel);
20588
+ const abs = (0, import_node_path7.join)(repo, rel);
20473
20589
  try {
20474
- const stat = (0, import_node_fs6.lstatSync)(abs);
20475
- if (stat.isSymbolicLink()) return `symlink:${(0, import_node_fs6.readlinkSync)(abs)}`;
20590
+ const stat = (0, import_node_fs7.lstatSync)(abs);
20591
+ if (stat.isSymbolicLink()) return `symlink:${(0, import_node_fs7.readlinkSync)(abs)}`;
20476
20592
  if (stat.isDirectory()) {
20477
20593
  try {
20478
20594
  const head = (0, import_node_child_process3.execFileSync)("git", ["-C", abs, "rev-parse", "--verify", "HEAD"], {
@@ -20487,7 +20603,7 @@ function digestPath(repo, rel) {
20487
20603
  }
20488
20604
  if (!stat.isFile()) return `other:${stat.mode}`;
20489
20605
  const gitMode = stat.mode & 73 ? "100755" : "100644";
20490
- return `file:${gitMode}:${(0, import_node_crypto5.createHash)("sha256").update((0, import_node_fs6.readFileSync)(abs)).digest("hex")}`;
20606
+ return `file:${gitMode}:${(0, import_node_crypto5.createHash)("sha256").update((0, import_node_fs7.readFileSync)(abs)).digest("hex")}`;
20491
20607
  } catch {
20492
20608
  return "(missing)";
20493
20609
  }
@@ -20563,9 +20679,22 @@ function collectChanges(repoInput, base = "HEAD", opts = {}) {
20563
20679
  fingerprint: fingerprint(target, resolvedBase, entries)
20564
20680
  };
20565
20681
  }
20682
+ function readFileAtCommit(repoInput, commit, rel) {
20683
+ const target = canonicalPath(repoInput);
20684
+ const root = canonicalPath(gitRoot(target));
20685
+ const prefix = targetPrefix(root, target);
20686
+ const path = prefix ? `${prefix}/${rel}` : rel;
20687
+ const entry = git(root, ["--literal-pathspecs", "ls-tree", "-z", "--full-tree", commit, "--", path]);
20688
+ const match = /^\d+ (\w+) ([0-9a-f]+)\t/.exec(entry);
20689
+ if (!match || match[1] !== "blob") return null;
20690
+ return git(root, ["cat-file", "blob", match[2]]);
20691
+ }
20692
+ function listWorktreeFiles(dir, glob) {
20693
+ return nulList(git(dir, ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", `:(glob)${glob}`]));
20694
+ }
20566
20695
 
20567
20696
  // src/upgrade.ts
20568
- var UPGRADE_STATE_REL = ".agents/harness.lock.json";
20697
+ var UPGRADE_STATE_REL = HARNESS_LOCK_REL;
20569
20698
  var UPGRADE_STATE_SCHEMA = "ai-harness/upgrade-state/v1";
20570
20699
  var UPGRADE_REPORT_SCHEMA = "ai-harness/upgrade-report/v1";
20571
20700
  var UPGRADE_MIGRATIONS = [
@@ -20730,15 +20859,16 @@ function internalUpgrade(repo, options) {
20730
20859
  };
20731
20860
  const manifestChanged = migratedManifestContent !== normalizedSource;
20732
20861
  const finalManifestContent = manifestChanged ? migratedManifestContent : manifestInspection.currentContent;
20862
+ const generated = renderTargets(finalManifest, { harnessVersion: nextState.version });
20733
20863
  const targets = [
20734
20864
  // Keep an unchanged manifest in the transaction preflight so generated
20735
20865
  // files can never be committed from bytes that changed after planning.
20736
20866
  [MANIFEST_REL, finalManifestContent],
20737
- ...renderTargets(finalManifest),
20867
+ ...generated,
20738
20868
  [UPGRADE_STATE_REL, renderState(nextState)]
20739
20869
  ];
20740
20870
  const preflight = inspectManagedFiles(repo, targets);
20741
- const generatedPaths = new Set(renderTargets(finalManifest).map(([path]) => path));
20871
+ const generatedPaths = new Set(generated.map(([path]) => path));
20742
20872
  try {
20743
20873
  assertManagedFileAdoption(
20744
20874
  repo,
@@ -20907,7 +21037,12 @@ function syncCmd(repo, opts = {}) {
20907
21037
  const errors = validateManifest(m).filter((issue) => issue.level === "error");
20908
21038
  if (errors.length) throw new Error(`manifest invalid: ${errors.map((issue) => issue.msg).join("; ")}`);
20909
21039
  info("Syncing generated files from .agents/manifest.yaml ...");
20910
- const targets = renderTargets(m);
21040
+ const harnessVersion = lockedHarnessVersion(repo);
21041
+ if (harnessVersion && harnessVersion !== package_default.version)
21042
+ warn(
21043
+ `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.`
21044
+ );
21045
+ const targets = renderTargets(m, { harnessVersion });
20911
21046
  if (!!opts.adoptionCandidate !== !!opts.adoptionAudit)
20912
21047
  throw new Error("adoption requires both --candidate <bundle> and --audit <receipt>");
20913
21048
  if ((opts.adoptionCandidate || opts.adoptionAudit) && !opts.adoptExisting)
@@ -20933,8 +21068,9 @@ function syncCmd(repo, opts = {}) {
20933
21068
 
20934
21069
  // src/commands/doctor.ts
20935
21070
  var import_fast_glob3 = __toESM(require_out4(), 1);
20936
- var import_node_fs12 = require("node:fs");
20937
- var import_node_path12 = require("node:path");
21071
+ var import_picomatch4 = __toESM(require_picomatch2(), 1);
21072
+ var import_node_fs13 = require("node:fs");
21073
+ var import_node_path13 = require("node:path");
20938
21074
 
20939
21075
  // src/guidance.ts
20940
21076
  function gap(kind, scope, classification, title, reason, when, legacyText) {
@@ -21015,7 +21151,7 @@ function declaredVerificationGaps(manifest) {
21015
21151
  }
21016
21152
  return gaps;
21017
21153
  }
21018
- function automationAction(gaps) {
21154
+ function automationAction(gaps, cli) {
21019
21155
  const recommended = gaps.filter((item) => item.classification === "recommended");
21020
21156
  if (!recommended.length) return null;
21021
21157
  return {
@@ -21025,7 +21161,7 @@ function automationAction(gaps) {
21025
21161
  when: "harness-maintenance",
21026
21162
  title: `Improve ${recommended.length} verification declaration(s)`,
21027
21163
  reason: "These declarations have no executable check or complete manual procedure. They do not invalidate this run, but they weaken future coverage.",
21028
- commands: ["harness-kit verify --repo . --details"],
21164
+ commands: [`${cli} verify --repo . --details`],
21029
21165
  completion: "Each declaration has a real enforcement/check, or an explicit manual procedure when automation is genuinely impossible."
21030
21166
  };
21031
21167
  }
@@ -21037,7 +21173,7 @@ function unsafeHookIssue(issue) {
21037
21173
  issue
21038
21174
  );
21039
21175
  }
21040
- function hookActions(hooks) {
21176
+ function hookActions(hooks, cli) {
21041
21177
  if (hooks.state === "active") return [];
21042
21178
  const configured = hooks.configuredAgents.join(",");
21043
21179
  const unsafe = hooks.issues.filter(unsafeHookIssue);
@@ -21061,7 +21197,7 @@ function hookActions(hooks) {
21061
21197
  when: "harness-maintenance",
21062
21198
  title: "Optional: observe lifecycle Hook on a later Stop",
21063
21199
  reason: `Hooks are configured for ${configured || "the current Agent"} but not yet observed. This does not block delivery \u2014 use harness-kit deliver for task acceptance.`,
21064
- commands: ["harness-kit deliver --repo .", "harness-kit evidence --repo . --json"],
21200
+ commands: [`${cli} deliver --repo .`, `${cli} evidence --repo . --json`],
21065
21201
  completion: "Deliver stamp is valid; hook observation is optional."
21066
21202
  }];
21067
21203
  }
@@ -21074,8 +21210,8 @@ function hookActions(hooks) {
21074
21210
  title: "Optional: install Agent Stop intercept for session-level loops",
21075
21211
  reason: "Without Stop hooks, agents must run harness-kit deliver cooperatively. Install hooks only when the host supports them.",
21076
21212
  commands: [
21077
- "harness-kit deliver --repo .",
21078
- `harness-kit install-hooks --repo . --stop --agents ${configured || "<current-agent>"}`
21213
+ `${cli} deliver --repo .`,
21214
+ `${cli} install-hooks --repo . --stop --agents ${configured || "<current-agent>"}`
21079
21215
  ],
21080
21216
  completion: "Deliver works without hooks; hooks only add session intercept when the host fires Stop."
21081
21217
  }];
@@ -21088,13 +21224,13 @@ function hookActions(hooks) {
21088
21224
  title: "Optional: repair Agent lifecycle Hook configuration",
21089
21225
  reason: "Hook configuration is incomplete or degraded. Delivery still uses harness-kit deliver.",
21090
21226
  commands: [
21091
- `harness-kit install-hooks --repo . --stop --agents ${configured}`,
21092
- "harness-kit deliver --repo ."
21227
+ `${cli} install-hooks --repo . --stop --agents ${configured}`,
21228
+ `${cli} deliver --repo .`
21093
21229
  ],
21094
21230
  completion: "Hooks install cleanly or the team accepts deliver-only cooperative mode."
21095
21231
  }];
21096
21232
  }
21097
- function evidenceActions(evidence) {
21233
+ function evidenceActions(evidence, cli) {
21098
21234
  if (!evidence.found) {
21099
21235
  return [{
21100
21236
  id: "record-delivery-evidence",
@@ -21103,10 +21239,7 @@ function evidenceActions(evidence) {
21103
21239
  when: "before-finish",
21104
21240
  title: "Accept this change with harness-kit deliver",
21105
21241
  reason: "No delivery stamp exists for the current worktree/session.",
21106
- commands: [
21107
- "harness-kit deliver --repo .",
21108
- "harness-kit evidence --repo . --json"
21109
- ],
21242
+ commands: [`${cli} deliver --repo .`, `${cli} evidence --repo . --json`],
21110
21243
  completion: "deliver reports status=accepted (or no-change) and evidence stamp is valid."
21111
21244
  }];
21112
21245
  }
@@ -21118,7 +21251,7 @@ function evidenceActions(evidence) {
21118
21251
  when: "before-finish",
21119
21252
  title: "Re-run deliver for the current code",
21120
21253
  reason: "The saved green stamp belongs to an older code fingerprint.",
21121
- commands: ["harness-kit deliver --repo .", "harness-kit evidence --repo . --json"],
21254
+ commands: [`${cli} deliver --repo .`, `${cli} evidence --repo . --json`],
21122
21255
  completion: "Stamp is no longer stale and deliver reports accepted."
21123
21256
  }];
21124
21257
  }
@@ -21130,7 +21263,7 @@ function evidenceActions(evidence) {
21130
21263
  when: "before-finish",
21131
21264
  title: "Complete impact-driven delivery checks",
21132
21265
  reason: "The selected checks did not produce valid evidence for the current code.",
21133
- commands: ["harness-kit deliver --repo .", "harness-kit evidence --repo . --json"],
21266
+ commands: [`${cli} deliver --repo .`, `${cli} evidence --repo . --json`],
21134
21267
  completion: "deliver reports accepted and stamp runChecksValid: true."
21135
21268
  }];
21136
21269
  }
@@ -21142,19 +21275,20 @@ function evidenceActions(evidence) {
21142
21275
  when: "before-finish",
21143
21276
  title: "Complete delivery verification",
21144
21277
  reason: "Change checks passed, but matching verify evidence is missing or failed.",
21145
- commands: ["harness-kit deliver --repo .", "harness-kit evidence --repo . --json"],
21278
+ commands: [`${cli} deliver --repo .`, `${cli} evidence --repo . --json`],
21146
21279
  completion: "deliver reports accepted and stamp valid: true."
21147
21280
  }];
21148
21281
  }
21149
21282
  return [];
21150
21283
  }
21151
21284
  function buildHarnessGuidance(input) {
21285
+ const cli = input.cli ?? "harness-kit";
21152
21286
  const gapDetails = input.manifest ? declaredVerificationGaps(input.manifest) : [];
21153
21287
  const nextActions2 = [
21154
- ...input.evidence ? evidenceActions(input.evidence) : [],
21155
- ...input.hooks ? hookActions(input.hooks) : []
21288
+ ...input.evidence ? evidenceActions(input.evidence, cli) : [],
21289
+ ...input.hooks ? hookActions(input.hooks, cli) : []
21156
21290
  ];
21157
- const improvement = automationAction(gapDetails);
21291
+ const improvement = automationAction(gapDetails, cli);
21158
21292
  if (improvement) nextActions2.push(improvement);
21159
21293
  return {
21160
21294
  gapDetails,
@@ -21168,14 +21302,14 @@ function buildHarnessGuidance(input) {
21168
21302
  }
21169
21303
 
21170
21304
  // src/hook-status.ts
21171
- var import_node_fs10 = require("node:fs");
21172
- var import_node_path10 = require("node:path");
21305
+ var import_node_fs11 = require("node:fs");
21306
+ var import_node_path11 = require("node:path");
21173
21307
 
21174
21308
  // src/codex-linked-hooks.ts
21175
21309
  var import_node_child_process4 = require("node:child_process");
21176
- var import_node_fs7 = require("node:fs");
21310
+ var import_node_fs8 = require("node:fs");
21177
21311
  var import_node_os = require("node:os");
21178
- var import_node_path7 = require("node:path");
21312
+ var import_node_path8 = require("node:path");
21179
21313
  var CODEX_LINKED_PROTOCOL = "ai-harness/codex-linked-dispatch/v1";
21180
21314
  var DISPATCH_ID = "codex-linked-dispatch-v1";
21181
21315
  var DISPATCHER_REL = `harness-kit/${DISPATCH_ID}.cjs`;
@@ -21185,25 +21319,25 @@ var RUNNER_REL = ".agents/hooks/harness-agent-hook.sh";
21185
21319
  var DISPATCHER_MARK = "harness-kit-managed-codex-linked-dispatch-v1";
21186
21320
  function canonical(path) {
21187
21321
  try {
21188
- return (0, import_node_fs7.realpathSync)(path);
21322
+ return (0, import_node_fs8.realpathSync)(path);
21189
21323
  } catch {
21190
- return (0, import_node_path7.resolve)(path);
21324
+ return (0, import_node_path8.resolve)(path);
21191
21325
  }
21192
21326
  }
21193
21327
  function ensureCodexHome(requestedInput, label) {
21194
- const requested = (0, import_node_path7.resolve)(requestedInput);
21195
- (0, import_node_fs7.mkdirSync)(requested, { recursive: true, mode: 448 });
21196
- const resolved = (0, import_node_fs7.realpathSync)(requested);
21197
- if (!(0, import_node_fs7.statSync)(resolved).isDirectory()) throw new Error(`${label} is not a directory: ${requested}`);
21328
+ const requested = (0, import_node_path8.resolve)(requestedInput);
21329
+ (0, import_node_fs8.mkdirSync)(requested, { recursive: true, mode: 448 });
21330
+ const resolved = (0, import_node_fs8.realpathSync)(requested);
21331
+ if (!(0, import_node_fs8.statSync)(resolved).isDirectory()) throw new Error(`${label} is not a directory: ${requested}`);
21198
21332
  return resolved;
21199
21333
  }
21200
21334
  function resolveCodexHookSourceHome(options = {}) {
21201
21335
  const env = options.env ?? process.env;
21202
21336
  const userHome = options.homeDir ?? (0, import_node_os.homedir)();
21203
- const runtimeHome = ensureCodexHome(env.CODEX_HOME ?? (0, import_node_path7.join)(userHome, ".codex"), "CODEX_HOME");
21337
+ const runtimeHome = ensureCodexHome(env.CODEX_HOME ?? (0, import_node_path8.join)(userHome, ".codex"), "CODEX_HOME");
21204
21338
  const orcaRuntimeHome = env.ORCA_CODEX_HOME?.trim();
21205
- if (env.ORCA_WORKTREE_ID?.trim() && orcaRuntimeHome && canonical((0, import_node_path7.resolve)(orcaRuntimeHome)) === runtimeHome) {
21206
- const codexHome = ensureCodexHome((0, import_node_path7.join)(userHome, ".codex"), "Codex system hook source home");
21339
+ if (env.ORCA_WORKTREE_ID?.trim() && orcaRuntimeHome && canonical((0, import_node_path8.resolve)(orcaRuntimeHome)) === runtimeHome) {
21340
+ const codexHome = ensureCodexHome((0, import_node_path8.join)(userHome, ".codex"), "Codex system hook source home");
21207
21341
  return { codexHome, requiresRuntimeRefresh: codexHome !== runtimeHome };
21208
21342
  }
21209
21343
  return { codexHome: runtimeHome, requiresRuntimeRefresh: false };
@@ -21212,7 +21346,7 @@ function shellQuote(value) {
21212
21346
  return `'${value.replace(/'/g, `'"'"'`)}'`;
21213
21347
  }
21214
21348
  function userHookCommand(codexHome, event) {
21215
- return `node ${shellQuote((0, import_node_path7.join)(codexHome, DISPATCHER_REL))} ${event}`;
21349
+ return `node ${shellQuote((0, import_node_path8.join)(codexHome, DISPATCHER_REL))} ${event}`;
21216
21350
  }
21217
21351
  function managedUserGroup(codexHome, event) {
21218
21352
  return {
@@ -21243,7 +21377,7 @@ function parseObjectJson(raw, label) {
21243
21377
  throw new Error(`${label} exists but is not valid JSON`);
21244
21378
  }
21245
21379
  function renderUserHooks(current, codexHome) {
21246
- const hooksPath = (0, import_node_path7.join)(codexHome, USER_HOOKS_REL);
21380
+ const hooksPath = (0, import_node_path8.join)(codexHome, USER_HOOKS_REL);
21247
21381
  const json = parseObjectJson(current, hooksPath);
21248
21382
  if (json.hooks !== void 0 && (!json.hooks || typeof json.hooks !== "object" || Array.isArray(json.hooks))) {
21249
21383
  throw new Error(`${hooksPath} hooks must be an object; refusing to replace an unknown existing shape`);
@@ -21292,9 +21426,9 @@ function registrationFrom(raw, label) {
21292
21426
  }
21293
21427
  function runnerMode(repoRoot, content) {
21294
21428
  try {
21295
- const path = (0, import_node_path7.join)(repoRoot, RUNNER_REL);
21296
- const stat = (0, import_node_fs7.lstatSync)(path);
21297
- if (stat.isFile() && !stat.isSymbolicLink() && (0, import_node_fs7.readFileSync)(path, "utf8") === content) return stat.mode & 511;
21429
+ const path = (0, import_node_path8.join)(repoRoot, RUNNER_REL);
21430
+ const stat = (0, import_node_fs8.lstatSync)(path);
21431
+ if (stat.isFile() && !stat.isSymbolicLink() && (0, import_node_fs8.readFileSync)(path, "utf8") === content) return stat.mode & 511;
21298
21432
  } catch {
21299
21433
  }
21300
21434
  return 493;
@@ -21428,7 +21562,7 @@ function prepareCodexLinkedInstall(repoInput, runnerContent, options = {}) {
21428
21562
  const initialByPath = inspectionMap(initialUser);
21429
21563
  const currentDispatcher = initialByPath.get(DISPATCHER_REL)?.currentContent ?? null;
21430
21564
  if (currentDispatcher !== null && currentDispatcher !== dispatcher) {
21431
- throw new Error(`${(0, import_node_path7.join)(codexHome, DISPATCHER_REL)} exists and is foreign or changed; refusing to replace it`);
21565
+ throw new Error(`${(0, import_node_path8.join)(codexHome, DISPATCHER_REL)} exists and is foreign or changed; refusing to replace it`);
21432
21566
  }
21433
21567
  const currentHooks = initialByPath.get(USER_HOOKS_REL)?.currentContent ?? null;
21434
21568
  const renderedHooks = renderUserHooks(currentHooks, codexHome);
@@ -21472,30 +21606,30 @@ function prepareCodexLinkedInstall(repoInput, runnerContent, options = {}) {
21472
21606
  };
21473
21607
  }
21474
21608
  function registrationPathLabel(gitDir) {
21475
- return (0, import_node_path7.join)(gitDir, REGISTRATION_REL);
21609
+ return (0, import_node_path8.join)(gitDir, REGISTRATION_REL);
21476
21610
  }
21477
21611
  function commitCodexLinkedInstall(plan, testHooks = {}) {
21478
21612
  testHooks.beforeUserTransaction?.();
21479
21613
  const userResult = writeManagedFiles(plan.codexHome, plan.userTargets, {
21480
21614
  authorize: (current) => assertInspectionsUnchanged(plan.userInspections, current, "Codex user Hook source")
21481
21615
  });
21482
- (0, import_node_fs7.chmodSync)((0, import_node_path7.join)(plan.codexHome, DISPATCHER_REL), 448);
21616
+ (0, import_node_fs8.chmodSync)((0, import_node_path8.join)(plan.codexHome, DISPATCHER_REL), 448);
21483
21617
  if (userResult.inspections.find((item) => item.relativePath === USER_HOOKS_REL)?.kind === "missing") {
21484
- (0, import_node_fs7.chmodSync)((0, import_node_path7.join)(plan.codexHome, USER_HOOKS_REL), 384);
21618
+ (0, import_node_fs8.chmodSync)((0, import_node_path8.join)(plan.codexHome, USER_HOOKS_REL), 384);
21485
21619
  }
21486
21620
  testHooks.beforeRegistrationTransaction?.();
21487
21621
  writeManagedFiles(plan.gitDir, [plan.registrationTarget], {
21488
21622
  authorize: (current) => assertInspectionsUnchanged(plan.registrationInspections, current, "Codex linked registration source")
21489
21623
  });
21490
- (0, import_node_fs7.chmodSync)((0, import_node_path7.join)(plan.gitDir, REGISTRATION_REL), 384);
21624
+ (0, import_node_fs8.chmodSync)((0, import_node_path8.join)(plan.gitDir, REGISTRATION_REL), 384);
21491
21625
  }
21492
21626
  function safeContent(root, rel, issues) {
21493
21627
  try {
21494
21628
  const inspected = inspectManagedFiles(root, [[rel, ""]])[0];
21495
21629
  if (inspected.kind === "missing" || inspected.currentContent === null) return { content: null };
21496
- return { content: inspected.currentContent, mode: (0, import_node_fs7.lstatSync)((0, import_node_path7.join)(root, rel)).mode & 511 };
21630
+ return { content: inspected.currentContent, mode: (0, import_node_fs8.lstatSync)((0, import_node_path8.join)(root, rel)).mode & 511 };
21497
21631
  } catch (error) {
21498
- issues.push(`${(0, import_node_path7.join)(root, rel)} is not a safe regular file: ${error.message}`);
21632
+ issues.push(`${(0, import_node_path8.join)(root, rel)} is not a safe regular file: ${error.message}`);
21499
21633
  return { content: null };
21500
21634
  }
21501
21635
  }
@@ -21538,7 +21672,7 @@ function inspectCodexLinkedHooks(repoInput) {
21538
21672
  issues.push("Codex user hooks.json is missing");
21539
21673
  } else {
21540
21674
  try {
21541
- const json = parseObjectJson(userHooksFile.content, (0, import_node_path7.join)(registration.codexHome, USER_HOOKS_REL));
21675
+ const json = parseObjectJson(userHooksFile.content, (0, import_node_path8.join)(registration.codexHome, USER_HOOKS_REL));
21542
21676
  const hooks = json.hooks;
21543
21677
  const start = Array.isArray(hooks?.SessionStart) ? hooks.SessionStart.find((group) => isExactManagedUserGroup(group, registration.codexHome, "session-start")) : void 0;
21544
21678
  const stop = Array.isArray(hooks?.Stop) ? hooks.Stop.find((group) => isExactManagedUserGroup(group, registration.codexHome, "stop")) : void 0;
@@ -21561,8 +21695,8 @@ function inspectCodexLinkedHooks(repoInput) {
21561
21695
 
21562
21696
  // src/validation-state.ts
21563
21697
  var import_node_crypto6 = require("node:crypto");
21564
- var import_node_fs8 = require("node:fs");
21565
- var import_node_path8 = require("node:path");
21698
+ var import_node_fs9 = require("node:fs");
21699
+ var import_node_path9 = require("node:path");
21566
21700
 
21567
21701
  // src/planner.ts
21568
21702
  var import_picomatch2 = __toESM(require_picomatch2(), 1);
@@ -21870,24 +22004,24 @@ var TOKEN_RX = /^[a-f0-9]{64}$/;
21870
22004
  var MAX_SESSIONS = 100;
21871
22005
  var MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
21872
22006
  function stateDir(repo) {
21873
- return (0, import_node_path8.join)(gitAdminDir(repo), "harness-kit", "validation");
22007
+ return (0, import_node_path9.join)(gitAdminDir(repo), "harness-kit", "validation");
21874
22008
  }
21875
22009
  function canonicalTarget(repo) {
21876
22010
  try {
21877
- return (0, import_node_fs8.realpathSync)(repo);
22011
+ return (0, import_node_fs9.realpathSync)(repo);
21878
22012
  } catch {
21879
- return (0, import_node_path8.resolve)(repo);
22013
+ return (0, import_node_path9.resolve)(repo);
21880
22014
  }
21881
22015
  }
21882
22016
  function latestPath(repo) {
21883
- return (0, import_node_path8.join)(stateDir(repo), `latest-${sha256(canonicalTarget(repo)).slice(0, 24)}.json`);
22017
+ return (0, import_node_path9.join)(stateDir(repo), `latest-${sha256(canonicalTarget(repo)).slice(0, 24)}.json`);
21884
22018
  }
21885
22019
  function validationSessionToken(agent, sessionId2) {
21886
22020
  return sha256(`${agent}\0${sessionId2}`);
21887
22021
  }
21888
22022
  function sessionPath(repo, token) {
21889
22023
  if (!TOKEN_RX.test(token)) throw new Error("invalid validation session token");
21890
- return (0, import_node_path8.join)(stateDir(repo), `${token}.json`);
22024
+ return (0, import_node_path9.join)(stateDir(repo), `${token}.json`);
21891
22025
  }
21892
22026
  function readJson(path) {
21893
22027
  const raw = readText(path);
@@ -21900,21 +22034,21 @@ function readJson(path) {
21900
22034
  }
21901
22035
  function expired(path) {
21902
22036
  try {
21903
- return Date.now() - (0, import_node_fs8.statSync)(path).mtimeMs > MAX_AGE_MS;
22037
+ return Date.now() - (0, import_node_fs9.statSync)(path).mtimeMs > MAX_AGE_MS;
21904
22038
  } catch {
21905
22039
  return false;
21906
22040
  }
21907
22041
  }
21908
22042
  function writePrivateJson(path, value) {
21909
- (0, import_node_fs8.mkdirSync)((0, import_node_path8.dirname)(path), { recursive: true });
22043
+ (0, import_node_fs9.mkdirSync)((0, import_node_path9.dirname)(path), { recursive: true });
21910
22044
  const temp = `${path}.${process.pid}.${(0, import_node_crypto6.randomUUID)()}.tmp`;
21911
22045
  try {
21912
- (0, import_node_fs8.writeFileSync)(temp, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
21913
- (0, import_node_fs8.renameSync)(temp, path);
21914
- (0, import_node_fs8.chmodSync)(path, 384);
22046
+ (0, import_node_fs9.writeFileSync)(temp, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
22047
+ (0, import_node_fs9.renameSync)(temp, path);
22048
+ (0, import_node_fs9.chmodSync)(path, 384);
21915
22049
  } catch (error) {
21916
22050
  try {
21917
- (0, import_node_fs8.unlinkSync)(temp);
22051
+ (0, import_node_fs9.unlinkSync)(temp);
21918
22052
  } catch {
21919
22053
  }
21920
22054
  throw error;
@@ -21927,9 +22061,9 @@ function pruneValidationState(repo) {
21927
22061
  const dir = stateDir(repo);
21928
22062
  let files;
21929
22063
  try {
21930
- files = (0, import_node_fs8.readdirSync)(dir).filter((name) => TOKEN_RX.test(name.replace(/\.json$/, ""))).map((name) => {
21931
- const path = (0, import_node_path8.join)(dir, name);
21932
- return { path, mtimeMs: (0, import_node_fs8.statSync)(path).mtimeMs };
22064
+ files = (0, import_node_fs9.readdirSync)(dir).filter((name) => TOKEN_RX.test(name.replace(/\.json$/, ""))).map((name) => {
22065
+ const path = (0, import_node_path9.join)(dir, name);
22066
+ return { path, mtimeMs: (0, import_node_fs9.statSync)(path).mtimeMs };
21933
22067
  }).sort((a, b) => b.mtimeMs - a.mtimeMs);
21934
22068
  } catch {
21935
22069
  return;
@@ -21938,7 +22072,7 @@ function pruneValidationState(repo) {
21938
22072
  for (const [index, file] of files.entries()) {
21939
22073
  if (index >= MAX_SESSIONS || now - file.mtimeMs > MAX_AGE_MS) {
21940
22074
  try {
21941
- (0, import_node_fs8.unlinkSync)(file.path);
22075
+ (0, import_node_fs9.unlinkSync)(file.path);
21942
22076
  } catch {
21943
22077
  }
21944
22078
  }
@@ -21949,7 +22083,7 @@ function startValidationSession(args) {
21949
22083
  const token = validationSessionToken(args.agent, args.sessionId);
21950
22084
  const existing = readValidationSession(repo, token);
21951
22085
  if (existing) {
21952
- const resumed = { ...existing, hookConfigFingerprint: args.hookConfigFingerprint, lastEvidence: void 0 };
22086
+ const resumed = { ...existing, hookConfigFingerprint: args.hookConfigFingerprint, lastEvidence: void 0, lastStop: void 0 };
21953
22087
  writeValidationSession(repo, resumed);
21954
22088
  pruneValidationState(repo);
21955
22089
  return resumed;
@@ -21978,7 +22112,7 @@ function readValidationSession(repo, token) {
21978
22112
  const path = sessionPath(repo, token);
21979
22113
  if (expired(path)) {
21980
22114
  try {
21981
- (0, import_node_fs8.unlinkSync)(path);
22115
+ (0, import_node_fs9.unlinkSync)(path);
21982
22116
  } catch {
21983
22117
  }
21984
22118
  return null;
@@ -21996,7 +22130,7 @@ function readLatestHookValidationSession(repoInput) {
21996
22130
  pruneValidationState(repo);
21997
22131
  let tokens;
21998
22132
  try {
21999
- 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);
22133
+ 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);
22000
22134
  } catch {
22001
22135
  return null;
22002
22136
  }
@@ -22038,6 +22172,16 @@ function writeValidationSession(repo, session) {
22038
22172
  function recordValidationEvidence(repo, session, evidence) {
22039
22173
  writeValidationSession(repo, { ...session, lastEvidence: evidence });
22040
22174
  }
22175
+ function recordStopObservation(repoInput, token, observation, evidence) {
22176
+ const repo = gitRoot(repoInput);
22177
+ const session = readValidationSession(repo, token);
22178
+ if (!session || session.agent === "manual") return false;
22179
+ const next = { ...session, lastStop: observation, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
22180
+ if (evidence === null) delete next.lastEvidence;
22181
+ else if (evidence) next.lastEvidence = evidence;
22182
+ writePrivateJson(sessionPath(repo, token), next);
22183
+ return true;
22184
+ }
22041
22185
  function inspectValidationEvidenceFreshness(repo, evidence) {
22042
22186
  let currentFingerprint = "";
22043
22187
  let currentPlanFingerprint = "";
@@ -22104,8 +22248,8 @@ function markManualVerifyResult(repoInput, passed) {
22104
22248
  }
22105
22249
 
22106
22250
  // src/commands/stop-hooks.ts
22107
- var import_node_fs9 = require("node:fs");
22108
- var import_node_path9 = require("node:path");
22251
+ var import_node_fs10 = require("node:fs");
22252
+ var import_node_path10 = require("node:path");
22109
22253
  var ALL_AGENTS = ["claude", "cursor", "codex"];
22110
22254
  var SCRIPT_REL = ".agents/hooks/harness-agent-hook.sh";
22111
22255
  var SCRIPT_MARK = "harness-kit-managed-hook (agent-lifecycle)";
@@ -22322,7 +22466,7 @@ function installStopHooks(repo, agents, opts = {}) {
22322
22466
  err(`agent hooks require a Git worktree: ${error.message}`);
22323
22467
  return 1;
22324
22468
  }
22325
- if (!(0, import_node_fs9.existsSync)((0, import_node_path9.join)(repo, ".agents", "manifest.yaml"))) {
22469
+ if (!(0, import_node_fs10.existsSync)((0, import_node_path10.join)(repo, ".agents", "manifest.yaml"))) {
22326
22470
  err("agent hooks require .agents/manifest.yaml \u2014 onboard the repository first");
22327
22471
  return 1;
22328
22472
  }
@@ -22374,7 +22518,7 @@ function installStopHooks(repo, agents, opts = {}) {
22374
22518
  writeManagedFiles(repo, targets, {
22375
22519
  authorize: (transactionPreflight) => assertRenderedSourcesUnchanged(inspections, transactionPreflight)
22376
22520
  });
22377
- (0, import_node_fs9.chmodSync)((0, import_node_path9.join)(repo, SCRIPT_REL), 493);
22521
+ (0, import_node_fs10.chmodSync)((0, import_node_path10.join)(repo, SCRIPT_REL), 493);
22378
22522
  } catch (error) {
22379
22523
  err(`agent hooks not installed: ${error.message}`);
22380
22524
  return 1;
@@ -22399,8 +22543,8 @@ function installStopHooks(repo, agents, opts = {}) {
22399
22543
  ok("codex: enabled project hooks -> .codex/config.toml");
22400
22544
  if (linkedPlan) {
22401
22545
  ok("codex: removed project Harness hooks so the user dispatcher is the only lifecycle path -> .codex/hooks.json");
22402
- ok(`codex: installed linked-worktree dispatcher source -> ${(0, import_node_path9.join)(linkedPlan.codexHome, "harness-kit", "codex-linked-dispatch-v1.cjs")}`);
22403
- ok(`codex: registered this worktree -> ${(0, import_node_path9.join)(linkedPlan.gitDir, "harness-kit", "codex-linked-dispatch-v1.json")}`);
22546
+ ok(`codex: installed linked-worktree dispatcher source -> ${(0, import_node_path10.join)(linkedPlan.codexHome, "harness-kit", "codex-linked-dispatch-v1.cjs")}`);
22547
+ ok(`codex: registered this worktree -> ${(0, import_node_path10.join)(linkedPlan.gitDir, "harness-kit", "codex-linked-dispatch-v1.json")}`);
22404
22548
  } else {
22405
22549
  ok("codex: installed SessionStart + Stop hooks -> .codex/hooks.json");
22406
22550
  }
@@ -22410,8 +22554,12 @@ function installStopHooks(repo, agents, opts = {}) {
22410
22554
  linkedPlan?.requiresRuntimeRefresh ? "codex: Orca mirrors this user Hook source into new terminals; start a fresh Orca Agent session, then review `/hooks` once" : linkedPlan ? "codex: run `/hooks` once to review and trust the Harness user dispatcher before it can run" : "codex: run `/hooks` to review and trust the new project hooks before they can run"
22411
22555
  );
22412
22556
  }
22413
- info("\nSessionStart records the exact task base; every Stop reruns run-checks + verify.");
22414
- info("After the first real agent session, run `harness-kit evidence`; no record means that client surface did not execute project hooks.");
22557
+ info(
22558
+ "\nSessionStart records the exact task base. By default (thin) each Stop requires an accepted deliver stamp for the current change; HARNESS_KIT_STOP_MODE=execute makes Stop rerun run-checks + verify itself. Every Stop is recorded as lifecycle evidence."
22559
+ );
22560
+ info(
22561
+ `Prove it: in a fresh Agent session, deliver a change and finish the turn, then \`${repoHarnessInvocation(repo)} evidence --repo . --json\` must show hookActive: true. No lifecycle record means that client surface did not execute project hooks.`
22562
+ );
22415
22563
  info(`Runner is pinned to @erzhe/harness-kit@${package_default.version}; override with HARNESS_KIT_CMD for local development.`);
22416
22564
  return 0;
22417
22565
  }
@@ -22526,7 +22674,7 @@ function codexFeatureEnabled(repo, issues) {
22526
22674
  return enabled;
22527
22675
  }
22528
22676
  function runnerReady(repo, issues) {
22529
- const path = (0, import_node_path10.join)(repo, RUNNER_REL2);
22677
+ const path = (0, import_node_path11.join)(repo, RUNNER_REL2);
22530
22678
  try {
22531
22679
  const inspected = safeProjectText(repo, RUNNER_REL2, issues);
22532
22680
  if (!inspected.exists) {
@@ -22534,7 +22682,7 @@ function runnerReady(repo, issues) {
22534
22682
  return false;
22535
22683
  }
22536
22684
  if (inspected.content === null) return false;
22537
- const stat = (0, import_node_fs10.lstatSync)(path);
22685
+ const stat = (0, import_node_fs11.lstatSync)(path);
22538
22686
  const withoutOptionalFinalNewline = (value) => value.endsWith("\n") ? value.slice(0, -1) : value;
22539
22687
  const ready = stat.isFile() && !stat.isSymbolicLink() && (stat.mode & 64) !== 0 && withoutOptionalFinalNewline(inspected.content) === withoutOptionalFinalNewline(installedAgentHookRunnerScript());
22540
22688
  if (!ready) issues.push(`${RUNNER_REL2} is not a managed executable runner`);
@@ -22546,7 +22694,7 @@ function runnerReady(repo, issues) {
22546
22694
  }
22547
22695
  function codexLinkedRegistrationExists(repo) {
22548
22696
  try {
22549
- return (0, import_node_fs10.existsSync)((0, import_node_path10.join)(gitAdminDir(repo), CODEX_LINKED_REGISTRATION_REL));
22697
+ return (0, import_node_fs11.existsSync)((0, import_node_path11.join)(gitAdminDir(repo), CODEX_LINKED_REGISTRATION_REL));
22550
22698
  } catch {
22551
22699
  return false;
22552
22700
  }
@@ -22583,7 +22731,7 @@ function agentHookConfigurationFingerprint(repo, agent) {
22583
22731
  artifacts.push({
22584
22732
  path: rel,
22585
22733
  content: inspected.content,
22586
- ...rel === RUNNER_REL2 ? { mode: (0, import_node_fs10.lstatSync)((0, import_node_path10.join)(repo, rel)).mode & 4095 } : {}
22734
+ ...rel === RUNNER_REL2 ? { mode: (0, import_node_fs11.lstatSync)((0, import_node_path11.join)(repo, rel)).mode & 4095 } : {}
22587
22735
  });
22588
22736
  }
22589
22737
  artifacts.push(...linkedArtifacts);
@@ -22618,7 +22766,12 @@ function inspectAgentHookStatus(repo) {
22618
22766
  try {
22619
22767
  const session = readLatestHookValidationSession(repo);
22620
22768
  const evidence = session?.lastEvidence;
22621
- if (session && session.agent !== "manual" && evidence) {
22769
+ if (session && session.agent !== "manual" && !evidence && session.lastStop?.decision === "block") {
22770
+ evidenceAgent = session.agent;
22771
+ evidenceAt = session.lastStop.at;
22772
+ evidenceInvalid = true;
22773
+ issues.push(`latest lifecycle evidence: ${session.agent} Stop blocked (${session.lastStop.reason}); run deliver, then finish the turn again`);
22774
+ } else if (session && session.agent !== "manual" && evidence) {
22622
22775
  evidenceAgent = session.agent;
22623
22776
  evidenceAt = evidence.createdAt;
22624
22777
  const freshness = inspectValidationEvidenceFreshness(repo, evidence);
@@ -22655,37 +22808,37 @@ function inspectAgentHookStatus(repo) {
22655
22808
  }
22656
22809
 
22657
22810
  // src/state.ts
22658
- var import_node_fs11 = require("node:fs");
22659
- var import_node_path11 = require("node:path");
22811
+ var import_node_fs12 = require("node:fs");
22812
+ var import_node_path12 = require("node:path");
22660
22813
  var import_fast_glob2 = __toESM(require_out4(), 1);
22661
22814
  var STATE_REL = ".agents/.harness-state.json";
22662
22815
  function inside3(base, target) {
22663
- const rel = (0, import_node_path11.relative)(base, target);
22664
- return rel === "" || !rel.startsWith("..") && !(0, import_node_path11.isAbsolute)(rel);
22816
+ const rel = (0, import_node_path12.relative)(base, target);
22817
+ return rel === "" || !rel.startsWith("..") && !(0, import_node_path12.isAbsolute)(rel);
22665
22818
  }
22666
22819
  function resolveKnowledgePath(repo, knowledge) {
22667
- const base = knowledge.root === "repo" ? (0, import_node_path11.resolve)(repo) : (0, import_node_path11.resolve)(repo, ".agents");
22668
- const target = (0, import_node_path11.resolve)(base, knowledge.path);
22820
+ const base = knowledge.root === "repo" ? (0, import_node_path12.resolve)(repo) : (0, import_node_path12.resolve)(repo, ".agents");
22821
+ const target = (0, import_node_path12.resolve)(base, knowledge.path);
22669
22822
  if (!inside3(base, target)) throw new Error(`knowledge path escapes ${knowledge.root === "repo" ? "repository" : ".agents"}: ${knowledge.path}`);
22670
22823
  return target;
22671
22824
  }
22672
22825
  function hashPath(absPath) {
22673
- if (!(0, import_node_fs11.existsSync)(absPath)) return "(missing)";
22826
+ if (!(0, import_node_fs12.existsSync)(absPath)) return "(missing)";
22674
22827
  let stat;
22675
22828
  try {
22676
- stat = (0, import_node_fs11.statSync)(absPath);
22829
+ stat = (0, import_node_fs12.statSync)(absPath);
22677
22830
  } catch {
22678
22831
  return "(missing)";
22679
22832
  }
22680
22833
  if (stat.isFile()) return hashFile(absPath) ?? "(missing)";
22681
22834
  if (!stat.isDirectory()) return "(missing)";
22682
22835
  const files = import_fast_glob2.default.sync("**/*", { cwd: absPath, onlyFiles: true, dot: true, followSymbolicLinks: false }).sort();
22683
- const entries = files.map((path) => [path, hashFile((0, import_node_path11.join)(absPath, path)) ?? "(missing)"]);
22836
+ const entries = files.map((path) => [path, hashFile((0, import_node_path12.join)(absPath, path)) ?? "(missing)"]);
22684
22837
  return sha256(JSON.stringify(entries));
22685
22838
  }
22686
22839
  function sourceHashes(repo, paths) {
22687
22840
  const result = {};
22688
- for (const path of paths) result[path] = hashFile((0, import_node_path11.join)(repo, path)) ?? "(missing)";
22841
+ for (const path of paths) result[path] = hashFile((0, import_node_path12.join)(repo, path)) ?? "(missing)";
22689
22842
  return result;
22690
22843
  }
22691
22844
  function knowledgeKey(knowledge) {
@@ -22739,14 +22892,17 @@ function contextSnapshots(repo, manifest) {
22739
22892
  }
22740
22893
  return snapshots;
22741
22894
  }
22742
- function readState(repo) {
22743
- const raw = readText((0, import_node_path11.join)(repo, STATE_REL));
22744
- if (!raw) return null;
22895
+ function parseState2(raw) {
22745
22896
  const value = JSON.parse(raw);
22746
22897
  return { bindings: value.bindings ?? {}, reviews: value.reviews ?? {} };
22747
22898
  }
22899
+ function readState(repo) {
22900
+ const raw = readText((0, import_node_path12.join)(repo, STATE_REL));
22901
+ if (!raw) return null;
22902
+ return parseState2(raw);
22903
+ }
22748
22904
  function writeState(repo, state) {
22749
- writeText((0, import_node_path11.join)(repo, STATE_REL), JSON.stringify(state, null, 2) + "\n");
22905
+ writeText((0, import_node_path12.join)(repo, STATE_REL), JSON.stringify(state, null, 2) + "\n");
22750
22906
  }
22751
22907
  function changedSources(before, after) {
22752
22908
  return [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((path) => before[path] !== after[path]).sort();
@@ -22769,6 +22925,7 @@ function inspectContextFreshness(repo, manifest) {
22769
22925
  kind: snapshot.kind,
22770
22926
  target: snapshot.target,
22771
22927
  severity: "blocking",
22928
+ code: "source-missing",
22772
22929
  reason: "\u7ED1\u5B9A\u6E90\u6587\u4EF6\u7F3A\u5931\uFF0C\u4E0D\u80FD\u628A\u4E0A\u4E0B\u6587\u89C6\u4E3A\u5DF2\u590D\u6838",
22773
22930
  changedSources: missing
22774
22931
  });
@@ -22781,6 +22938,7 @@ function inspectContextFreshness(repo, manifest) {
22781
22938
  kind: snapshot.kind,
22782
22939
  target: snapshot.target,
22783
22940
  severity: "blocking",
22941
+ code: "authority-changed",
22784
22942
  reason: `authority \u5728\u590D\u6838\u540E\u4ECE ${review.authority} \u53D8\u4E3A ${expectedAuthority}`,
22785
22943
  changedSources: changedSources(review.sources, snapshot.sources)
22786
22944
  });
@@ -22793,6 +22951,7 @@ function inspectContextFreshness(repo, manifest) {
22793
22951
  kind: snapshot.kind,
22794
22952
  target: snapshot.target,
22795
22953
  severity: "blocking",
22954
+ code: "review-missing",
22796
22955
  reason: `\u5C1A\u672A\u8BB0\u5F55\u590D\u6838\uFF08authority: ${snapshot.authority}\uFF09`,
22797
22956
  changedSources: Object.keys(snapshot.sources).sort()
22798
22957
  });
@@ -22805,6 +22964,7 @@ function inspectContextFreshness(repo, manifest) {
22805
22964
  kind: snapshot.kind,
22806
22965
  target: snapshot.target,
22807
22966
  severity: "blocking",
22967
+ code: "content-changed",
22808
22968
  reason: "\u77E5\u8BC6\u5185\u5BB9\u5728\u590D\u6838\u540E\u53D1\u751F\u53D8\u5316\uFF0C\u5FC5\u987B\u91CD\u65B0\u8BB0\u5F55\u590D\u6838",
22809
22969
  changedSources: sources2
22810
22970
  });
@@ -22814,6 +22974,7 @@ function inspectContextFreshness(repo, manifest) {
22814
22974
  kind: snapshot.kind,
22815
22975
  target: snapshot.target,
22816
22976
  severity: "blocking",
22977
+ code: "sources-changed",
22817
22978
  reason: `\u7ED1\u5B9A\u6E90\u6587\u4EF6\u5728\u590D\u6838\u540E\u53D1\u751F\u53D8\u5316\uFF08authority: ${snapshot.authority}\uFF09`,
22818
22979
  changedSources: sources2
22819
22980
  });
@@ -22828,6 +22989,7 @@ function inspectContextFreshness(repo, manifest) {
22828
22989
  kind: snapshot.kind,
22829
22990
  target: snapshot.target,
22830
22991
  severity: "blocking",
22992
+ code: review.contentHash !== snapshot.contentHash ? "content-changed" : "sources-changed",
22831
22993
  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",
22832
22994
  changedSources: sources2
22833
22995
  });
@@ -22843,6 +23005,7 @@ function inspectContextFreshness(repo, manifest) {
22843
23005
  kind: snapshot.kind,
22844
23006
  target: snapshot.target,
22845
23007
  severity: "advisory",
23008
+ code: "legacy-baseline-changed",
22846
23009
  reason: "legacy freshness baseline changed; record a context review to make it durable",
22847
23010
  changedSources: sources
22848
23011
  });
@@ -22856,12 +23019,53 @@ function inspectContextFreshness(repo, manifest) {
22856
23019
  kind: review.kind,
22857
23020
  target: review.target,
22858
23021
  severity: "blocking",
23022
+ code: "orphan-review",
22859
23023
  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",
22860
23024
  changedSources: Object.keys(review.sources ?? {}).sort()
22861
23025
  });
22862
23026
  }
22863
23027
  return issues;
22864
23028
  }
23029
+ function repoRelative(path) {
23030
+ return import_node_path12.posix.normalize(path.split(import_node_path12.sep).join("/")).replace(/^\.\//, "").replace(/\/+$/, "");
23031
+ }
23032
+ function contextPaths(manifest, key) {
23033
+ const paths = [];
23034
+ for (const knowledge of manifest?.knowledge ?? []) {
23035
+ if (knowledgeKey(knowledge) !== key) continue;
23036
+ paths.push(repoRelative(knowledge.root === "repo" ? knowledge.path : `.agents/${knowledge.path}`));
23037
+ paths.push(...(knowledge.binds ?? []).map(repoRelative));
23038
+ }
23039
+ for (const module2 of manifest?.modules ?? []) {
23040
+ if (`module:${module2.name}` === key) paths.push(...(module2.entry ?? []).map(repoRelative));
23041
+ }
23042
+ return paths;
23043
+ }
23044
+ function contextDeclaration(manifest, key) {
23045
+ return JSON.stringify([
23046
+ ...(manifest?.knowledge ?? []).filter((knowledge) => knowledgeKey(knowledge) === key).map((knowledge) => ({ binds: knowledge.binds ?? [], authority: knowledge.authority ?? null })),
23047
+ ...(manifest?.modules ?? []).filter((module2) => `module:${module2.name}` === key).map(moduleContentHash)
23048
+ ]);
23049
+ }
23050
+ function contextReviewEvidence(state, issue) {
23051
+ const legacyKey = issue.kind === "knowledge" ? issue.target : issue.key;
23052
+ return JSON.stringify([state?.reviews?.[issue.key] ?? null, state?.bindings?.[legacyKey] ?? null]);
23053
+ }
23054
+ function inheritedContextKeys(issues, current, base, changedFiles) {
23055
+ const inherited = /* @__PURE__ */ new Set();
23056
+ if (!base.manifest) return inherited;
23057
+ const changed = changedFiles.map(repoRelative);
23058
+ const touches = (path) => changed.some((file) => file === path || file.startsWith(`${path}/`));
23059
+ for (const issue of issues) {
23060
+ if (issue.severity !== "blocking") continue;
23061
+ if (contextDeclaration(current.manifest, issue.key) !== contextDeclaration(base.manifest, issue.key)) continue;
23062
+ if (contextReviewEvidence(current.state, issue) !== contextReviewEvidence(base.state, issue)) continue;
23063
+ const paths = [...contextPaths(current.manifest, issue.key), ...issue.changedSources.map(repoRelative)];
23064
+ if (paths.some(touches)) continue;
23065
+ inherited.add(issue.key);
23066
+ }
23067
+ return inherited;
23068
+ }
22865
23069
  function recordContextReview(repo, manifest, opts) {
22866
23070
  if (!!opts.path === !!opts.module) throw new Error("\u53EA\u80FD\u6307\u5B9A\u4E00\u4E2A --path \u6216 --module");
22867
23071
  const reason = opts.reason?.trim();
@@ -22902,6 +23106,7 @@ var AGENTS_MAX_WORDS = 700;
22902
23106
  function doctorCmd(repo, opts = {}) {
22903
23107
  let problems = 0;
22904
23108
  const m = loadManifest(repo);
23109
+ const render = { harnessVersion: lockedHarnessVersion(repo) };
22905
23110
  info("1) Manifest validation");
22906
23111
  const issues = validateManifest(m);
22907
23112
  if (!issues.length) ok("schema looks good");
@@ -22929,16 +23134,20 @@ function doctorCmd(repo, opts = {}) {
22929
23134
  if (n === 0 && !inv.enforcement.allow_empty)
22930
23135
  warn(`invariant ${inv.id}: enforcement path_glob matches 0 files \u2014 passes without checking anything (wrong path_glob for this repo layout?)`);
22931
23136
  }
23137
+ const repoFiles = (m.modules ?? []).some((mod) => mod.owns?.length || mod.tests?.length) ? import_fast_glob3.default.sync("**/*", { cwd: repo, onlyFiles: true, dot: true, ignore: ["**/node_modules/**", "**/.git/**", "**/dist/**"] }) : [];
23138
+ const matchesNothing = (glob) => {
23139
+ const matcher = (0, import_picomatch4.default)(glob, { dot: true });
23140
+ return !repoFiles.some((file) => matcher(file));
23141
+ };
22932
23142
  for (const mod of m.modules ?? []) {
22933
- if (!mod.owns?.length) continue;
22934
- const n = import_fast_glob3.default.sync(mod.owns, {
22935
- cwd: repo,
22936
- onlyFiles: true,
22937
- dot: true,
22938
- ignore: ["**/node_modules/**", "**/.git/**", "**/dist/**"]
22939
- }).length;
22940
- if (n === 0)
23143
+ const deadOwns = (mod.owns ?? []).filter(matchesNothing);
23144
+ if (deadOwns.length && deadOwns.length === mod.owns.length)
22941
23145
  warn(`module ${mod.name}: owns glob matches 0 files \u2014 impact planner can never select it (stale owns for this layout?)`);
23146
+ else
23147
+ for (const glob of deadOwns)
23148
+ warn(`module ${mod.name}: owns glob "${glob}" matches 0 files \u2014 changes under it can never select this module (stale path?)`);
23149
+ for (const glob of (mod.tests ?? []).filter(matchesNothing))
23150
+ warn(`module ${mod.name}: tests glob "${glob}" matches 0 files \u2014 it can never map a test change or satisfy test_touch (stale path?)`);
22942
23151
  }
22943
23152
  for (const glob of m.validation?.required_coverage ?? []) {
22944
23153
  const n = import_fast_glob3.default.sync(glob, {
@@ -22961,18 +23170,18 @@ function doctorCmd(repo, opts = {}) {
22961
23170
  }
22962
23171
  info("\n2) Referenced paths");
22963
23172
  const checkPath = (rel, label) => {
22964
- if ((0, import_node_fs12.existsSync)((0, import_node_path12.join)(repo, ".agents", rel))) ok(`${label}: ${rel}`);
23173
+ if ((0, import_node_fs13.existsSync)((0, import_node_path13.join)(repo, ".agents", rel))) ok(`${label}: ${rel}`);
22965
23174
  else {
22966
23175
  err(`${label} missing: .agents/${rel}`);
22967
23176
  problems++;
22968
23177
  }
22969
23178
  };
22970
23179
  const checkRepoPath = (rel, label, wantFile = false) => {
22971
- const abs = (0, import_node_path12.join)(repo, rel);
22972
- if (!(0, import_node_fs12.existsSync)(abs)) {
23180
+ const abs = (0, import_node_path13.join)(repo, rel);
23181
+ if (!(0, import_node_fs13.existsSync)(abs)) {
22973
23182
  err(`${label} points at a missing path: ${rel}`);
22974
23183
  problems++;
22975
- } else if (wantFile && (0, import_node_fs12.statSync)(abs).isDirectory()) {
23184
+ } else if (wantFile && (0, import_node_fs13.statSync)(abs).isDirectory()) {
22976
23185
  warn(`${label}: ${rel} is a directory \u2014 entry/binds should be a file (freshness hashes file content)`);
22977
23186
  } else ok(`${label}: ${rel}`);
22978
23187
  };
@@ -22999,7 +23208,7 @@ function doctorCmd(repo, opts = {}) {
22999
23208
  problems++;
23000
23209
  continue;
23001
23210
  }
23002
- if ((0, import_node_fs12.existsSync)(knowledgePath)) ok(`knowledge: ${k.path}`);
23211
+ if ((0, import_node_fs13.existsSync)(knowledgePath)) ok(`knowledge: ${k.path}`);
23003
23212
  else {
23004
23213
  err(`knowledge missing: ${k.root === "repo" ? "" : ".agents/"}${k.path}`);
23005
23214
  problems++;
@@ -23014,11 +23223,11 @@ function doctorCmd(repo, opts = {}) {
23014
23223
  for (const mod of m.modules ?? []) {
23015
23224
  if (!mod.playbook) continue;
23016
23225
  const candidates = [
23017
- m.playbooks?.dir ? (0, import_node_path12.join)(repo, ".agents", m.playbooks.dir, mod.playbook) : "",
23018
- (0, import_node_path12.join)(repo, ".agents", mod.playbook),
23019
- (0, import_node_path12.join)(repo, mod.playbook)
23226
+ m.playbooks?.dir ? (0, import_node_path13.join)(repo, ".agents", m.playbooks.dir, mod.playbook) : "",
23227
+ (0, import_node_path13.join)(repo, ".agents", mod.playbook),
23228
+ (0, import_node_path13.join)(repo, mod.playbook)
23020
23229
  ].filter(Boolean);
23021
- if (candidates.some((c) => (0, import_node_fs12.existsSync)(c))) ok(`module ${mod.name} playbook: ${mod.playbook}`);
23230
+ if (candidates.some((c) => (0, import_node_fs13.existsSync)(c))) ok(`module ${mod.name} playbook: ${mod.playbook}`);
23022
23231
  else {
23023
23232
  err(`module ${mod.name} playbook missing: ${mod.playbook} (looked in ${m.playbooks?.dir ? `.agents/${m.playbooks.dir}/, ` : ""}.agents/, repo root)`);
23024
23233
  problems++;
@@ -23026,7 +23235,7 @@ function doctorCmd(repo, opts = {}) {
23026
23235
  }
23027
23236
  info("\n3) Generated files drift");
23028
23237
  try {
23029
- for (const inspection of inspectManagedFiles(repo, renderTargets(m))) {
23238
+ for (const inspection of inspectManagedFiles(repo, renderTargets(m, render))) {
23030
23239
  if (inspection.kind === "missing") warn(`${inspection.relativePath} not generated yet (run \`harness-kit sync\`)`);
23031
23240
  else if (!inspection.satisfiesDesired) {
23032
23241
  err(`${inspection.relativePath} drifted from manifest (run \`harness-kit sync\`)`);
@@ -23073,7 +23282,7 @@ function doctorCmd(repo, opts = {}) {
23073
23282
  } else info(" details: `harness-kit doctor --details`");
23074
23283
  }
23075
23284
  info("\n6) AGENTS.md size budget (must stay short \u2014 agents read it every session)");
23076
- const agents = renderAgentsMd(m);
23285
+ const agents = renderAgentsMd(m, render);
23077
23286
  const nLines = agents.split("\n").length;
23078
23287
  const nWords = agents.trim().split(/\s+/).length;
23079
23288
  if (nLines > AGENTS_MAX_LINES || nWords > AGENTS_MAX_WORDS) {
@@ -23093,7 +23302,7 @@ function doctorCmd(repo, opts = {}) {
23093
23302
  } else {
23094
23303
  warn(`DEGRADED \u2014 configured: ${configuredAgents}; ${hooks.issues.join("; ")}`);
23095
23304
  }
23096
- const guidance = buildHarnessGuidance({ manifest: m, hooks });
23305
+ const guidance = buildHarnessGuidance({ manifest: m, hooks, cli: repoHarnessInvocation(repo) });
23097
23306
  const visibleActions = opts.details ? guidance.nextActions : guidance.nextActions.filter((action) => action.priority === "required");
23098
23307
  info("\nNEXT ACTIONS");
23099
23308
  if (!visibleActions.length) ok("nothing required now");
@@ -23123,10 +23332,186 @@ function doctorCmd(repo, opts = {}) {
23123
23332
  // src/commands/verify.ts
23124
23333
  var import_node_child_process5 = require("node:child_process");
23125
23334
 
23335
+ // src/delivery.ts
23336
+ var import_node_crypto7 = require("node:crypto");
23337
+ var import_node_fs14 = require("node:fs");
23338
+ var import_node_path14 = require("node:path");
23339
+ var import_yaml3 = __toESM(require_dist(), 1);
23340
+ function canonicalTarget2(repo) {
23341
+ try {
23342
+ return (0, import_node_fs14.realpathSync)(repo);
23343
+ } catch {
23344
+ return (0, import_node_path14.resolve)(repo);
23345
+ }
23346
+ }
23347
+ function taskStateDir(repo) {
23348
+ return (0, import_node_path14.join)(gitAdminDir(repo), "harness-kit", "task");
23349
+ }
23350
+ function taskPath(repo) {
23351
+ return (0, import_node_path14.join)(taskStateDir(repo), `current-${sha256(canonicalTarget2(repo)).slice(0, 24)}.json`);
23352
+ }
23353
+ function writePrivateJson2(path, value) {
23354
+ (0, import_node_fs14.mkdirSync)((0, import_node_path14.dirname)(path), { recursive: true });
23355
+ const temp = `${path}.${process.pid}.${(0, import_node_crypto7.randomUUID)()}.tmp`;
23356
+ try {
23357
+ (0, import_node_fs14.writeFileSync)(temp, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
23358
+ (0, import_node_fs14.renameSync)(temp, path);
23359
+ (0, import_node_fs14.chmodSync)(path, 384);
23360
+ } catch (error) {
23361
+ try {
23362
+ (0, import_node_fs14.unlinkSync)(temp);
23363
+ } catch {
23364
+ }
23365
+ throw error;
23366
+ }
23367
+ }
23368
+ function readTaskRecord(repoInput) {
23369
+ const repo = gitRoot(repoInput);
23370
+ const raw = readText(taskPath(repo));
23371
+ if (raw === null) return null;
23372
+ try {
23373
+ const value = JSON.parse(raw);
23374
+ if (value?.schema !== "ai-harness/task/v1" || typeof value.baseSha !== "string" || !value.baseSha) return null;
23375
+ return value;
23376
+ } catch {
23377
+ return null;
23378
+ }
23379
+ }
23380
+ function startTaskRecord(args) {
23381
+ const repo = gitRoot(args.repo);
23382
+ const head = collectChanges(repo, "HEAD", { mode: "exact" }).head;
23383
+ const baseSha = args.baseSha ?? head;
23384
+ if (!baseSha) throw new Error("cannot start task: repository has no HEAD commit and no --base was provided");
23385
+ collectChanges(repo, baseSha, { mode: "exact" });
23386
+ const record = {
23387
+ schema: "ai-harness/task/v1",
23388
+ baseSha,
23389
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
23390
+ ...args.note?.trim() ? { note: args.note.trim() } : {},
23391
+ ...args.hostSessionId ? { hostSessionId: args.hostSessionId } : {},
23392
+ ...args.agent ? { agent: args.agent } : {}
23393
+ };
23394
+ writePrivateJson2(taskPath(repo), record);
23395
+ return record;
23396
+ }
23397
+ function resolveChangeScope(repoInput, opts = {}) {
23398
+ const repo = gitRoot(repoInput);
23399
+ if (opts.base !== void 0) {
23400
+ const changes2 = collectChanges(repo, opts.base, { mode: "exact" });
23401
+ return { kind: "explicit-base", base: opts.base, mode: "exact", changes: changes2, task: readTaskRecord(repo) };
23402
+ }
23403
+ const task = readTaskRecord(repo);
23404
+ if (task) {
23405
+ const changes2 = collectChanges(repo, task.baseSha, { mode: "exact" });
23406
+ return { kind: "task", base: task.baseSha, mode: "exact", changes: changes2, task };
23407
+ }
23408
+ const changes = collectChanges(repo, "HEAD", { mode: "exact" });
23409
+ return { kind: "worktree", base: "HEAD", mode: "exact", changes, task: null };
23410
+ }
23411
+ function stampFromEvidence(repo, session) {
23412
+ if (!session?.lastEvidence) {
23413
+ return { status: "missing", found: false, stale: false, valid: false, reason: "no delivery evidence recorded" };
23414
+ }
23415
+ const evidence = session.lastEvidence;
23416
+ const freshness = inspectValidationEvidenceFreshness(repo, evidence);
23417
+ const runChecksValid = (evidence.runChecksStatus !== void 0 ? evidence.runChecksStatus !== "not-verified" : evidence.ok && evidence.status !== "not-verified") && !freshness.stale;
23418
+ const verifyPassed = evidence.verifyPassed === true;
23419
+ const valid = runChecksValid && verifyPassed && !freshness.error;
23420
+ let status;
23421
+ if (freshness.stale || freshness.error) status = "stale";
23422
+ else if (evidence.status === "no-change" && verifyPassed) status = "no-change";
23423
+ else if (valid) status = "accepted";
23424
+ else status = "needs-work";
23425
+ return {
23426
+ status,
23427
+ found: true,
23428
+ fingerprint: evidence.fingerprint,
23429
+ planFingerprint: evidence.planFingerprint,
23430
+ runChecksStatus: evidence.runChecksStatus ?? evidence.status,
23431
+ verifyPassed: evidence.verifyPassed,
23432
+ scopeBase: evidence.resolvedBase ?? evidence.requestedBase,
23433
+ createdAt: evidence.createdAt,
23434
+ session: session.token,
23435
+ stale: freshness.stale || !!freshness.error,
23436
+ valid,
23437
+ reason: freshness.error || void 0
23438
+ };
23439
+ }
23440
+ function inspectDeliveryStamp(repoInput) {
23441
+ const repo = gitRoot(repoInput);
23442
+ try {
23443
+ return stampFromEvidence(repo, readLatestValidationSession(repo));
23444
+ } catch (error) {
23445
+ return {
23446
+ status: "missing",
23447
+ found: false,
23448
+ stale: false,
23449
+ valid: false,
23450
+ reason: `cannot read delivery stamp: ${error.message}`
23451
+ };
23452
+ }
23453
+ }
23454
+ function stampCoversScope(repoInput, scope) {
23455
+ const stamp = inspectDeliveryStamp(repoInput);
23456
+ if (!stamp.found || stamp.stale || !stamp.valid) return false;
23457
+ if (scope.changes.files.length === 0) return stamp.status === "no-change" || stamp.status === "accepted";
23458
+ return stamp.status === "accepted" && stamp.fingerprint === scope.changes.fingerprint;
23459
+ }
23460
+ function coveringStampEvidence(repoInput, scope) {
23461
+ if (!stampCoversScope(repoInput, scope)) return null;
23462
+ try {
23463
+ return readLatestValidationSession(gitRoot(repoInput))?.lastEvidence ?? null;
23464
+ } catch {
23465
+ return null;
23466
+ }
23467
+ }
23468
+ function inheritedContextIssueKeys(repo, manifest, issues, base) {
23469
+ if (!issues.some((issue) => issue.severity === "blocking")) return /* @__PURE__ */ new Set();
23470
+ const changes = collectChanges(repo, base, { mode: "exact" });
23471
+ if (!changes.resolvedBase) return /* @__PURE__ */ new Set();
23472
+ const manifestText = readFileAtCommit(repo, changes.resolvedBase, MANIFEST_REL);
23473
+ if (manifestText === null) return /* @__PURE__ */ new Set();
23474
+ const parsed = import_yaml3.default.parse(manifestText);
23475
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return /* @__PURE__ */ new Set();
23476
+ const stateText = readFileAtCommit(repo, changes.resolvedBase, STATE_REL);
23477
+ const baseState = stateText ? parseState2(stateText) : null;
23478
+ return inheritedContextKeys(
23479
+ issues,
23480
+ { manifest, state: readState(repo) },
23481
+ { manifest: parsed, state: baseState },
23482
+ changes.files
23483
+ );
23484
+ }
23485
+ function locateHarnessTargets(repoInput) {
23486
+ const repo = (0, import_node_path14.resolve)(repoInput);
23487
+ if ((0, import_node_fs14.existsSync)((0, import_node_path14.join)(repo, MANIFEST_REL))) return { adopted: true, enclosing: null, nested: [] };
23488
+ let root;
23489
+ try {
23490
+ root = canonicalTarget2(gitRoot(repo));
23491
+ } catch {
23492
+ return { adopted: false, enclosing: null, nested: [] };
23493
+ }
23494
+ let enclosing = null;
23495
+ for (let dir = canonicalTarget2(repo); dir !== root && (0, import_node_path14.dirname)(dir) !== dir; ) {
23496
+ dir = (0, import_node_path14.dirname)(dir);
23497
+ if ((0, import_node_fs14.existsSync)((0, import_node_path14.join)(dir, MANIFEST_REL))) {
23498
+ enclosing = dir;
23499
+ break;
23500
+ }
23501
+ }
23502
+ let nested = [];
23503
+ try {
23504
+ const suffix = `/${MANIFEST_REL}`;
23505
+ nested = listWorktreeFiles(repo, `**/${MANIFEST_REL}`).filter((path) => path.endsWith(suffix)).map((path) => (0, import_node_path14.join)(repo, path.slice(0, -suffix.length))).sort();
23506
+ } catch {
23507
+ }
23508
+ return { adopted: false, enclosing, nested };
23509
+ }
23510
+
23126
23511
  // src/enforce.ts
23127
23512
  var import_fast_glob4 = __toESM(require_out4(), 1);
23128
- var import_node_fs13 = require("node:fs");
23129
- var import_node_path13 = require("node:path");
23513
+ var import_node_fs15 = require("node:fs");
23514
+ var import_node_path15 = require("node:path");
23130
23515
  var DEFAULT_IGNORE = ["**/node_modules/**", "**/.git/**", "**/dist/**", "**/.agents/map/**"];
23131
23516
  function runEnforcement(repo, invId, e) {
23132
23517
  const globs = e.path_glob?.length ? e.path_glob : ["**/*"];
@@ -23143,7 +23528,7 @@ function runEnforcement(repo, invId, e) {
23143
23528
  for (const rel of files) {
23144
23529
  let content;
23145
23530
  try {
23146
- content = (0, import_node_fs13.readFileSync)((0, import_node_path13.join)(repo, rel), "utf8");
23531
+ content = (0, import_node_fs15.readFileSync)((0, import_node_path15.join)(repo, rel), "utf8");
23147
23532
  } catch {
23148
23533
  continue;
23149
23534
  }
@@ -23234,7 +23619,7 @@ function verifyInternal(repo, opts) {
23234
23619
  const messages = [];
23235
23620
  let manifestErrors = [];
23236
23621
  const hooks = safeInspectAgentHookStatus(repo);
23237
- const guidance = buildHarnessGuidance({ manifest, hooks });
23622
+ const guidance = buildHarnessGuidance({ manifest, hooks, cli: repoHarnessInvocation(repo) });
23238
23623
  const gaps = guidance.gapDetails.map((gap2) => gap2.legacyText);
23239
23624
  const emit = (level, text) => {
23240
23625
  messages.push({ level, text });
@@ -23307,7 +23692,7 @@ verify: FAILED (${manifestErrors.length} manifest problem(s))`);
23307
23692
  }
23308
23693
  emit("info", "1) Generated files in sync");
23309
23694
  try {
23310
- for (const inspection of inspectManagedFiles(repo, renderTargets(manifest))) {
23695
+ for (const inspection of inspectManagedFiles(repo, renderTargets(manifest, { harnessVersion: lockedHarnessVersion(repo) }))) {
23311
23696
  if (inspection.kind === "missing") {
23312
23697
  emit("error", `${inspection.relativePath} missing (run \`harness-kit sync\`)`);
23313
23698
  failures++;
@@ -23323,14 +23708,29 @@ verify: FAILED (${manifestErrors.length} manifest problem(s))`);
23323
23708
  }
23324
23709
  emit("info", "\n2) Context freshness");
23325
23710
  try {
23326
- for (const issue of inspectContextFreshness(repo, manifest)) {
23327
- context.push(issue);
23711
+ const issues = inspectContextFreshness(repo, manifest);
23712
+ let inherited = /* @__PURE__ */ new Set();
23713
+ if (opts.contextBase !== void 0) {
23714
+ try {
23715
+ inherited = inheritedContextIssueKeys(repo, manifest, issues, opts.contextBase);
23716
+ } catch (error) {
23717
+ emit("warn", `cannot compare context freshness with task base ${opts.contextBase}; treating it as task-scoped (${error.message})`);
23718
+ }
23719
+ }
23720
+ for (const issue of issues) {
23328
23721
  const changed = issue.changedSources.length ? ` -> ${issue.changedSources.join(", ")}` : "";
23329
23722
  const message = `${issue.key}: ${issue.reason}${changed}`;
23330
- if (issue.severity === "blocking") {
23723
+ if (issue.severity === "blocking" && inherited.has(issue.key)) {
23724
+ context.push({ ...issue, inherited: true });
23725
+ emit("warn", `${message} (inherited: already stale on task base ${opts.contextBase}; not introduced by this task)`);
23726
+ } else if (issue.severity === "blocking") {
23727
+ context.push(issue);
23331
23728
  failures++;
23332
23729
  emit("error", message);
23333
- } else emit("warn", message);
23730
+ } else {
23731
+ context.push(issue);
23732
+ emit("warn", message);
23733
+ }
23334
23734
  }
23335
23735
  } catch (error) {
23336
23736
  failures++;
@@ -23531,19 +23931,19 @@ function acceptContractCmd(repo, id) {
23531
23931
  }
23532
23932
 
23533
23933
  // src/skill.ts
23534
- var import_node_fs14 = require("node:fs");
23535
- var import_node_path14 = require("node:path");
23934
+ var import_node_fs16 = require("node:fs");
23935
+ var import_node_path16 = require("node:path");
23536
23936
  var import_node_url = require("node:url");
23537
23937
  var import_meta = {};
23538
23938
  function moduleDir() {
23539
23939
  if (typeof __dirname !== "undefined" && __dirname) return __dirname;
23540
- return (0, import_node_path14.dirname)((0, import_node_url.fileURLToPath)(import_meta.url));
23940
+ return (0, import_node_path16.dirname)((0, import_node_url.fileURLToPath)(import_meta.url));
23541
23941
  }
23542
23942
  var HERE = moduleDir();
23543
23943
  function resolveSkill(skillRel) {
23544
- for (const up of [".", "..", (0, import_node_path14.join)("..", "..")]) {
23545
- const p = (0, import_node_path14.join)(HERE, up, skillRel);
23546
- if ((0, import_node_fs14.existsSync)(p)) return p;
23944
+ for (const up of [".", "..", (0, import_node_path16.join)("..", "..")]) {
23945
+ const p = (0, import_node_path16.join)(HERE, up, skillRel);
23946
+ if ((0, import_node_fs16.existsSync)(p)) return p;
23547
23947
  }
23548
23948
  return null;
23549
23949
  }
@@ -23554,7 +23954,7 @@ function printSkill(skillRel, meta = "") {
23554
23954
  return 1;
23555
23955
  }
23556
23956
  if (meta) process.stdout.write(meta);
23557
- process.stdout.write((0, import_node_fs14.readFileSync)(p, "utf8"));
23957
+ process.stdout.write((0, import_node_fs16.readFileSync)(p, "utf8"));
23558
23958
  return 0;
23559
23959
  }
23560
23960
 
@@ -23562,8 +23962,10 @@ function printSkill(skillRel, meta = "") {
23562
23962
  var SKILL_REL = "skills/harness-check-loop/SKILL.md";
23563
23963
  var META = `<!-- harness-kit check-loop -->
23564
23964
  You are an AI agent implementing a requirement or fixing a bug in the CURRENT repo.
23565
- Follow the loop below. Run every harness-kit command through
23566
- \`npx -y @erzhe/harness-kit@latest <cmd>\` unless a local build is available.
23965
+ Follow the loop below. Run every harness-kit command through the pinned
23966
+ \`npx -y @erzhe/harness-kit@<version from .agents/harness.lock.json> <cmd>\`
23967
+ (the "Harness CLI" line in AGENTS.md; \`@latest\` only without a lock) unless a
23968
+ local build is available. A bare \`harness-kit\` is usually not on PATH.
23567
23969
  Primary finish gate: \`harness-kit deliver\` (scope \u2192 run-checks + verify \u2192 stamp).
23568
23970
  Optional Stop hooks only check that stamp; they must not demand a new session.
23569
23971
  Use \`evidence\` to inspect the durable stamp.
@@ -23575,132 +23977,41 @@ function checkLoopCmd() {
23575
23977
  return printSkill(SKILL_REL, META);
23576
23978
  }
23577
23979
 
23578
- // src/delivery.ts
23579
- var import_node_crypto7 = require("node:crypto");
23580
- var import_node_fs15 = require("node:fs");
23581
- var import_node_path15 = require("node:path");
23582
- function canonicalTarget2(repo) {
23583
- try {
23584
- return (0, import_node_fs15.realpathSync)(repo);
23585
- } catch {
23586
- return (0, import_node_path15.resolve)(repo);
23587
- }
23588
- }
23589
- function taskStateDir(repo) {
23590
- return (0, import_node_path15.join)(gitAdminDir(repo), "harness-kit", "task");
23591
- }
23592
- function taskPath(repo) {
23593
- return (0, import_node_path15.join)(taskStateDir(repo), `current-${sha256(canonicalTarget2(repo)).slice(0, 24)}.json`);
23594
- }
23595
- function writePrivateJson2(path, value) {
23596
- (0, import_node_fs15.mkdirSync)((0, import_node_path15.dirname)(path), { recursive: true });
23597
- const temp = `${path}.${process.pid}.${(0, import_node_crypto7.randomUUID)()}.tmp`;
23598
- try {
23599
- (0, import_node_fs15.writeFileSync)(temp, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
23600
- (0, import_node_fs15.renameSync)(temp, path);
23601
- (0, import_node_fs15.chmodSync)(path, 384);
23602
- } catch (error) {
23603
- try {
23604
- (0, import_node_fs15.unlinkSync)(temp);
23605
- } catch {
23606
- }
23607
- throw error;
23608
- }
23609
- }
23610
- function readTaskRecord(repoInput) {
23611
- const repo = gitRoot(repoInput);
23612
- const raw = readText(taskPath(repo));
23613
- if (raw === null) return null;
23614
- try {
23615
- const value = JSON.parse(raw);
23616
- if (value?.schema !== "ai-harness/task/v1" || typeof value.baseSha !== "string" || !value.baseSha) return null;
23617
- return value;
23618
- } catch {
23619
- return null;
23620
- }
23621
- }
23622
- function startTaskRecord(args) {
23623
- const repo = gitRoot(args.repo);
23624
- const head = collectChanges(repo, "HEAD", { mode: "exact" }).head;
23625
- const baseSha = args.baseSha ?? head;
23626
- if (!baseSha) throw new Error("cannot start task: repository has no HEAD commit and no --base was provided");
23627
- collectChanges(repo, baseSha, { mode: "exact" });
23628
- const record = {
23629
- schema: "ai-harness/task/v1",
23630
- baseSha,
23631
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
23632
- ...args.note?.trim() ? { note: args.note.trim() } : {},
23633
- ...args.hostSessionId ? { hostSessionId: args.hostSessionId } : {},
23634
- ...args.agent ? { agent: args.agent } : {}
23635
- };
23636
- writePrivateJson2(taskPath(repo), record);
23637
- return record;
23638
- }
23639
- function resolveChangeScope(repoInput, opts = {}) {
23640
- const repo = gitRoot(repoInput);
23641
- if (opts.base !== void 0) {
23642
- const changes2 = collectChanges(repo, opts.base, { mode: "exact" });
23643
- return { kind: "explicit-base", base: opts.base, mode: "exact", changes: changes2, task: readTaskRecord(repo) };
23644
- }
23645
- const task = readTaskRecord(repo);
23646
- if (task) {
23647
- const changes2 = collectChanges(repo, task.baseSha, { mode: "exact" });
23648
- return { kind: "task", base: task.baseSha, mode: "exact", changes: changes2, task };
23649
- }
23650
- const changes = collectChanges(repo, "HEAD", { mode: "exact" });
23651
- return { kind: "worktree", base: "HEAD", mode: "exact", changes, task: null };
23652
- }
23653
- function stampFromEvidence(repo, session) {
23654
- if (!session?.lastEvidence) {
23655
- return { status: "missing", found: false, stale: false, valid: false, reason: "no delivery evidence recorded" };
23656
- }
23980
+ // src/commands/evidence.ts
23981
+ function lifecycleProof(repo, session) {
23982
+ if (!session || session.agent === "manual") return null;
23983
+ const configurationCurrent = !!session.hookConfigFingerprint && agentHookConfigurationFingerprint(repo, session.agent) === session.hookConfigFingerprint;
23657
23984
  const evidence = session.lastEvidence;
23658
- const freshness = inspectValidationEvidenceFreshness(repo, evidence);
23659
- const runChecksValid = (evidence.runChecksStatus !== void 0 ? evidence.runChecksStatus !== "not-verified" : evidence.ok && evidence.status !== "not-verified") && !freshness.stale;
23660
- const verifyPassed = evidence.verifyPassed === true;
23661
- const valid = runChecksValid && verifyPassed && !freshness.error;
23662
- let status;
23663
- if (freshness.stale || freshness.error) status = "stale";
23664
- else if (evidence.status === "no-change" && verifyPassed) status = "no-change";
23665
- else if (valid) status = "accepted";
23666
- else status = "needs-work";
23985
+ let evidenceValid = false;
23986
+ if (evidence) {
23987
+ const runChecksStatus = evidence.runChecksStatus ?? (evidence.ok ? evidence.status : "not-verified");
23988
+ evidenceValid = runChecksStatus !== "not-verified" && evidence.verifyPassed === true && !inspectValidationEvidenceFreshness(repo, evidence).stale;
23989
+ }
23667
23990
  return {
23668
- status,
23669
- found: true,
23670
- fingerprint: evidence.fingerprint,
23671
- planFingerprint: evidence.planFingerprint,
23672
- runChecksStatus: evidence.runChecksStatus ?? evidence.status,
23673
- verifyPassed: evidence.verifyPassed,
23674
- scopeBase: evidence.resolvedBase ?? evidence.requestedBase,
23675
- createdAt: evidence.createdAt,
23991
+ agent: session.agent,
23676
23992
  session: session.token,
23677
- stale: freshness.stale || !!freshness.error,
23678
- valid,
23679
- reason: freshness.error || void 0
23993
+ sessionStartedAt: session.createdAt,
23994
+ baseSha: session.baseSha,
23995
+ configurationCurrent,
23996
+ stop: session.lastStop ?? null,
23997
+ evidenceSource: evidence ? evidence.source ?? "run-checks" : null,
23998
+ evidenceValid,
23999
+ active: configurationCurrent && evidenceValid
23680
24000
  };
23681
24001
  }
23682
- function inspectDeliveryStamp(repoInput) {
23683
- const repo = gitRoot(repoInput);
24002
+ function safeLifecycleProof(repo, session) {
23684
24003
  try {
23685
- return stampFromEvidence(repo, readLatestValidationSession(repo));
23686
- } catch (error) {
23687
- return {
23688
- status: "missing",
23689
- found: false,
23690
- stale: false,
23691
- valid: false,
23692
- reason: `cannot read delivery stamp: ${error.message}`
23693
- };
24004
+ return lifecycleProof(repo, session === void 0 ? readLatestHookValidationSession(repo) : session);
24005
+ } catch {
24006
+ return null;
23694
24007
  }
23695
24008
  }
23696
- function stampCoversScope(repoInput, scope) {
23697
- const stamp = inspectDeliveryStamp(repoInput);
23698
- if (!stamp.found || stamp.stale || !stamp.valid) return false;
23699
- if (scope.changes.files.length === 0) return stamp.status === "no-change" || stamp.status === "accepted";
23700
- return stamp.status === "accepted" && stamp.fingerprint === scope.changes.fingerprint;
24009
+ function describeLifecycle(lifecycle) {
24010
+ if (!lifecycle) return "lifecycle: no SessionStart recorded by an installed hook";
24011
+ const stop = lifecycle.stop ? `last Stop ${lifecycle.stop.decision} (${lifecycle.stop.mode}, ${lifecycle.stop.reason}) at ${lifecycle.stop.at}` : "no Stop observed yet";
24012
+ const config = lifecycle.configurationCurrent ? "" : "; hook configuration changed since SessionStart";
24013
+ return `lifecycle: ${lifecycle.agent} session started ${lifecycle.sessionStartedAt}; ${stop}${config}; hookActive: ${lifecycle.active ? "yes" : "no"}`;
23701
24014
  }
23702
-
23703
- // src/commands/evidence.ts
23704
24015
  function safeHookStatus(repo) {
23705
24016
  try {
23706
24017
  return inspectAgentHookStatus(repo);
@@ -23735,18 +24046,27 @@ function evidenceCmd(repo, opts = {}) {
23735
24046
  return 1;
23736
24047
  }
23737
24048
  const hooks = safeHookStatus(repo);
24049
+ const lifecycle = safeLifecycleProof(repo, opts.session ? session : void 0);
23738
24050
  if (!session?.lastEvidence) {
23739
- const guidance2 = buildHarnessGuidance({ hooks, evidence: { found: false } });
24051
+ const guidance2 = buildHarnessGuidance({ hooks, evidence: { found: false }, cli: repoHarnessInvocation(repo) });
23740
24052
  if (opts.json) {
23741
24053
  process.stdout.write(
23742
24054
  JSON.stringify(
23743
- { schema: "ai-harness/evidence/v1", found: false, hooks, nextActions: guidance2.nextActions },
24055
+ {
24056
+ schema: "ai-harness/evidence/v1",
24057
+ found: false,
24058
+ hooks,
24059
+ hookActive: lifecycle?.active ?? false,
24060
+ lifecycle,
24061
+ nextActions: guidance2.nextActions
24062
+ },
23744
24063
  null,
23745
24064
  2
23746
24065
  ) + "\n"
23747
24066
  );
23748
24067
  } else {
23749
24068
  warn("no validation evidence recorded for this worktree/session");
24069
+ info(describeLifecycle(lifecycle));
23750
24070
  printNextActions(guidance2.nextActions.filter((action) => action.priority === "required"));
23751
24071
  warn(`Harness readiness: INCOMPLETE (${guidance2.nextActions.filter((action) => action.priority === "required").length} required action(s) above)`);
23752
24072
  }
@@ -23767,11 +24087,12 @@ function evidenceCmd(repo, opts = {}) {
23767
24087
  const runChecksValid = (evidence.runChecksStatus !== void 0 ? evidence.runChecksStatus !== "not-verified" : evidence.ok && evidence.status !== "not-verified") && !stale;
23768
24088
  const valid = runChecksValid && evidence.verifyPassed === true;
23769
24089
  const hookConfigurationCurrent = session.agent !== "manual" && !!session.hookConfigFingerprint && agentHookConfigurationFingerprint(repo, session.agent) === session.hookConfigFingerprint;
23770
- const hookActive = valid && hookConfigurationCurrent;
24090
+ const hookActive = valid && hookConfigurationCurrent || (lifecycle?.active ?? false);
23771
24091
  const stamp = inspectDeliveryStamp(repo);
23772
24092
  const guidance = buildHarnessGuidance({
23773
24093
  hooks,
23774
- evidence: { found: true, stale, runChecksValid, verifyPassed: evidence.verifyPassed, valid }
24094
+ evidence: { found: true, stale, runChecksValid, verifyPassed: evidence.verifyPassed, valid },
24095
+ cli: repoHarnessInvocation(repo)
23775
24096
  });
23776
24097
  const result = {
23777
24098
  ...body,
@@ -23780,6 +24101,7 @@ function evidenceCmd(repo, opts = {}) {
23780
24101
  stamp,
23781
24102
  hookActive,
23782
24103
  hookConfigurationCurrent,
24104
+ lifecycle,
23783
24105
  stale,
23784
24106
  currentFingerprint,
23785
24107
  currentPlanFingerprint,
@@ -23818,6 +24140,7 @@ function evidenceCmd(repo, opts = {}) {
23818
24140
  }
23819
24141
  if (hooks.configuredAgents.length) {
23820
24142
  info(`session intercept: ${hooks.state} (configured: ${hooks.configuredAgents.join(",")})`);
24143
+ info(describeLifecycle(lifecycle));
23821
24144
  } else {
23822
24145
  info("session intercept: none (cooperative deliver only)");
23823
24146
  }
@@ -23829,7 +24152,10 @@ function evidenceCmd(repo, opts = {}) {
23829
24152
  }
23830
24153
 
23831
24154
  // src/commands/hook-event.ts
23832
- var import_node_fs16 = require("node:fs");
24155
+ var import_node_fs17 = require("node:fs");
24156
+
24157
+ // src/commands/deliver.ts
24158
+ var import_node_path17 = require("node:path");
23833
24159
 
23834
24160
  // src/commands/run-checks.ts
23835
24161
  var import_node_child_process6 = require("node:child_process");
@@ -24122,6 +24448,7 @@ function runChecksCmd(repo, opts) {
24122
24448
  }
24123
24449
 
24124
24450
  // src/commands/deliver.ts
24451
+ var DELIVER_NOT_ADOPTED_EXIT_CODE = 3;
24125
24452
  function captureStdout(fn) {
24126
24453
  const chunks = [];
24127
24454
  const original = process.stdout.write.bind(process.stdout);
@@ -24147,7 +24474,18 @@ function parseRunReport(output) {
24147
24474
  return null;
24148
24475
  }
24149
24476
  }
24150
- function nextActions(status, report) {
24477
+ function parseVerifyReport(output) {
24478
+ try {
24479
+ const report = JSON.parse(output);
24480
+ return report?.schema === "ai-harness/verify-report/v1" ? report : null;
24481
+ } catch {
24482
+ return null;
24483
+ }
24484
+ }
24485
+ function shellArg(value) {
24486
+ return /^[A-Za-z0-9_./@:+=,-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
24487
+ }
24488
+ function nextActions(status, report, cli) {
24151
24489
  if (status === "accepted" || status === "no-change") return [];
24152
24490
  const next = [];
24153
24491
  if (report) {
@@ -24161,13 +24499,59 @@ function nextActions(status, report) {
24161
24499
  next.push(`resolve skipped check ${skipped.id}: ${skipped.reason}`);
24162
24500
  }
24163
24501
  }
24164
- next.push("re-run: harness-kit deliver --repo .");
24502
+ next.push(`re-run: ${cli} deliver --repo .`);
24165
24503
  return next;
24166
24504
  }
24167
- function reportHuman2(report) {
24505
+ function inheritedContextActions(issues, base, cli) {
24506
+ return issues.map((issue) => {
24507
+ const changed = issue.changedSources.length ? ` (${issue.changedSources.join(", ")})` : "";
24508
+ const action = {
24509
+ id: `refresh-inherited-context:${issue.key}`,
24510
+ priority: "recommended",
24511
+ owner: "agent",
24512
+ when: "harness-maintenance",
24513
+ title: `Refresh inherited context review: ${issue.target}`,
24514
+ 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.`,
24515
+ commands: [],
24516
+ completion: "verify reports no context freshness issue for this item."
24517
+ };
24518
+ if (issue.code === "source-missing") {
24519
+ action.title = `Fix missing bound sources: ${issue.target}`;
24520
+ action.reason += ` Update its binds/entry in .agents/manifest.yaml first; a review cannot be recorded against missing sources.`;
24521
+ return action;
24522
+ }
24523
+ if (issue.code === "orphan-review") {
24524
+ action.title = `Resolve orphan context review: ${issue.target}`;
24525
+ action.reason += ` Restore its binds/authority in .agents/manifest.yaml, or retire the stale review record deliberately.`;
24526
+ return action;
24527
+ }
24528
+ if (issue.changedSources.length) action.commands.push(`git log -n 5 --oneline -- ${issue.changedSources.map(shellArg).join(" ")}`);
24529
+ const selector = issue.kind === "knowledge" ? `--path ${shellArg(issue.target)}` : `--module ${shellArg(issue.target)}`;
24530
+ action.commands.push(`${cli} record-context-review --repo . ${selector} --reason "<what you re-checked>"`);
24531
+ return action;
24532
+ });
24533
+ }
24534
+ function printActions(actions) {
24535
+ for (const action of actions) {
24536
+ warn(`[${action.priority.toUpperCase()} | ${action.owner.toUpperCase()}] ${action.title}`);
24537
+ info(` why: ${action.reason}`);
24538
+ for (const command of action.commands) info(` run: ${command}`);
24539
+ info(` done when: ${action.completion}`);
24540
+ }
24541
+ }
24542
+ function reportHuman2(report, cli) {
24543
+ if (report.status === "not-adopted" || report.harnessTargets) {
24544
+ for (const message of report.errors) err(message);
24545
+ if (report.status === "not-adopted")
24546
+ warn("deliver: NOT-ADOPTED \u2014 no .agents/manifest.yaml covers this directory; harness-kit cannot accept changes here");
24547
+ else err("deliver: NEEDS-WORK \u2014 run deliver at the Harness target root");
24548
+ info("\nNEXT ACTIONS");
24549
+ printActions(report.nextActions);
24550
+ return;
24551
+ }
24168
24552
  info(`deliver (scope=${report.scope}, base ${report.base}) \u2014 ${report.changed.length} changed file(s)`);
24169
24553
  if (report.scope === "worktree" && report.status !== "no-change") {
24170
- info(" using worktree diff vs HEAD (no task base); for committed task range run: harness-kit task start");
24554
+ info(` using worktree diff vs HEAD (no task base); for committed task range run: ${cli} task-start`);
24171
24555
  }
24172
24556
  if (report.runChecks) {
24173
24557
  info(` run-checks: ${report.runChecks.status} (${report.runChecks.passed.length} passed, ${report.runChecks.failed.length} failed)`);
@@ -24182,6 +24566,15 @@ function reportHuman2(report) {
24182
24566
  }
24183
24567
  if (report.verifyPassed) ok("verify: passed");
24184
24568
  else err("verify: failed");
24569
+ if (report.inheritedContext.length) {
24570
+ warn(
24571
+ `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:`
24572
+ );
24573
+ for (const issue of report.inheritedContext) {
24574
+ const changed = issue.changedSources.length ? ` -> ${issue.changedSources.join(", ")}` : "";
24575
+ info(` ${issue.key}: ${issue.reason}${changed}`);
24576
+ }
24577
+ }
24185
24578
  for (const message of report.errors) err(message);
24186
24579
  info("");
24187
24580
  if (report.status === "accepted") ok("deliver: ACCEPTED \u2014 task stamp is valid for this fingerprint");
@@ -24191,8 +24584,101 @@ function reportHuman2(report) {
24191
24584
  info("\nNEXT");
24192
24585
  for (const step of report.next) info(` - ${step}`);
24193
24586
  }
24587
+ const maintenance = report.nextActions.filter((action) => action.priority === "recommended");
24588
+ if (maintenance.length) {
24589
+ info("\nMAINTENANCE (recommended; keep out of this task's diff unless the task is Harness maintenance)");
24590
+ printActions(maintenance);
24591
+ }
24592
+ }
24593
+ function emitReport(report, json, cli) {
24594
+ if (json) process.stdout.write(JSON.stringify(report, null, 2) + "\n");
24595
+ else reportHuman2(report, cli);
24596
+ if (report.status === "not-adopted") return DELIVER_NOT_ADOPTED_EXIT_CODE;
24597
+ return report.ok ? 0 : 1;
24598
+ }
24599
+ function unadoptedReport(repo, opts, targets) {
24600
+ let scope = null;
24601
+ try {
24602
+ scope = resolveChangeScope(repo, { base: opts.base });
24603
+ } catch {
24604
+ }
24605
+ const base = {
24606
+ schema: "ai-harness/deliver-report/v1",
24607
+ ok: false,
24608
+ scope: scope?.kind ?? "worktree",
24609
+ base: scope?.base ?? opts.base ?? "HEAD",
24610
+ fingerprint: scope?.changes.fingerprint ?? "",
24611
+ changed: scope?.changes.files ?? [],
24612
+ runChecks: null,
24613
+ verifyPassed: false,
24614
+ stamp: { status: "missing", found: false, stale: false, valid: false, reason: "no Harness manifest in this directory" },
24615
+ inheritedContext: [],
24616
+ harnessTargets: { enclosing: targets.enclosing, nested: targets.nested }
24617
+ };
24618
+ if (targets.enclosing) {
24619
+ const command = `${repoHarnessInvocation(targets.enclosing)} deliver --repo ${shellArg(targets.enclosing)}`;
24620
+ return {
24621
+ ...base,
24622
+ status: "needs-work",
24623
+ adopted: true,
24624
+ errors: [`${repo} is inside Harness target ${targets.enclosing}; deliver must run at the target root`],
24625
+ next: [`re-run at the Harness target root: ${command}`],
24626
+ nextActions: [
24627
+ {
24628
+ id: "deliver-at-harness-target-root",
24629
+ priority: "required",
24630
+ owner: "agent",
24631
+ when: "before-finish",
24632
+ title: "Re-run deliver at the Harness target root",
24633
+ reason: `The manifest for this directory lives in ${targets.enclosing}.`,
24634
+ commands: [command],
24635
+ completion: "deliver at the target root reports status=accepted (or no-change on a clean tree)."
24636
+ }
24637
+ ]
24638
+ };
24639
+ }
24640
+ const touched = targets.nested.filter((dir) => base.changed.some((file) => (0, import_node_path17.join)(repo, file).startsWith(`${dir}/`)));
24641
+ const nestedCommands = touched.map((dir) => `${repoHarnessInvocation(dir)} deliver --repo ${shellArg(dir)}`);
24642
+ const nextActions2 = [
24643
+ {
24644
+ id: "validate-with-repository-conventions",
24645
+ priority: "required",
24646
+ owner: "agent",
24647
+ when: "before-finish",
24648
+ title: "Validate with this repository's own conventions",
24649
+ reason: "No .agents/manifest.yaml covers this directory, so harness-kit cannot accept the change and re-running deliver will not help.",
24650
+ commands: [],
24651
+ completion: "The checks this repository documents (README / CONTRIBUTING / package scripts / CI config) pass, and the report names which ones ran."
24652
+ }
24653
+ ];
24654
+ if (nestedCommands.length) {
24655
+ nextActions2.push({
24656
+ id: "deliver-nested-harness-targets",
24657
+ priority: "required",
24658
+ owner: "agent",
24659
+ when: "before-finish",
24660
+ title: "Deliver the changed nested Harness targets",
24661
+ reason: `Changed files fall inside nested Harness targets: ${touched.join(", ")}.`,
24662
+ commands: nestedCommands,
24663
+ completion: "Each listed target reports status=accepted."
24664
+ });
24665
+ }
24666
+ return {
24667
+ ...base,
24668
+ status: "not-adopted",
24669
+ adopted: false,
24670
+ errors: [],
24671
+ next: [
24672
+ "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",
24673
+ ...nestedCommands.map((command) => `changed nested Harness target: ${command}`)
24674
+ ],
24675
+ nextActions: nextActions2
24676
+ };
24194
24677
  }
24195
24678
  function deliverCmd(repo, opts = {}) {
24679
+ const cli = repoHarnessInvocation(repo);
24680
+ const targets = locateHarnessTargets(repo);
24681
+ if (!targets.adopted) return emitReport(unadoptedReport(repo, opts, targets), opts.json, cli);
24196
24682
  const errors = [];
24197
24683
  let scope;
24198
24684
  try {
@@ -24216,15 +24702,19 @@ function deliverCmd(repo, opts = {}) {
24216
24702
  const verify = captureStdout(
24217
24703
  () => verifyCmd(repo, {
24218
24704
  recordManualEvidence: true,
24705
+ json: true,
24706
+ contextBase: scope.base,
24219
24707
  budgetMs: Number(process.env.HARNESS_KIT_DELIVER_VERIFY_BUDGET_MS) || 60 * 60 * 1e3
24220
24708
  })
24221
24709
  );
24222
24710
  const verifyPassed = verify.code === 0;
24711
+ const verifyReport = parseVerifyReport(verify.output);
24223
24712
  if (!verifyPassed) {
24224
- const tail = verify.output.trim().split("\n").filter(Boolean).slice(-8);
24225
- if (tail.length) errors.push(`verify failed: ${tail.join(" | ")}`);
24713
+ 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);
24714
+ if (failures.length) errors.push(`verify failed: ${failures.join(" | ")}`);
24226
24715
  else errors.push("verify failed");
24227
24716
  }
24717
+ const inheritedContext = (verifyReport?.context ?? []).filter((issue) => issue.inherited);
24228
24718
  let fingerprintError = "";
24229
24719
  if (runReport?.fingerprint) {
24230
24720
  try {
@@ -24244,11 +24734,25 @@ function deliverCmd(repo, opts = {}) {
24244
24734
  if (runOk && verifyPassed && stable && runReport?.status === "no-change") status = "no-change";
24245
24735
  else if (runOk && verifyPassed && stable) status = "accepted";
24246
24736
  else status = "needs-work";
24737
+ const actions = inheritedContextActions(inheritedContext, scope.base, cli);
24738
+ if (status === "needs-work") {
24739
+ actions.unshift({
24740
+ id: "fix-delivery-failures",
24741
+ priority: "required",
24742
+ owner: "agent",
24743
+ when: "before-finish",
24744
+ title: "Fix deliver failures and re-run deliver",
24745
+ reason: errors.length ? errors.slice(0, 3).join("; ") : "run-checks did not pass for this change.",
24746
+ commands: [`${cli} deliver --repo .`],
24747
+ completion: "deliver reports status=accepted (or no-change on a clean tree)."
24748
+ });
24749
+ }
24247
24750
  const stamp = inspectDeliveryStamp(repo);
24248
24751
  const report = {
24249
24752
  schema: "ai-harness/deliver-report/v1",
24250
24753
  status,
24251
24754
  ok: status === "accepted" || status === "no-change",
24755
+ adopted: true,
24252
24756
  scope: scope.kind,
24253
24757
  base: scope.base,
24254
24758
  fingerprint: runReport?.fingerprint ?? scope.changes.fingerprint,
@@ -24256,15 +24760,12 @@ function deliverCmd(repo, opts = {}) {
24256
24760
  runChecks: runReport,
24257
24761
  verifyPassed,
24258
24762
  stamp,
24763
+ inheritedContext,
24259
24764
  errors,
24260
- next: nextActions(status, runReport)
24765
+ next: nextActions(status, runReport, cli),
24766
+ nextActions: actions
24261
24767
  };
24262
- if (opts.json) {
24263
- process.stdout.write(JSON.stringify(report, null, 2) + "\n");
24264
- } else {
24265
- reportHuman2(report);
24266
- }
24267
- return report.ok ? 0 : 1;
24768
+ return emitReport(report, opts.json, cli);
24268
24769
  }
24269
24770
 
24270
24771
  // src/commands/hook-event.ts
@@ -24279,7 +24780,7 @@ function stopMode() {
24279
24780
  return raw === "execute" || raw === "thick" ? "execute" : "thin";
24280
24781
  }
24281
24782
  function readPayload() {
24282
- const raw = (0, import_node_fs16.readFileSync)(0, "utf8").trim();
24783
+ const raw = (0, import_node_fs17.readFileSync)(0, "utf8").trim();
24283
24784
  if (!raw) return {};
24284
24785
  const value = JSON.parse(raw);
24285
24786
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("hook stdin must be a JSON object");
@@ -24329,17 +24830,17 @@ function parseRunReport2(output) {
24329
24830
  return null;
24330
24831
  }
24331
24832
  }
24332
- function deliverBlockMessage(extra = "") {
24833
+ function deliverBlockMessage(cli, extra = "") {
24333
24834
  const lines = [
24334
24835
  "harness-kit: delivery is not verified; continue working before stopping.",
24335
- "Run: harness-kit deliver --repo .",
24836
+ `Run: ${cli} deliver --repo .`,
24336
24837
  "Only status=accepted (or no-change with a clean tree) may finish.",
24337
24838
  "Fix failures from deliver, then finish again."
24338
24839
  ];
24339
24840
  if (extra.trim()) lines.splice(1, 0, extra.trim());
24340
24841
  return lines.join("\n");
24341
24842
  }
24342
- function failureMessage(report, verifyOutput, token) {
24843
+ function failureMessage(report, verifyOutput, token, cli) {
24343
24844
  const lines = ["harness-kit: delivery is not verified; continue working before stopping."];
24344
24845
  if (!report) lines.push("run-checks did not return valid evidence.");
24345
24846
  else {
@@ -24362,36 +24863,56 @@ function failureMessage(report, verifyOutput, token) {
24362
24863
  const actionable = outputLines.filter((line) => /\bERR\b|timed out|budget exhausted|verify: FAILED/.test(line));
24363
24864
  lines.push(`- verify: ${(actionable.length ? actionable.slice(-8) : outputLines.slice(-8)).join(" | ")}`);
24364
24865
  }
24365
- lines.push("Prefer: harness-kit deliver --repo . (then finish again)");
24866
+ lines.push(`Prefer: ${cli} deliver --repo . (then finish again)`);
24366
24867
  lines.push(
24367
- `For a genuine non-goal coverage gap only: harness-kit run-checks --repo . --session ${token} --waive <kind> --where <scope> --reason "<why>"`
24868
+ `For a genuine non-goal coverage gap only: ${cli} run-checks --repo . --session ${token} --waive <kind> --where <scope> --reason "<why>"`
24368
24869
  );
24369
24870
  return lines.join("\n");
24370
24871
  }
24371
- function thinStop(repo, agent) {
24872
+ function observeStop(repo, token, observation, evidence) {
24873
+ try {
24874
+ recordStopObservation(repo, token, { at: (/* @__PURE__ */ new Date()).toISOString(), ...observation }, evidence);
24875
+ } catch {
24876
+ }
24877
+ }
24878
+ function thinStop(repo, agent, id) {
24879
+ const cli = repoHarnessInvocation(repo);
24880
+ const token = validationSessionToken(agent, id);
24372
24881
  let scope;
24373
24882
  try {
24374
24883
  scope = resolveChangeScope(repo);
24375
24884
  } catch (error) {
24376
- return block(agent, "stop", deliverBlockMessage(`cannot resolve changes: ${error.message}`));
24885
+ observeStop(repo, token, { mode: "thin", decision: "block", reason: "scope-error" }, null);
24886
+ return block(agent, "stop", deliverBlockMessage(cli, `cannot resolve changes: ${error.message}`));
24377
24887
  }
24378
- if (scope.changes.files.length === 0) return allow(agent);
24379
- if (stampCoversScope(repo, scope)) return allow(agent);
24888
+ const fingerprint2 = scope.changes.fingerprint;
24889
+ if (scope.changes.files.length === 0) {
24890
+ observeStop(repo, token, { mode: "thin", decision: "allow", reason: "clean", fingerprint: fingerprint2 }, null);
24891
+ return allow(agent);
24892
+ }
24893
+ const stamp = coveringStampEvidence(repo, scope);
24894
+ if (stamp) {
24895
+ observeStop(repo, token, { mode: "thin", decision: "allow", reason: "stamp", fingerprint: fingerprint2 }, { ...stamp, source: "deliver-stamp" });
24896
+ return allow(agent);
24897
+ }
24898
+ observeStop(repo, token, { mode: "thin", decision: "block", reason: "no-stamp", fingerprint: fingerprint2 }, null);
24380
24899
  return block(
24381
24900
  agent,
24382
24901
  "stop",
24383
24902
  deliverBlockMessage(
24903
+ cli,
24384
24904
  `scope=${scope.kind} base=${scope.base} changed=${scope.changes.files.length} file(s); no matching accepted delivery stamp.`
24385
24905
  )
24386
24906
  );
24387
24907
  }
24388
24908
  function executeStop(repo, agent, id) {
24909
+ const cli = repoHarnessInvocation(repo);
24389
24910
  const token = validationSessionToken(agent, id);
24390
24911
  let session;
24391
24912
  try {
24392
24913
  session = readValidationSession(repo, token);
24393
24914
  } catch (error) {
24394
- return block(agent, "stop", deliverBlockMessage(`validation session unreadable: ${error.message}`));
24915
+ return block(agent, "stop", deliverBlockMessage(cli, `validation session unreadable: ${error.message}`));
24395
24916
  }
24396
24917
  if (!session) {
24397
24918
  const delivered = captureStdout2(() => deliverCmd(repo, { json: true }));
@@ -24403,7 +24924,7 @@ function executeStop(repo, agent, id) {
24403
24924
  } catch {
24404
24925
  detail = delivered.output.trim().slice(0, 500);
24405
24926
  }
24406
- return block(agent, "stop", deliverBlockMessage(detail));
24927
+ return block(agent, "stop", deliverBlockMessage(cli, detail));
24407
24928
  }
24408
24929
  if (session.hookConfigFingerprint && agentHookConfigurationFingerprint(repo, agent) !== session.hookConfigFingerprint) {
24409
24930
  const delivered = captureStdout2(() => deliverCmd(repo, { json: true }));
@@ -24412,6 +24933,7 @@ function executeStop(repo, agent, id) {
24412
24933
  agent,
24413
24934
  "stop",
24414
24935
  deliverBlockMessage(
24936
+ cli,
24415
24937
  "project hook configuration changed after SessionStart; lifecycle proof was discarded. Run deliver to re-accept the current change."
24416
24938
  )
24417
24939
  );
@@ -24419,11 +24941,17 @@ function executeStop(repo, agent, id) {
24419
24941
  try {
24420
24942
  clearValidationEvidence(repo, session);
24421
24943
  } catch (error) {
24422
- return block(agent, "stop", deliverBlockMessage(`could not start a fresh validation attempt: ${error.message}`));
24944
+ return block(agent, "stop", deliverBlockMessage(cli, `could not start a fresh validation attempt: ${error.message}`));
24423
24945
  }
24424
24946
  const run = captureStdout2(() => runChecksCmd(repo, { session: token, json: true, budgetMs: 0 }));
24425
24947
  const report = parseRunReport2(run.output);
24426
- const verify = captureStdout2(() => verifyCmd(repo, { budgetMs: hookVerifyBudgetMs(), recordManualEvidence: false }));
24948
+ const verify = captureStdout2(
24949
+ () => verifyCmd(repo, {
24950
+ budgetMs: hookVerifyBudgetMs(),
24951
+ recordManualEvidence: false,
24952
+ ...session.baseSha ? { contextBase: session.baseSha } : {}
24953
+ })
24954
+ );
24427
24955
  let finalFingerprintError = "";
24428
24956
  if (report?.fingerprint) {
24429
24957
  try {
@@ -24439,15 +24967,22 @@ function executeStop(repo, agent, id) {
24439
24967
  try {
24440
24968
  evidencePersisted = markLatestVerifyResult(repo, token, verifyPassed, report?.fingerprint, report?.planFingerprint);
24441
24969
  } catch (error) {
24442
- return block(agent, "stop", deliverBlockMessage(`could not persist verify result: ${error.message}`));
24443
- }
24444
- if (run.code === 0 && report?.ok && verifyPassed && evidencePersisted) return allow(agent);
24970
+ return block(agent, "stop", deliverBlockMessage(cli, `could not persist verify result: ${error.message}`));
24971
+ }
24972
+ const passed = run.code === 0 && !!report?.ok && verifyPassed && evidencePersisted;
24973
+ observeStop(repo, token, {
24974
+ mode: "execute",
24975
+ decision: passed ? "allow" : "block",
24976
+ reason: "checks",
24977
+ ...report?.fingerprint ? { fingerprint: report.fingerprint } : {}
24978
+ });
24979
+ if (passed) return allow(agent);
24445
24980
  const verifyDetails = [
24446
24981
  verify.code === 0 ? "" : verify.output.trim(),
24447
24982
  finalFingerprintError,
24448
24983
  evidencePersisted ? "" : "matching final evidence was not persisted; refusing to allow Stop"
24449
24984
  ].filter(Boolean).join("\n");
24450
- return block(agent, "stop", failureMessage(report, verifyDetails, token));
24985
+ return block(agent, "stop", failureMessage(report, verifyDetails, token, cli));
24451
24986
  }
24452
24987
  function hookEventCmd(repoInput, opts) {
24453
24988
  let payload;
@@ -24494,14 +25029,14 @@ function hookEventCmd(repoInput, opts) {
24494
25029
  }
24495
25030
  }
24496
25031
  if (opts.agent === "cursor" && ["aborted", "error"].includes(payload.status ?? "")) return allow(opts.agent);
24497
- if (stopMode() === "thin") return thinStop(repo, opts.agent);
25032
+ if (stopMode() === "thin") return thinStop(repo, opts.agent, id);
24498
25033
  return executeStop(repo, opts.agent, id);
24499
25034
  }
24500
25035
 
24501
25036
  // src/commands/install-hooks.ts
24502
25037
  var import_node_child_process7 = require("node:child_process");
24503
- var import_node_fs17 = require("node:fs");
24504
- var import_node_path16 = require("node:path");
25038
+ var import_node_fs18 = require("node:fs");
25039
+ var import_node_path18 = require("node:path");
24505
25040
  var MARK = "harness-kit-managed-hook";
24506
25041
  function git2(repo, args) {
24507
25042
  const result = (0, import_node_child_process7.spawnSync)("git", args, { cwd: repo, encoding: "utf8" });
@@ -24543,9 +25078,9 @@ function inspectGitHookScope(repo) {
24543
25078
  }
24544
25079
  ];
24545
25080
  });
24546
- const hooksDir = (0, import_node_path16.resolve)(repo, hooks.stdout.trim());
24547
- const commonDir = (0, import_node_path16.resolve)(repo, common.stdout.trim());
24548
- const gitDir = (0, import_node_path16.resolve)(repo, current.stdout.trim());
25081
+ const hooksDir = (0, import_node_path18.resolve)(repo, hooks.stdout.trim());
25082
+ const commonDir = (0, import_node_path18.resolve)(repo, common.stdout.trim());
25083
+ const gitDir = (0, import_node_path18.resolve)(repo, current.stdout.trim());
24549
25084
  return {
24550
25085
  scope: {
24551
25086
  hooksDir,
@@ -24554,21 +25089,21 @@ function inspectGitHookScope(repo) {
24554
25089
  worktrees,
24555
25090
  hooksPathConfigs,
24556
25091
  hooksPathConfigRaw,
24557
- defaultHooksDirMatches: hooksDir === (0, import_node_path16.join)(commonDir, "hooks")
25092
+ defaultHooksDirMatches: hooksDir === (0, import_node_path18.join)(commonDir, "hooks")
24558
25093
  }
24559
25094
  };
24560
25095
  }
24561
25096
  function hookOwnership(path) {
24562
25097
  try {
24563
- if (!(0, import_node_fs17.lstatSync)(path).isFile()) return "foreign";
24564
- return (0, import_node_fs17.readFileSync)(path, "utf8").includes(MARK) ? "managed" : "foreign";
25098
+ if (!(0, import_node_fs18.lstatSync)(path).isFile()) return "foreign";
25099
+ return (0, import_node_fs18.readFileSync)(path, "utf8").includes(MARK) ? "managed" : "foreign";
24565
25100
  } catch (error) {
24566
25101
  return error.code === "ENOENT" ? "missing" : "foreign";
24567
25102
  }
24568
25103
  }
24569
25104
  function hooksPathReason(scope) {
24570
25105
  if (!scope.hooksPathConfigRaw.length) {
24571
- return scope.defaultHooksDirMatches ? null : `resolved hooks directory does not match ${(0, import_node_path16.join)(scope.commonDir, "hooks")}; core.hooksPath origin is ambiguous`;
25106
+ return scope.defaultHooksDirMatches ? null : `resolved hooks directory does not match ${(0, import_node_path18.join)(scope.commonDir, "hooks")}; core.hooksPath origin is ambiguous`;
24572
25107
  }
24573
25108
  if (scope.hooksPathConfigs.length !== 1 || scope.hooksPathConfigRaw.length !== 1) {
24574
25109
  return `core.hooksPath is ambiguous: ${scope.hooksPathConfigRaw.join("; ")}`;
@@ -24619,7 +25154,7 @@ function installGitHooks(repo, force, allowSharedGitHooks) {
24619
25154
  ["pre-commit", preCommit()],
24620
25155
  ["pre-push", prePush()]
24621
25156
  ];
24622
- const ownership = new Map(targets.map(([name]) => [name, hookOwnership((0, import_node_path16.join)(scope.hooksDir, name))]));
25157
+ const ownership = new Map(targets.map(([name]) => [name, hookOwnership((0, import_node_path18.join)(scope.hooksDir, name))]));
24623
25158
  const reasons = [];
24624
25159
  const configuredPathReason = hooksPathReason(scope);
24625
25160
  if (configuredPathReason) reasons.push(configuredPathReason);
@@ -24642,10 +25177,10 @@ function installGitHooks(repo, force, allowSharedGitHooks) {
24642
25177
  );
24643
25178
  }
24644
25179
  for (const [name, body] of targets) {
24645
- const p = (0, import_node_path16.join)(scope.hooksDir, name);
25180
+ const p = (0, import_node_path18.join)(scope.hooksDir, name);
24646
25181
  const wasManaged = ownership.get(name) === "managed";
24647
25182
  writeText(p, body);
24648
- (0, import_node_fs17.chmodSync)(p, 493);
25183
+ (0, import_node_fs18.chmodSync)(p, 493);
24649
25184
  ok(`${wasManaged ? force ? "refreshed" : "updated" : "installed"} ${name}`);
24650
25185
  }
24651
25186
  info(`
@@ -24676,7 +25211,9 @@ var SKILL_REL2 = "skills/erzhe-harness-init/SKILL.md";
24676
25211
  var META2 = `<!-- harness-kit onboard -->
24677
25212
  You are an AI agent onboarding the CURRENT repository to harness-kit.
24678
25213
  Follow the skill below verbatim. Run every harness-kit command through
24679
- \`npx -y @erzhe/harness-kit@latest <cmd>\` \u2014 always the latest version, no global install.
25214
+ \`${harnessInvocation(package_default.version)} <cmd>\` \u2014 the exact version printing this skill,
25215
+ no global install. \`init\` records it in .agents/harness.lock.json. If the repository
25216
+ already has that lock, use the version it pins instead and never mix versions.
24680
25217
  Do not fabricate: confirm uncertain fields with the user, and report honest GAPS.
24681
25218
 
24682
25219
  ---
@@ -24758,10 +25295,10 @@ function recordContextReviewCmd(repo, opts) {
24758
25295
  }
24759
25296
 
24760
25297
  // src/commands/prepare-adoption.ts
24761
- var import_node_path17 = require("node:path");
25298
+ var import_node_path19 = require("node:path");
24762
25299
  function prepareAdoptionCmd(repo, opts) {
24763
25300
  if (!opts.output?.trim()) throw new Error("candidate output directory is required");
24764
- const output = (0, import_node_path17.resolve)(opts.output);
25301
+ const output = (0, import_node_path19.resolve)(opts.output);
24765
25302
  const candidate = prepareAdoptionCandidate(repo, output);
24766
25303
  const result = {
24767
25304
  ok: true,
@@ -24771,23 +25308,27 @@ function prepareAdoptionCmd(repo, opts) {
24771
25308
  assurance: candidate.assurance,
24772
25309
  independence: candidate.independence,
24773
25310
  legacyEvidenceCount: candidate.legacy.length,
25311
+ landingEvidenceCount: candidate.landing.length,
24774
25312
  targetCount: candidate.targets.length
24775
25313
  };
24776
25314
  if (opts.json) process.stdout.write(JSON.stringify(result) + "\n");
24777
- else ok(`prepared adoption candidate ${candidate.candidateHash} at ${output}`);
25315
+ else {
25316
+ ok(`prepared adoption candidate ${candidate.candidateHash} at ${output}`);
25317
+ ok(`bundle: ${candidate.legacy.length} legacy, ${candidate.guidance.length} guidance, ${candidate.landing.length} landing, ${candidate.targets.length} generated`);
25318
+ }
24778
25319
  return 0;
24779
25320
  }
24780
25321
 
24781
25322
  // src/commands/record-adoption-audit.ts
24782
- var import_node_path18 = require("node:path");
25323
+ var import_node_path20 = require("node:path");
24783
25324
  function recordAdoptionAuditCmd(repo, opts) {
24784
25325
  if (!opts.candidate?.trim()) throw new Error("candidate directory is required");
24785
25326
  if (!opts.report?.trim()) throw new Error("audit report path is required");
24786
- const recorded = recordAdoptionAudit(repo, (0, import_node_path18.resolve)(opts.candidate), {
25327
+ const recorded = recordAdoptionAudit(repo, (0, import_node_path20.resolve)(opts.candidate), {
24787
25328
  verdict: opts.verdict,
24788
25329
  reason: opts.reason,
24789
- reportPath: (0, import_node_path18.resolve)(opts.report),
24790
- receiptPath: opts.receipt ? (0, import_node_path18.resolve)(opts.receipt) : void 0
25330
+ reportPath: (0, import_node_path20.resolve)(opts.report),
25331
+ receiptPath: opts.receipt ? (0, import_node_path20.resolve)(opts.receipt) : void 0
24791
25332
  });
24792
25333
  const result = {
24793
25334
  ok: true,
@@ -24905,7 +25446,7 @@ function taskStartCmd(repo, opts = {}) {
24905
25446
  } else {
24906
25447
  ok(`task started at base ${record.baseSha}`);
24907
25448
  if (record.note) info(`note: ${record.note}`);
24908
- info("run harness-kit deliver when ready to accept this task's changes");
25449
+ info(`run ${repoHarnessInvocation(repo)} deliver when ready to accept this task's changes`);
24909
25450
  }
24910
25451
  return 0;
24911
25452
  } catch (error) {
@@ -24921,7 +25462,7 @@ function taskStatusCmd(repo, opts = {}) {
24921
25462
  }
24922
25463
  if (!record) {
24923
25464
  err("no active task record for this worktree");
24924
- info("run: harness-kit task start --repo .");
25465
+ info(`run: ${repoHarnessInvocation(repo)} task-start --repo .`);
24925
25466
  info("without a task base, deliver falls back to worktree diff vs HEAD");
24926
25467
  return 1;
24927
25468
  }
@@ -24943,7 +25484,7 @@ function guard(fn) {
24943
25484
  }
24944
25485
  var program2 = new Command();
24945
25486
  program2.name("harness-kit").description("AI-friendly repo harness").version(package_default.version);
24946
- var repoOf = (o) => (0, import_node_path19.resolve)(o.repo ?? process.cwd());
25487
+ var repoOf = (o) => (0, import_node_path21.resolve)(o.repo ?? process.cwd());
24947
25488
  function agentList(value) {
24948
25489
  const agents = value.split(",").map((item) => item.trim()).filter(Boolean);
24949
25490
  const invalid = agents.filter((agent) => !ALL_AGENTS.includes(agent));
@@ -25014,7 +25555,7 @@ program2.command("record-context-review").description("record an Agent's complet
25014
25555
  )
25015
25556
  );
25016
25557
  program2.command("accept-contract").description("record current contract fingerprint(s) as the accepted baseline (after an intended change)").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--id <id>", "only this contract (default: all with a snapshot command)").action((o) => guard(() => acceptContractCmd(repoOf(o), o.id)));
25017
- program2.command("install-hooks").description("install git hooks and/or agent SessionStart + Stop hooks (run-checks + verify gate)").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--git", "install git hooks (default when no selector given)").option("--stop", "install agent SessionStart + Stop hooks (Claude Code / Cursor / Codex)").option("--agents <list>", "comma list of agent tools for --stop: claude,cursor,codex (default: all)").option("--force", "refresh harness-kit-managed hooks; never overwrite foreign hooks", false).option("--allow-shared-git-hooks", "acknowledge native hooks affect every linked worktree", false).option(
25558
+ program2.command("install-hooks").description("install git hooks and/or agent SessionStart + Stop hooks (Stop requires an accepted deliver stamp)").option("-C, --repo <dir>", "target repo dir (default: current directory)").option("--git", "install git hooks (default when no selector given)").option("--stop", "install agent SessionStart + Stop hooks (Claude Code / Cursor / Codex)").option("--agents <list>", "comma list of agent tools for --stop: claude,cursor,codex (default: all)").option("--force", "refresh harness-kit-managed hooks; never overwrite foreign hooks", false).option("--allow-shared-git-hooks", "acknowledge native hooks affect every linked worktree", false).option(
25018
25559
  "--allow-user-dispatcher",
25019
25560
  "allow the safe CODEX_HOME dispatcher required by Codex in linked worktrees",
25020
25561
  false
@@ -25030,7 +25571,7 @@ program2.command("install-hooks").description("install git hooks and/or agent Se
25030
25571
  })
25031
25572
  )
25032
25573
  );
25033
- program2.command("onboard").description("print the erzhe-harness-init skill for an agent to follow (use via npx, always latest)").action(() => guard(() => onboardCmd()));
25574
+ program2.command("onboard").description("print the erzhe-harness-init skill for an agent to follow (pins this exact version)").action(() => guard(() => onboardCmd()));
25034
25575
  program2.command("check-loop").description("print the harness-check-loop skill: the implement -> verify loop for an agent").action(() => guard(() => checkLoopCmd()));
25035
25576
  program2.command("hook-event", { hidden: true }).description("internal lifecycle hook adapter").requiredOption("-C, --repo <dir>", "target repo dir").requiredOption("--agent <agent>", "claude, cursor, or codex").requiredOption("--event <event>", "session-start or stop").action(
25036
25577
  (o) => guard(() => {