@mrciphersmith/keryx 0.4.11 → 0.4.13

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.
package/dist/core.js CHANGED
@@ -2187,8 +2187,51 @@ function hasPhoneSeparatorShape(value) {
2187
2187
  return /^\(?\d{2,4}\)?(?:[-.]\d{2,4})*$/.test(group);
2188
2188
  });
2189
2189
  }
2190
- function scanWith(content, rule, scanner, validate, accept) {
2190
+ function timestampSpans(content) {
2191
+ const spans = [];
2192
+ const extended = /^(\d{4})-(\d{2})-(\d{2})T(\d{2})(:)(\d{2})\5(\d{2})(?:([.,])(\d{1,9}))?(Z|[+-]\d{2}(?::?\d{2})?)?/;
2193
+ const filename = /^(\d{4})-(\d{2})-(\d{2})T(\d{2})(-)(\d{2})\5(\d{2})(?:([.,]|-(?!\d{2}:))(\d{1,9}))?(Z|[+-]\d{2}(?::?\d{2})?)?/;
2194
+ const compact = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:[.,](\d{1,9}))?(Z)?/;
2195
+ for (let start = 0;start < content.length; start += 1) {
2196
+ if (!/[0-9]/.test(content[start] ?? "") || /[0-9]/.test(content[start - 1] ?? ""))
2197
+ continue;
2198
+ const sample = content.slice(start, start + 64);
2199
+ const separated = (sample[13] === ":" ? extended : filename).exec(sample);
2200
+ const match = separated ?? compact.exec(sample);
2201
+ if (match === null)
2202
+ continue;
2203
+ const year = Number(match[1]);
2204
+ const month = Number(match[2]);
2205
+ const day = Number(match[3]);
2206
+ const hour = Number(match[4]);
2207
+ const minute = Number(match[separated === null ? 5 : 6]);
2208
+ const second = Number(match[separated === null ? 6 : 7]);
2209
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
2210
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
2211
+ if (year === 0 || month < 1 || month > 12 || day < 1 || day > (days[month - 1] ?? 0) || hour > 23 || minute > 59 || second > 59)
2212
+ continue;
2213
+ let zone = match[separated === null ? 8 : 10] ?? "";
2214
+ if (separated?.[8] === "-" && zone === "" && (separated[9]?.length === 2 || separated[9]?.length === 4)) {
2215
+ zone = "-" + separated[9];
2216
+ }
2217
+ if (zone !== "" && zone !== "Z") {
2218
+ const digits = zone.slice(1).replace(":", "");
2219
+ if (Number(digits.slice(0, 2)) > 23 || Number(digits.slice(2) || "0") > 59)
2220
+ continue;
2221
+ }
2222
+ const end = start + match[0].length;
2223
+ const next = content[end] ?? "";
2224
+ const producer = zone === "Z" && /^-[a-fA-F0-9]{6}_[A-Za-z]/.test(content.slice(end, end + 9));
2225
+ if (/[A-Za-z0-9:+,\u0080-\uffff]/.test(next) || next === "-" && !producer || next === "." && !/^[.][A-Za-z]/.test(content.slice(end, end + 2)))
2226
+ continue;
2227
+ spans.push({ start, end });
2228
+ start = end - 1;
2229
+ }
2230
+ return spans;
2231
+ }
2232
+ function scanWith(content, rule, scanner, validate, accept, timestamps) {
2191
2233
  const matches = [];
2234
+ let timestampIndex = timestamps?.first ?? 0;
2192
2235
  scanner.reset?.();
2193
2236
  scanner.lastIndex = 0;
2194
2237
  let m;
@@ -2203,6 +2246,15 @@ function scanWith(content, rule, scanner, validate, accept) {
2203
2246
  }
2204
2247
  const start = group === 0 ? m.index : m.index + m[0].indexOf(value);
2205
2248
  const end = start + value.length;
2249
+ if (rule.policyId === "pii.phone" && timestamps !== undefined) {
2250
+ const [a, b] = timestamps.original?.(start, end) ?? [start, end];
2251
+ while (timestampIndex < timestamps.spans.length && timestamps.spans[timestampIndex].end <= a) {
2252
+ timestampIndex += 1;
2253
+ }
2254
+ const span = timestamps.spans[timestampIndex];
2255
+ if (span !== undefined && span.start <= a && b <= span.end)
2256
+ continue;
2257
+ }
2206
2258
  if (rule.accept && !rule.accept(content, start, end) || accept && !accept(content, start, end)) {
2207
2259
  if (m.index === scanner.lastIndex) {
2208
2260
  scanner.lastIndex += 1;
@@ -2230,14 +2282,14 @@ function scanWith(content, rule, scanner, validate, accept) {
2230
2282
  }
2231
2283
  return matches;
2232
2284
  }
2233
- function scanRule(content, rule) {
2234
- const matches = scanWith(content, rule, rule.regex, rule.validate, undefined);
2285
+ function scanRule(content, rule, timestamps) {
2286
+ const matches = scanWith(content, rule, rule.regex, rule.validate, undefined, timestamps);
2235
2287
  if (rule.also === undefined) {
2236
2288
  return matches;
2237
2289
  }
2238
2290
  let result = matches;
2239
2291
  for (const extra of rule.also) {
2240
- const found = scanWith(content, rule, extra.regex, extra.validate ?? rule.validate, extra.accept);
2292
+ const found = scanWith(content, rule, extra.regex, extra.validate ?? rule.validate, extra.accept, timestamps);
2241
2293
  const added = found.filter((match) => !containedIn(result, match.start, match.end));
2242
2294
  if (added.length > 0) {
2243
2295
  result = coalesce(content, [...result, ...added].sort((x, y) => x.start - y.start || y.end - x.end));
@@ -2245,8 +2297,8 @@ function scanRule(content, rule) {
2245
2297
  }
2246
2298
  return result;
2247
2299
  }
2248
- function scanRules(content) {
2249
- return RULES.map((rule) => scanRule(content, rule));
2300
+ function scanRules(content, timestamps) {
2301
+ return RULES.map((rule) => scanRule(content, rule, timestamps));
2250
2302
  }
2251
2303
  function decimalDigitValue(codePoint) {
2252
2304
  if (codePoint < 1632) {
@@ -2449,7 +2501,8 @@ function viewsOf(content, nonAscii) {
2449
2501
  return views;
2450
2502
  }
2451
2503
  function detectPii(content) {
2452
- const perRule = scanRules(content);
2504
+ const spans = timestampSpans(content);
2505
+ const perRule = scanRules(content, { spans, first: 0 });
2453
2506
  const nonAscii = NON_ASCII.test(content);
2454
2507
  if (nonAscii) {
2455
2508
  const emailRule = RULES[0];
@@ -2462,6 +2515,7 @@ function detectPii(content) {
2462
2515
  }
2463
2516
  const views = viewsOf(content, nonAscii);
2464
2517
  for (const options of views) {
2518
+ let timestampFirst = 0;
2465
2519
  for (let from = 0;from < content.length; ) {
2466
2520
  let start = from;
2467
2521
  let to = Math.min(content.length, from + NORMALIZE_CHUNK);
@@ -2473,7 +2527,14 @@ function detectPii(content) {
2473
2527
  }
2474
2528
  const window = normalizeWindow(content, start, to, options);
2475
2529
  if (window !== null) {
2476
- const extra = scanRules(window.text);
2530
+ while (timestampFirst < spans.length && spans[timestampFirst].end <= start) {
2531
+ timestampFirst += 1;
2532
+ }
2533
+ const extra = scanRules(window.text, {
2534
+ spans,
2535
+ first: timestampFirst,
2536
+ original: (a, b) => toOriginal(window, content, a, b)
2537
+ });
2477
2538
  extra.forEach((found, index) => {
2478
2539
  if (options.breaks && !NUMBER_RULES.has(index)) {
2479
2540
  return;
@@ -7862,7 +7923,7 @@ var init_credential_shape = __esm(() => {
7862
7923
  "CODEX_HOME",
7863
7924
  "CLAUDECODE"
7864
7925
  ];
7865
- EXTERNAL_ENV_PREFIX_SWEEPS = ["CLAUDE_CODE_", "KERYX_"];
7926
+ EXTERNAL_ENV_PREFIX_SWEEPS = ["CLAUDE_CODE_", "KERYX_", "HC_", "HERDR_"];
7866
7927
  MCP_ENV_ALLOW_EXACT = ["PWD", "OLDPWD"];
7867
7928
  MCP_ENV_DENY = [
7868
7929
  "SSH_AUTH_SOCK",
@@ -14477,7 +14538,7 @@ var CATASTROPHIC_TARGETS, RECURSIVE_FLAG, PRIVILEGE, INTERPRETERS, DOWNLOADERS,
14477
14538
  return false;
14478
14539
  const operands = git.args.filter((w) => !w.startsWith("-"));
14479
14540
  return operands.some((w, i) => i + 1 < operands.length && configWriteArmsPush(gitConfigEntry(`${w}=${operands[i + 1]}`, false)));
14480
- }, RULES3, ASSIGNING_BUILTINS, CREDENTIAL_MARKERS, SYSTEMCTL_CONTROL_VERBS, SCHEDULE_VERBS, WRAPPER_COMMANDS, WRAPPER_FLAGS_WITH_VALUE, SHELLS, KERYX_ENTRY_NAMES, JS_RUNNERS, TERMINAL_DRIVERS, ANSI_C_ESCAPES, OPERATOR_REVIEW_VERBS, UNATTENDED_REVIEW_VERBS, HUB_MACHINE_OPERATOR_VERBS, OPERATOR_COMMAND_PATHS, MAX_COMMAND_PATH, OPERATOR_PATH_WORDS;
14541
+ }, RULES3, ASSIGNING_BUILTINS, CREDENTIAL_MARKERS, SYSTEMCTL_CONTROL_VERBS, SCHEDULE_VERBS, WRAPPER_COMMANDS, WRAPPER_FLAGS_WITH_VALUE, SHELLS, KERYX_ENTRY_NAMES, JS_RUNNERS, TERMINAL_DRIVERS, HC_LAUNCHABLE_AGENTS, HC_AGENT_PACKAGES, HC_LAUNCH_RUNNERS, RUNNER_VERBS, HC_PROGRAM_VERBS, HC_RUN_VALUE_OPTIONS, ANSI_C_ESCAPES, OPERATOR_REVIEW_VERBS, UNATTENDED_REVIEW_VERBS, HUB_MACHINE_OPERATOR_VERBS, OPERATOR_COMMAND_PATHS, MAX_COMMAND_PATH, OPERATOR_PATH_WORDS;
14481
14542
  var init_command_risk = __esm(() => {
14482
14543
  init_args();
14483
14544
  init_shell_syntax();
@@ -14842,6 +14903,16 @@ var init_command_risk = __esm(() => {
14842
14903
  KERYX_ENTRY_NAMES = new Set(["keryx", "cli.ts", "cli.js"]);
14843
14904
  JS_RUNNERS = new Set(["bun", "bunx", "node", "npx", "pnpx", "tsx", "deno"]);
14844
14905
  TERMINAL_DRIVERS = new Set(["script", "screen", "tmux", "unbuffer", "dtach", "abduco", "expect", "socat", "zpty"]);
14906
+ HC_LAUNCHABLE_AGENTS = new Set(["keryx", "claude", "codex", "opencode", "gemini", "agy"]);
14907
+ HC_AGENT_PACKAGES = new Map([
14908
+ ["claude-code", "claude"],
14909
+ ["gemini-cli", "gemini"],
14910
+ ["opencode-ai", "opencode"]
14911
+ ]);
14912
+ HC_LAUNCH_RUNNERS = new Set([...JS_RUNNERS, "npm", "pnpm", "yarn"]);
14913
+ RUNNER_VERBS = new Set(["run", "x", "exec", "dlx"]);
14914
+ HC_PROGRAM_VERBS = new Set(["run", "exec"]);
14915
+ HC_RUN_VALUE_OPTIONS = new Set(["--name", "--cwd", "--on", "--label", "--parent", "--timeout"]);
14845
14916
  ANSI_C_ESCAPES = { n: `
14846
14917
  `, t: "\t", r: "\r", a: "\x07", b: "\b", e: "\x1B", E: "\x1B", f: "\f", v: "\v", "\\": "\\", "'": "'", '"': '"', "?": "?" };
14847
14918
  OPERATOR_REVIEW_VERBS = new Set(["waive-mutation", "override-reviewers", "confirm-plan", "decide-premise"]);
@@ -27409,6 +27480,7 @@ __export(exports_service2, {
27409
27480
  buildAcKindReport: () => buildAcKindReport,
27410
27481
  classifyAcCriterionNotCheckable: () => classifyAcCriterionNotCheckable,
27411
27482
  classifyNotCheckable: () => classifyNotCheckable,
27483
+ completionExceptionQuestion: () => completionExceptionQuestion,
27412
27484
  completionFixHint: () => completionFixHint,
27413
27485
  completionTarget: () => completionTarget,
27414
27486
  computeAcFacts: () => computeAcFacts,
@@ -27423,6 +27495,7 @@ __export(exports_service2, {
27423
27495
  flowDeliveryStatementFrom: () => flowDeliveryStatementFrom,
27424
27496
  flowStatementFrom: () => flowStatementFrom,
27425
27497
  flowsRoot: () => flowsRoot,
27498
+ formatCompletionException: () => formatCompletionException,
27426
27499
  freezePrecondition: () => freezePrecondition,
27427
27500
  githubAdapter: () => githubAdapter,
27428
27501
  githubPostReview: () => githubPostReview,
@@ -27454,6 +27527,7 @@ __export(exports_service2, {
27454
27527
  resolveFlowDir: () => resolveFlowDir,
27455
27528
  resolveOrigin: () => resolveOrigin,
27456
27529
  sectionOf: () => sectionOf,
27530
+ selectCompletionExceptions: () => selectCompletionExceptions,
27457
27531
  selectMatchedHunks: () => selectMatchedHunks,
27458
27532
  statementFrom: () => statementFrom,
27459
27533
  statusLabel: () => statusLabel,
@@ -27602,6 +27676,62 @@ __export(exports_service10, {
27602
27676
  runValidate: () => runValidate
27603
27677
  });
27604
27678
 
27679
+ // src/flow/completion-exceptions.ts
27680
+ function formatCompletionException(item) {
27681
+ return `${item.gate}${item.condition ? `:${item.condition}` : ""}: ${item.detail}; reason: ${item.reason}`;
27682
+ }
27683
+ var ACCEPTABLE = new Set([
27684
+ "pull-request",
27685
+ "main-merge",
27686
+ "health",
27687
+ "security",
27688
+ "base-branch"
27689
+ ]);
27690
+ function failures(gates) {
27691
+ const result = new Map;
27692
+ for (const gate of gates) {
27693
+ if (gate.status !== "fail")
27694
+ continue;
27695
+ if (gate.name === "review" && gate.conditions?.length) {
27696
+ for (const condition of gate.conditions) {
27697
+ if (condition.status !== "pass") {
27698
+ result.set(`review:${condition.id}`, { ...gate, detail: condition.detail });
27699
+ }
27700
+ }
27701
+ } else {
27702
+ result.set(gate.name, gate);
27703
+ }
27704
+ }
27705
+ return result;
27706
+ }
27707
+ function selectCompletionExceptions(gates, requested, reason) {
27708
+ const failed = failures(gates);
27709
+ if (requested.length && (!reason?.trim() || [...reason].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))) {
27710
+ return { ok: false, error: "Accepted gates require a nonempty single-line --reason." };
27711
+ }
27712
+ const exceptions = [];
27713
+ for (const key of new Set(requested)) {
27714
+ const gate = failed.get(key);
27715
+ if (!gate)
27716
+ return { ok: false, error: `Gate ${key} is not currently failing.` };
27717
+ const condition = key.startsWith("review:") ? key.slice(7) : undefined;
27718
+ if (!(condition && gate.name === "review") && !ACCEPTABLE.has(gate.name)) {
27719
+ return { ok: false, error: `Gate ${key} cannot be accepted; review requires an individual condition.` };
27720
+ }
27721
+ exceptions.push({
27722
+ gate: gate.name,
27723
+ ...condition ? { condition } : {},
27724
+ detail: gate.detail,
27725
+ reason
27726
+ });
27727
+ failed.delete(key);
27728
+ }
27729
+ return { ok: true, exceptions, remaining: [...failed.keys()] };
27730
+ }
27731
+ function completionExceptionQuestion(id, selected, context) {
27732
+ return `Complete flow ${id} with exceptions? ` + selected.map(formatCompletionException).join(" ") + (context === undefined ? "" : ` Context: ${JSON.stringify(context)}`);
27733
+ }
27734
+
27605
27735
  // src/flow/service.ts
27606
27736
  init_fs();
27607
27737
  init_validator();
@@ -27804,6 +27934,11 @@ function evaluateTaskGate(tasks) {
27804
27934
  };
27805
27935
  }
27806
27936
 
27937
+ // src/review/completion-lock.ts
27938
+ import { AsyncLocalStorage } from "async_hooks";
27939
+ init_fs();
27940
+ var owners = new AsyncLocalStorage;
27941
+
27807
27942
  // src/review/coverage-complete.ts
27808
27943
  import path54 from "path";
27809
27944
 
@@ -31574,10 +31709,10 @@ function readCoverageWaiver(dispatch) {
31574
31709
  if (waiver === undefined || !text2(waiver.operatorQuote) || !text2(waiver.time))
31575
31710
  return;
31576
31711
  const files = Array.isArray(waiver.files) ? waiver.files.filter(text2) : [];
31577
- const via = waiver.confirmedVia === "tui-card" || waiver.confirmedVia === "remote-card" ? waiver.confirmedVia : undefined;
31712
+ const via = waiver.confirmedVia === "tui-card" || waiver.confirmedVia === "remote-card" || waiver.confirmedVia === "host-question" ? waiver.confirmedVia : undefined;
31578
31713
  const pressedBy = typeof waiver.pressedBy === "number" && Number.isSafeInteger(waiver.pressedBy) ? waiver.pressedBy : undefined;
31579
31714
  const pressedAt = text2(waiver.pressedAt) ? waiver.pressedAt : undefined;
31580
- return { operatorQuote: waiver.operatorQuote, time: waiver.time, files, ...via === undefined ? {} : { confirmedVia: via }, ...cardPressFields({ pressedBy, pressedAt }) };
31715
+ return { operatorQuote: waiver.operatorQuote, time: waiver.time, files, ...via === undefined ? {} : { confirmedVia: via }, ...cardPressFields({ pressedBy, pressedAt }), ...via === "host-question" && isHostQuestion(waiver.hostQuestion) ? { hostQuestion: waiver.hostQuestion } : {} };
31581
31716
  }
31582
31717
  async function computeCoverage(packageDir, options = {}) {
31583
31718
  const research = options.research ?? await readJson2(path54.join(packageDir, "research.json"));
@@ -32929,7 +33064,7 @@ async function reviewGate(input) {
32929
33064
  };
32930
33065
  }
32931
33066
  const verdict = await runReviewGate(input);
32932
- return { name: "review", status: verdict.status, detail: verdict.detail };
33067
+ return { name: "review", status: verdict.status, detail: verdict.detail, conditions: verdict.conditions };
32933
33068
  }
32934
33069
 
32935
33070
  // src/flow/outcome-author.ts
@@ -33406,7 +33541,15 @@ function flowStateSchema() {
33406
33541
  pr: {
33407
33542
  type: "object",
33408
33543
  additionalProperties: false,
33409
- properties: { url: { type: ["string", "null"] } }
33544
+ properties: {
33545
+ url: { type: ["string", "null"] },
33546
+ previous: { type: "array", items: {
33547
+ type: "object",
33548
+ additionalProperties: false,
33549
+ required: ["url", "fixOf"],
33550
+ properties: { url: { type: "string" }, fixOf: { type: "string", minLength: 1 } }
33551
+ } }
33552
+ }
33410
33553
  },
33411
33554
  merged: {
33412
33555
  type: "object",
@@ -35845,6 +35988,7 @@ function createFlowService(deps) {
35845
35988
  for (const dir of dirs) {
35846
35989
  try {
35847
35990
  const flow = await readFlow(cwd, dir);
35991
+ const completion = flow.signatures?.slice().reverse().find((signature) => signature.kind === "complete");
35848
35992
  summaries.push({
35849
35993
  id: flow.id,
35850
35994
  slug: flow.slug,
@@ -35852,7 +35996,9 @@ function createFlowService(deps) {
35852
35996
  status: flow.status,
35853
35997
  dir: `.metaproject/flows/${dir}`,
35854
35998
  tasksDone: flow.tasks.filter((task) => task.status === "done").length,
35855
- tasksTotal: flow.tasks.length
35999
+ tasksTotal: flow.tasks.length,
36000
+ ...flow.status === "done" && completion?.cleanCompletion !== undefined ? { cleanCompletion: completion.cleanCompletion } : {},
36001
+ ...flow.status === "done" && completion?.exceptions ? { exceptions: completion.exceptions } : {}
35856
36002
  });
35857
36003
  } catch {}
35858
36004
  }
@@ -36137,13 +36283,29 @@ function createFlowService(deps) {
36137
36283
  return save(cwd, dir, flow, "ac-resealed", reason);
36138
36284
  });
36139
36285
  },
36140
- async implemented({ cwd, id, prUrl }) {
36286
+ async baseSet({ cwd, id, base, reason }) {
36287
+ if (!base.trim() || !reason.trim() || /[\r\n]/.test(base + reason)) {
36288
+ throw new Error("flow base set requires --base <branch> and a non-empty single-line --reason");
36289
+ }
36290
+ return mutate(cwd, id, async ({ dir, flow }) => {
36291
+ await assertAcIntact(cwd, dir, flow);
36292
+ const previous = flow.baseBranch ?? "not set";
36293
+ flow.baseBranch = base.trim();
36294
+ return save(cwd, dir, flow, "base-set", `${previous} \u2192 ${flow.baseBranch}: ${reason.trim()}`);
36295
+ });
36296
+ },
36297
+ async implemented({ cwd, id, prUrl, fixOf }) {
36141
36298
  if (!prUrl?.trim()) {
36142
36299
  throw new Error("flow implemented requires --pr <draft PR url>");
36143
36300
  }
36144
36301
  return mutate(cwd, id, async ({ dir, flow }) => {
36145
36302
  await assertAcIntact(cwd, dir, flow);
36146
- assertTransition(flow.status, "implemented");
36303
+ const followUp = flow.status === "implemented" && Boolean(fixOf?.trim());
36304
+ if (!followUp)
36305
+ assertTransition(flow.status, "implemented");
36306
+ if (fixOf !== undefined && (!fixOf.trim() || /[\r\n]/.test(fixOf) || !flow.pr.url || flow.pr.url === prUrl)) {
36307
+ throw new Error("--fix-of requires a round reference and a different, previously recorded PR");
36308
+ }
36147
36309
  let detail = `draft PR: ${prUrl}`;
36148
36310
  if (deps.tracker && await deps.tracker.detect()) {
36149
36311
  const pr = await deps.tracker.prStatus(prUrl);
@@ -36160,6 +36322,10 @@ function createFlowService(deps) {
36160
36322
  } else {
36161
36323
  detail += " (tracker unavailable: existence not verified)";
36162
36324
  }
36325
+ if (fixOf && flow.pr.url) {
36326
+ flow.pr.previous = [...flow.pr.previous ?? [], { url: flow.pr.url, fixOf: fixOf.trim() }];
36327
+ detail += ` (fix-of: ${fixOf.trim()}; previous PR: ${flow.pr.url})`;
36328
+ }
36163
36329
  flow.pr.url = prUrl;
36164
36330
  flow.status = "implemented";
36165
36331
  return save(cwd, dir, flow, "implemented", detail);
@@ -36183,10 +36349,20 @@ function createFlowService(deps) {
36183
36349
  merge: prMergeState(evaluation.pr, evaluation.gates),
36184
36350
  gates: evaluation.gates,
36185
36351
  passed: allowed && evaluation.gates.every((gate) => gate.status !== "fail"),
36186
- confirmationRequired: flow.gates?.confirmation === true
36352
+ confirmationRequired: flow.gates?.confirmation === true,
36353
+ exceptionContext: {
36354
+ head: evaluation.evaluatedHeadCommit ?? null,
36355
+ acChecksum: flow.acChecksum,
36356
+ prUrl: flow.pr.url,
36357
+ baseBranch: flow.baseBranch ?? null,
36358
+ mergedCommit: mergedCommit ?? null
36359
+ }
36187
36360
  };
36188
36361
  },
36189
36362
  async complete({
36363
+ acceptGates = [],
36364
+ reason,
36365
+ confirmExceptions,
36190
36366
  cwd,
36191
36367
  id,
36192
36368
  comment,
@@ -36207,7 +36383,43 @@ function createFlowService(deps) {
36207
36383
  flow = await transition(cwd, dir, flow, "completing", "completing");
36208
36384
  }
36209
36385
  const { gates, confirmationToken, evaluatedHeadCommit } = await evaluateCompletionGates(cwd, dir, flow, mergedCommit ?? undefined, confirmToken);
36210
- const passed = gates.every((gate) => gate.status !== "fail");
36386
+ const exceptionContext = {
36387
+ head: evaluatedHeadCommit ?? null,
36388
+ acChecksum: flow.acChecksum,
36389
+ prUrl: flow.pr.url,
36390
+ baseBranch: flow.baseBranch ?? null,
36391
+ mergedCommit: mergedCommit ?? null
36392
+ };
36393
+ const selection = selectCompletionExceptions(gates, acceptGates, reason);
36394
+ let exceptions = [];
36395
+ let confirmationError;
36396
+ if (!selection.ok) {
36397
+ confirmationError = selection.error;
36398
+ } else if (selection.exceptions.length && !selection.remaining.length) {
36399
+ try {
36400
+ const decision = await confirmExceptions?.(structuredClone(selection.exceptions), structuredClone(exceptionContext));
36401
+ if (!decision || !/^(yes|\u0434\u0430|y)$/iu.test(decision.operatorWords.trim()) || !["host-question", "terminal", "shell-card"].includes(decision.confirmedVia)) {
36402
+ confirmationError = "Accepted exceptions require an affirmative operator decision.";
36403
+ } else if (decision.confirmedVia === "host-question" && (!decision.hostQuestion || flow.completionAttempts?.some((attempt) => attempt.exceptions?.some((item) => item.hostQuestion?.source === decision.hostQuestion?.source && item.hostQuestion?.ref === decision.hostQuestion?.ref)))) {
36404
+ confirmationError = "Host question is missing or already used; ask a fresh question.";
36405
+ } else {
36406
+ if (decision.confirmedVia === "host-question" && decision.hostQuestion?.questionText !== completionExceptionQuestion(flow.id, selection.exceptions, exceptionContext)) {
36407
+ throw new Error("Stale completion question; ask the current question with its HEAD, AC and PR context.");
36408
+ }
36409
+ const current = await evaluateCompletionGates(cwd, dir, flow, mergedCommit ?? undefined, confirmToken);
36410
+ if (current.evaluatedHeadCommit !== evaluatedHeadCommit || JSON.stringify(current.gates) !== JSON.stringify(gates)) {
36411
+ confirmationError = "Completion gates changed while the operator answered; ask again with current refusal text.";
36412
+ } else {
36413
+ exceptions = selection.exceptions.map((item) => ({ ...item, ...decision, at: now() }));
36414
+ }
36415
+ }
36416
+ } catch (error) {
36417
+ confirmationError = `Exception confirmation failed: ${error instanceof Error ? error.message : String(error)}`;
36418
+ }
36419
+ }
36420
+ if (confirmationError)
36421
+ gates.push({ name: "confirmation", status: "fail", detail: confirmationError });
36422
+ const passed = selection.ok && !selection.remaining.length && !confirmationError && (!selection.exceptions.length || exceptions.length === selection.exceptions.length);
36211
36423
  const tamperDetail = await acTamperDetail(cwd, dir, flow);
36212
36424
  const recordedGates = tamperDetail === undefined ? gates : [
36213
36425
  ...gates,
@@ -36220,7 +36432,13 @@ function createFlowService(deps) {
36220
36432
  const recordedPassed = tamperDetail === undefined && passed;
36221
36433
  flow.completionAttempts = [
36222
36434
  ...flow.completionAttempts ?? [],
36223
- { at: now(), gates: recordedGates, passed: recordedPassed, acChecksum: flow.acChecksum }
36435
+ {
36436
+ at: now(),
36437
+ gates: recordedGates,
36438
+ passed: recordedPassed,
36439
+ acChecksum: flow.acChecksum,
36440
+ ...recordedPassed ? { cleanCompletion: exceptions.length === 0, ...exceptions.length ? { exceptions } : {} } : {}
36441
+ }
36224
36442
  ];
36225
36443
  flow = await save(cwd, dir, flow, "completion-attempt-recorded", tamperDetail !== undefined ? `attempt ${flow.completionAttempts.length}: acceptance criteria tampered \u2014 ${tamperDetail}` : `attempt ${flow.completionAttempts.length}: ${recordedPassed ? "passed" : "failed"}`);
36226
36444
  await deps.afterAttemptRecorded?.(cwd, dir);
@@ -36248,7 +36466,7 @@ function createFlowService(deps) {
36248
36466
  flow = await returnToInProgress(cwd, dir, flow, "completion-failed", `acceptance-criteria: ${lateTamper}`);
36249
36467
  return { flow, gates: lateGates, passed: false, issueComment, commented };
36250
36468
  }
36251
- if (mergedCommit) {
36469
+ if (mergedCommit && recordedGates.some((gate) => gate.name === "main-merge" && gate.status === "pass")) {
36252
36470
  flow.merged = { commit: mergedCommit, ref: "origin/main", at: now() };
36253
36471
  }
36254
36472
  const confirmation = confirmationToken !== undefined ? await consumeConfirmationToken(cwd, dir, confirmationToken, deps.now()) : undefined;
@@ -36258,6 +36476,8 @@ function createFlowService(deps) {
36258
36476
  {
36259
36477
  at: now(),
36260
36478
  kind: "complete",
36479
+ cleanCompletion: exceptions.length === 0,
36480
+ ...exceptions.length ? { exceptions } : {},
36261
36481
  identity: completionIdentity,
36262
36482
  acChecksum: flow.acChecksum,
36263
36483
  ...evaluatedHeadCommit ? { headCommit: evaluatedHeadCommit } : {},
@@ -36267,7 +36487,7 @@ function createFlowService(deps) {
36267
36487
  const warnNote = healthWarnNote(recordedGates);
36268
36488
  assertTransition(flow.status, "done");
36269
36489
  flow.status = "done";
36270
- flow = await save(cwd, dir, flow, "done", warnNote ? `all gates passed (${warnNote})` : "all gates passed");
36490
+ flow = await save(cwd, dir, flow, "done", exceptions.length ? `completed with exceptions: ${exceptions.map((item) => `${item.gate}${item.condition ? `:${item.condition}` : ""}: ${item.detail}; reason: ${item.reason}; operator: ${item.operatorWords}`).join(" | ")}` : warnNote ? `all gates passed (${warnNote})` : "all gates passed");
36271
36491
  issueComment = buildIssueComment(flow, recordedGates);
36272
36492
  if (comment && flow.source.type === "github-issue" && flow.source.ref && deps.tracker) {
36273
36493
  const ref = deps.tracker.parseRef(flow.source.ref);
@@ -36727,7 +36947,8 @@ function buildIssueComment(flow, gates) {
36727
36947
  const warnNote = healthWarnNote(gates);
36728
36948
  const gateLine = gates.map((gate) => gate.name === "health" && warnNote ? warnNote : `${gate.name}: ${gate.status}`).join(", ");
36729
36949
  return [
36730
- `Flow ${flow.id} (${flow.title}) is complete.`,
36950
+ `Flow ${flow.id} (${flow.title}) is complete${flow.signatures?.at(-1)?.cleanCompletion === false ? " with exceptions" : ""}.`,
36951
+ ...(flow.signatures?.at(-1)?.exceptions ?? []).map((item) => `- Accepted exception: ${formatCompletionException(item)}; operator: ${item.operatorWords}`),
36731
36952
  "",
36732
36953
  `- Draft PR: ${flow.pr.url ?? "n/a"}`,
36733
36954
  ...flow.merged ? [`- Main merge: ${flow.merged.commit} contained in ${flow.merged.ref}`] : [],
@@ -48626,6 +48847,12 @@ var HELP_GROUPS = [
48626
48847
  group: "External agents, ACP and MCP",
48627
48848
  summary: "Agent bus: list peers and leases, read the log, send a message, prune."
48628
48849
  },
48850
+ {
48851
+ kind: "cli",
48852
+ name: "report",
48853
+ group: "External agents, ACP and MCP",
48854
+ summary: "One-way, unverified report from an outside agent or script to a live keryx shell over the bus."
48855
+ },
48629
48856
  {
48630
48857
  kind: "cli",
48631
48858
  name: "workspace",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrciphersmith/keryx",
3
- "version": "0.4.11",
3
+ "version": "0.4.13",
4
4
  "description": "Version-controlled project context for AI coding agents: code graph, architecture wiki, project memory, relevant tests, quality signals, and task flows.",
5
5
  "private": false,
6
6
  "publishConfig": {
@@ -28,8 +28,6 @@ Run in the main session: this skill dispatches workers. Without a subagent-spawn
28
28
  ## Purpose
29
29
 
30
30
  Flow Orchestrator is the Task Manager-aware implementation orchestrator. Plan bridge: publish the tasks with `plan_set` under the ids `T1`…`Tn`, mirror each `keryx flow task done` with `plan_update`, and publish Phase 4's completion choice as `proposed` — see the `session-plan-bridge` rule.
31
- It wraps the existing gdskills pipeline with `keryx flow` state.
32
-
33
31
  Use this skill instead of `job-orchestrator` when the user wants a managed story/issue lifecycle with frozen acceptance criteria, task state, an explicit completion choice, Code Health, and a durable flow package in `.metaproject/flows/`.
34
32
 
35
33
  ## Hard Preconditions
@@ -614,6 +612,8 @@ Completion is allowed only after the PR merge has been confirmed. The merge
614
612
  target must be the base branch captured when the flow was created; do not
615
613
  silently retarget or close against another branch. The flow folder is committed in the same PR as the code; the commit at closing is a rule to follow, not one the gate checks. `flow complete` fails the `folder-committed` gate while the flow's `flow.json` is not in `HEAD` (flows created from 0.3.53 on; commit it with `git add .metaproject/flows/<dir> && git commit`, then run `flow complete` again). `flow init` and `flow renumber` avoid numbers used on known remote branches, and `keryx flow check` reports a clash with a remote branch (repair with `keryx flow renumber <dir> --to <free id> --reason "<why>"`) and warns about a folder that is not committed. Flows created since the owner gate fail completion while no owner is set (`keryx flow owner set <id> --owner "<name>" --reason "<why>"`); `ac confirm` and `flow complete` append a signature — `--signed-by "<name>"` names the signer, otherwise `KERYX_ACTOR` or the local git identity is recorded, as a claim. A flow created with `--require-confirmation` needs one more gate — `--confirm-token <token>` from `keryx flow confirm <id>`, a short-lived single-use token. In keryx shell call the `flow_confirm` tool (the operator answers it as a card; never send the operator to a terminal); outside it, a typed challenge in a terminal mints it. It proves an interactive step ran, not that a human ran it. A flow left stuck in `completing` by a crash or interrupted attempt (never a normal gate failure) recovers with `keryx flow recover <id> --reason "<why>"`.
616
614
 
615
+ For released work with known refusals, read [completion-exceptions.md](completion-exceptions.md) before closing: require fresh operator words, preserve failing gates, and never call it clean.
616
+
617
617
  If gates fail, the CLI returns the flow to `in-progress`. Add a journal note,
618
618
  create fix tasks, and repeat Phase 2.
619
619
 
@@ -0,0 +1,18 @@
1
+ ### Known exceptions are not blocked work
2
+
3
+ For released work whose remaining refusal is known, show `flow check-complete
4
+ <id>` and ask the operator; do not mark it blocked just because clean closure
5
+ is impossible. Repair a retargeted base with `flow base set <id> --base
6
+ <branch> --reason "<why>"`. Record subsequent fix PRs with `flow implemented
7
+ <id> --pr <url> --fix-of <round-ref>`.
8
+
9
+ Use `flow complete <id> --accept-gate <gate|review:condition>` once per current
10
+ refusal, with `--reason "<why>"`. This requests fresh operator confirmation,
11
+ not an automatic override. In shell call `flow_complete_exceptions`; elsewhere
12
+ use the controlling terminal or the existing host-question protocol
13
+ (`--answered-by <host:ref>`). Never invent the operator's words. Nested and
14
+ unattended contexts cannot confirm. AC integrity/confirmation, tasks, owner,
15
+ committed folder and required completion-token gates cannot be excepted.
16
+ Preserve failed outcomes and operator words; report **completed with
17
+ exceptions**, not clean. Status/list, journal and product index retain it.
18
+