gentle-pi 2.0.0 → 2.1.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.
@@ -1,9 +1,9 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { execFileSync } from "node:child_process";
3
3
  import { createHash } from "node:crypto";
4
- import { chmodSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
4
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
- import { basename, dirname, join } from "node:path";
6
+ import { dirname, join, resolve } from "node:path";
7
7
  import test from "node:test";
8
8
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
9
9
  import { __testing, createGentleAiExtension } from "../extensions/gentle-ai.ts";
@@ -40,9 +40,14 @@ type ToolCallHandler = (
40
40
  ctx: ExtensionContext,
41
41
  ) => Promise<unknown>;
42
42
 
43
+ interface RegisteredCommandFixture {
44
+ handler: (args: string, ctx: ExtensionContext) => Promise<void>;
45
+ }
46
+
43
47
  interface Runtime {
44
48
  controller: RegisteredTool;
45
49
  toolCall: ToolCallHandler;
50
+ commands: Map<string, RegisteredCommandFixture>;
46
51
  }
47
52
 
48
53
  interface PublicationProbeRequestFixture {
@@ -74,6 +79,7 @@ function runtime(
74
79
  candidateViews: CandidateViewRegistry | null = null,
75
80
  ): Runtime {
76
81
  const tools = new Map<string, RegisteredTool>();
82
+ const commands = new Map<string, RegisteredCommandFixture>();
77
83
  let toolCall: ToolCallHandler | undefined;
78
84
  const dependencies = { nativeReviewCli, publicationProbe, publicationProbeTimeoutMs, bashTimeRevalidationTimeoutMs, candidateViews } as unknown as Parameters<typeof createGentleAiExtension>[0];
79
85
  createGentleAiExtension(dependencies)({
@@ -81,12 +87,12 @@ function runtime(
81
87
  if (name === "tool_call") toolCall = handler;
82
88
  },
83
89
  registerTool(definition: RegisteredTool & { name: string }) { tools.set(definition.name, definition); },
84
- registerCommand() {},
90
+ registerCommand(name: string, definition: RegisteredCommandFixture) { commands.set(name, definition); },
85
91
  } as unknown as ExtensionAPI);
86
92
  const controller = tools.get("gentle_review");
87
93
  assert.ok(controller);
88
94
  assert.ok(toolCall);
89
- return { controller, toolCall };
95
+ return { controller, toolCall, commands };
90
96
  }
91
97
 
92
98
  function context(cwd: string, signal?: AbortSignal): ExtensionContext {
@@ -261,7 +267,7 @@ function fakeNative(overrides: Partial<NativeReviewCli> = {}): NativeReviewCli {
261
267
  targetStatus: async (request) => {
262
268
  const lineageId = request.lineageId ?? "";
263
269
  return lineageId === ""
264
- ? targetStatusFixture({ applicability: "unrelated", action: "start" })
270
+ ? candidateStartTargetStatus(request)
265
271
  : targetStatusFixture({ lineageId });
266
272
  },
267
273
  ...overrides,
@@ -287,6 +293,7 @@ function targetStatusFixture(options: {
287
293
  baseTree?: string;
288
294
  currentCandidateTree?: string;
289
295
  paths?: readonly string[];
296
+ projection?: "workspace" | "staged";
290
297
  } = {}): ReviewStatusV3 {
291
298
  const applicability = options.applicability ?? "current_target";
292
299
  const action = options.action ?? (applicability === "current_target" ? "finalize" : applicability === "unrelated" ? "start" : applicability === "ambiguous" ? "select_lineage" : "repair_authority");
@@ -302,7 +309,7 @@ function targetStatusFixture(options: {
302
309
  const projection = {
303
310
  schema: "gentle-ai.review-integration.projection/v1" as const,
304
311
  kind: "current-changes" as const,
305
- projection: "workspace" as const,
312
+ projection: options.projection ?? "workspace",
306
313
  baseTree,
307
314
  initialReviewTree: tree,
308
315
  currentCandidateTree: tree,
@@ -371,6 +378,28 @@ function targetStatusFixture(options: {
371
378
  };
372
379
  }
373
380
 
381
+ function candidateStartTargetStatus(request: Parameters<NonNullable<NativeReviewCli["targetStatus"]>>[0]): ReviewStatusV3 {
382
+ let candidate: ReturnType<CandidateViewRegistry["create"]> | undefined;
383
+ try {
384
+ candidate = new CandidateViewRegistry().create({
385
+ contributorRoot: request.cwd,
386
+ ...(request.baseRef === undefined ? {} : { baseRef: request.baseRef, committedOnly: true }),
387
+ });
388
+ return targetStatusFixture({
389
+ applicability: "unrelated",
390
+ action: "start",
391
+ baseTree: candidate.baseTree,
392
+ currentCandidateTree: candidate.candidateTree,
393
+ paths: candidate.paths,
394
+ projection: request.projection ?? "workspace",
395
+ });
396
+ } catch {
397
+ return targetStatusFixture({ applicability: "unrelated", action: "start" });
398
+ } finally {
399
+ candidate?.cleanup();
400
+ }
401
+ }
402
+
374
403
  function bindReviewerManifest(status: ReviewStatusV3, cwd: string, manifestHash = `sha256:${"7".repeat(64)}`): ReviewStatusV3 {
375
404
  const manifest = deriveChangedPathManifest(cwd, status.projection.baseTree, status.projection.currentCandidateTree).map((entry) => ({
376
405
  ...entry,
@@ -606,7 +635,7 @@ test("fresh registry reload restores the native resumed lineage only while the l
606
635
  stderr: "", exitCode: 0, signal: null, timedOut: false, outputLimitExceeded: false,
607
636
  }));
608
637
  native.targetStatus = async (request) => request.lineageId === undefined
609
- ? targetStatusFixture({ applicability: "unrelated", action: "start" })
638
+ ? candidateStartTargetStatus(request)
610
639
  : targetStatusFixture({ lineageId: request.lineageId });
611
640
  const { controller, toolCall } = runtime(native, undefined, undefined, undefined, candidateViews);
612
641
  await controller.execute("reload-start", { operation: "start", input: JSON.stringify({ mode: "ordinary" }) }, undefined, undefined, context(cwd));
@@ -853,10 +882,10 @@ test("ambiguous native START runs target status first and follows only its decla
853
882
  let statuses = 0;
854
883
  const reconciled = targetStatusFixture({ action: "finalize", lineageId: "resumed-lineage" });
855
884
  const { controller } = runtime(fakeNative({
856
- targetStatus: async () => {
885
+ targetStatus: async (request) => {
857
886
  calls.push("status");
858
887
  statuses += 1;
859
- return statuses === 1 ? targetStatusFixture({ applicability: "unrelated", action: "start" }) : reconciled;
888
+ return statuses === 1 ? candidateStartTargetStatus(request) : reconciled;
860
889
  },
861
890
  start: async (request) => {
862
891
  calls.push("start");
@@ -879,7 +908,9 @@ test("ambiguous native START runs target status first and follows only its decla
879
908
  authority_applicability: "current_target",
880
909
  provider_action: "finalize",
881
910
  });
882
- candidateViews.cleanup(basename(requests[0]!.cwd));
911
+ assert.equal(requests[0]?.cwd, cwd);
912
+ const replayKey = JSON.stringify({ cwd, lineageId: null, input: request.input, inputPath: null });
913
+ candidateViews.createOrReuse({ contributorRoot: cwd, replayKey }).cleanup();
883
914
  });
884
915
 
885
916
  test("ambiguous native FINALIZE returns the target-status action without a second mutation", async (t) => {
@@ -1551,8 +1582,8 @@ test("native START uses the default policy or a canonical safe policy path, and
1551
1582
  await controller.execute("default-policy", { operation: "start", input: JSON.stringify({ mode: "ordinary" }) }, undefined, undefined, context(cwd));
1552
1583
  await controller.execute("custom-policy", { operation: "start", input: JSON.stringify({ mode: "ordinary", policyPath: ".gentle-ai/policies/team policy.json" }) }, undefined, undefined, context(cwd));
1553
1584
  assert.deepEqual(requests, [
1554
- { cwd },
1555
- { cwd, policyPath },
1585
+ { cwd, targetIdentity: `sha256:${"a".repeat(64)}`, projection: "workspace" },
1586
+ { cwd, policyPath, targetIdentity: `sha256:${"a".repeat(64)}`, projection: "workspace" },
1556
1587
  ]);
1557
1588
  for (const [input, outcome, reason] of [
1558
1589
  [{ mode: "ordinary", policyHash: "legacy" }, "native-start-legacy-policy-hash-unsupported", "legacy-policy-hash-unsupported"],
@@ -1588,12 +1619,18 @@ test("native START preserves the default dirty-inclusive candidate without base
1588
1619
  return { lineageId: "default-dirty-lineage", state: "reviewing", riskLevel: "medium", selectedLenses: ["review-reliability"], changedFiles: 2, changedLines: 2, correctionBudget: 1, action: "created", lensesRequired: true };
1589
1620
  },
1590
1621
  }), undefined, undefined, undefined, candidateViews);
1591
- await controller.execute("default-dirty", { operation: "start", input: JSON.stringify({ mode: "ordinary" }) }, undefined, undefined, context(cwd));
1622
+ const started = await controller.execute("default-dirty", { operation: "start", input: JSON.stringify({ mode: "ordinary" }) }, undefined, undefined, context(cwd));
1592
1623
  const view = candidateViews.resolveForLens("default-dirty-lineage", "review-reliability");
1593
1624
  try {
1594
1625
  assert.deepEqual(view.paths, ["app.ts", "untracked.ts"]);
1595
1626
  assert.equal(view.committedOnly, false);
1596
- assert.deepEqual(requests, [{ cwd: view.root }]);
1627
+ assert.deepEqual(requests, [{ cwd, targetIdentity: `sha256:${"a".repeat(64)}`, projection: "workspace" }]);
1628
+ const actorBinding = (started.details as { actor_binding: { workspace_root: string; candidate_root: string; candidate_tree: string; candidate_paths: readonly string[] } }).actor_binding;
1629
+ assert.equal(actorBinding.workspace_root, cwd);
1630
+ assert.equal(actorBinding.candidate_root, view.root);
1631
+ assert.notEqual(actorBinding.candidate_root, requests[0]?.cwd);
1632
+ assert.equal(actorBinding.candidate_tree, view.candidateTree);
1633
+ assert.deepEqual(actorBinding.candidate_paths, view.paths);
1597
1634
  } finally {
1598
1635
  view.cleanup();
1599
1636
  }
@@ -1619,12 +1656,68 @@ test("native START binds an acknowledged committed range and native identity to
1619
1656
  assert.deepEqual(view.paths, ["committed-after-base.ts"]);
1620
1657
  assert.equal(view.committedOnly, true);
1621
1658
  assert.equal(view.baseCommit, baseCommit);
1622
- assert.deepEqual(requests, [{ cwd: view.root, baseRef: view.baseCommit, committedOnly: true }]);
1659
+ assert.deepEqual(requests, [{ cwd, baseRef: view.baseCommit, committedOnly: true, targetIdentity: `sha256:${"a".repeat(64)}`, projection: "workspace" }]);
1623
1660
  } finally {
1624
1661
  view.cleanup();
1625
1662
  }
1626
1663
  });
1627
1664
 
1665
+ test("native START fails closed before mutation when the workspace target and immutable candidate view differ", async (t) => {
1666
+ const cwd = repository(t);
1667
+ writeFileSync(join(cwd, "app.ts"), "export const value = 2;\n");
1668
+ let starts = 0;
1669
+ const { controller } = runtime(fakeNative({
1670
+ targetStatus: async () => targetStatusFixture({
1671
+ applicability: "unrelated",
1672
+ action: "start",
1673
+ baseTree: git(cwd, "rev-parse", "HEAD^{tree}"),
1674
+ currentCandidateTree: "b".repeat(40),
1675
+ paths: ["app.ts"],
1676
+ }),
1677
+ start: async () => {
1678
+ starts += 1;
1679
+ return { lineageId: "must-not-start", state: "reviewing", riskLevel: "medium", selectedLenses: ["review-reliability"], changedFiles: 1, changedLines: 1, correctionBudget: 1, action: "created", lensesRequired: true };
1680
+ },
1681
+ }), undefined, undefined, undefined, new CandidateViewRegistry());
1682
+ const result = await controller.execute("target-view-drift", { operation: "start", input: JSON.stringify({ mode: "ordinary" }) }, undefined, undefined, context(cwd));
1683
+ assert.equal((result.details as { outcome: string }).outcome, "native-operation-failed");
1684
+ assert.deepEqual((result.details as { diagnostics: unknown }).diagnostics, {
1685
+ code: "candidate-target-projection-drift",
1686
+ message: "candidate view rejected before native START",
1687
+ });
1688
+ assert.equal(starts, 0);
1689
+ });
1690
+
1691
+ test("native START re-verifies candidate-view integrity before granting workspace authority", async (t) => {
1692
+ const cwd = repository(t);
1693
+ writeFileSync(join(cwd, "app.ts"), "export const value = 2;\n");
1694
+ class DriftingCandidateViewRegistry extends CandidateViewRegistry {
1695
+ override createOrReuse(request: Parameters<CandidateViewRegistry["createOrReuse"]>[0]): ReturnType<CandidateViewRegistry["createOrReuse"]> {
1696
+ const candidate = super.createOrReuse(request);
1697
+ chmodSync(candidate.root, 0o755);
1698
+ chmodSync(join(candidate.root, "app.ts"), 0o644);
1699
+ writeFileSync(join(candidate.root, "app.ts"), "corrupted frozen content\n");
1700
+ chmodSync(join(candidate.root, "app.ts"), 0o444);
1701
+ chmodSync(candidate.root, 0o555);
1702
+ return candidate;
1703
+ }
1704
+ }
1705
+ let starts = 0;
1706
+ const { controller } = runtime(fakeNative({
1707
+ start: async () => {
1708
+ starts += 1;
1709
+ return { lineageId: "must-not-start", state: "reviewing", riskLevel: "medium", selectedLenses: ["review-reliability"], changedFiles: 1, changedLines: 1, correctionBudget: 1, action: "created", lensesRequired: true };
1710
+ },
1711
+ }), undefined, undefined, undefined, new DriftingCandidateViewRegistry());
1712
+ const result = await controller.execute("candidate-view-drift", { operation: "start", input: JSON.stringify({ mode: "ordinary" }) }, undefined, undefined, context(cwd));
1713
+ assert.equal((result.details as { outcome: string }).outcome, "native-operation-failed");
1714
+ assert.deepEqual((result.details as { diagnostics: unknown }).diagnostics, {
1715
+ code: "candidate-view-invalid",
1716
+ message: "candidate view rejected before native START",
1717
+ });
1718
+ assert.equal(starts, 0);
1719
+ });
1720
+
1628
1721
  test("native START rejects an unresolvable explicit base before native mutation", async (t) => {
1629
1722
  const cwd = repository(t);
1630
1723
  let starts = 0;
@@ -1691,7 +1784,7 @@ test("native START forwards an acknowledged base ref and rejects invalid values
1691
1784
  },
1692
1785
  }));
1693
1786
  await controller.execute("committed-base", { operation: "start", input: JSON.stringify({ mode: "ordinary", baseRef: "refs/heads/main", committedOnly: true }) }, undefined, undefined, context(cwd));
1694
- assert.deepEqual(requests, [{ cwd, baseRef: git(cwd, "rev-parse", "refs/heads/main"), committedOnly: true }]);
1787
+ assert.deepEqual(requests, [{ cwd, baseRef: git(cwd, "rev-parse", "refs/heads/main"), committedOnly: true, targetIdentity: `sha256:${"a".repeat(64)}`, projection: "workspace" }]);
1695
1788
  for (const baseRef of ["", " ", " origin/main", "origin/main ", "origin\0main", "origin\nmain", "origin\rmain", "origin\tmain", "origin\u007fmain", 42, [], {}]) {
1696
1789
  const rejected = await controller.execute("invalid-base", { operation: "start", input: JSON.stringify({ mode: "ordinary", baseRef }) }, undefined, undefined, context(cwd));
1697
1790
  assert.deepEqual(rejected.details, {
@@ -1896,7 +1989,181 @@ test("native allow registers one authorization and bash-time revalidation consum
1896
1989
  assert.equal(await toolCall({ toolName: "bash", input: { command } }, interactiveContext(cwd)), undefined);
1897
1990
  const replay = await toolCall({ toolName: "bash", input: { command } }, context(cwd)) as { block: boolean };
1898
1991
  assert.equal(replay.block, true);
1899
- assert.equal(validates, 2);
1992
+ assert.equal(validates, 3, "the replay discovers but cannot remint the consumed binding");
1993
+ });
1994
+
1995
+ test("fresh pre-commit consumes an exact approved native receipt without START or projection restoration", async (t) => {
1996
+ const cwd = repository(t);
1997
+ writeFileSync(join(cwd, "app.ts"), "export const value = 2;\n");
1998
+ git(cwd, "add", "--", "app.ts");
1999
+ const tree = git(cwd, "write-tree");
2000
+ let starts = 0;
2001
+ const requests: Parameters<NativeReviewCli["validate"]>[0][] = [];
2002
+ const { toolCall } = runtime(fakeNative({
2003
+ start: async () => {
2004
+ starts += 1;
2005
+ throw new Error("an approved exact candidate must not start another review");
2006
+ },
2007
+ validate: async (request) => {
2008
+ requests.push(request);
2009
+ return { allowed: true, result: "allow", action: "continue", reason: "approved receipt binds the index", gateContext: nativeGateContext("approved-lineage", "r1", tree) };
2010
+ },
2011
+ targetStatus: async () => { throw new Error("approved receipt consumption must not reconstruct an unrelated projection"); },
2012
+ }), undefined, undefined, undefined, new CandidateViewRegistry());
2013
+ const command = "git commit -m approved";
2014
+ const input = { command };
2015
+
2016
+ assert.equal(await toolCall({ toolName: "bash", input }, context(cwd)), undefined);
2017
+ assert.equal(starts, 0);
2018
+ assert.equal(requests.length, 2, "authorization and bash-time TOCTOU validation must both run");
2019
+ assert.equal(requests[0]?.lineageId, undefined, "fresh receipt discovery is candidate-bound, not caller-selected");
2020
+ assert.equal(requests[1]?.lineageId, "approved-lineage");
2021
+ assert.notEqual(input.command, command, "the approved pre-commit must use the durable commit transaction");
2022
+ });
2023
+
2024
+ test("a consumed native receipt binding cannot remint authorization for the same exact command", async (t) => {
2025
+ const cwd = repository(t);
2026
+ writeFileSync(join(cwd, "app.ts"), "export const value = 2;\n");
2027
+ git(cwd, "add", "--", "app.ts");
2028
+ const tree = git(cwd, "write-tree");
2029
+ let validations = 0;
2030
+ const { toolCall } = runtime(fakeNative({
2031
+ validate: async () => {
2032
+ validations += 1;
2033
+ return { allowed: true, result: "allow", action: "continue", reason: "same approved receipt", gateContext: nativeGateContext("same-lineage", "same-revision", tree) };
2034
+ },
2035
+ }));
2036
+ const command = "git commit -m same-binding";
2037
+
2038
+ assert.equal(await toolCall({ toolName: "bash", input: { command } }, context(cwd)), undefined);
2039
+ const replayInput = { command };
2040
+ const replay = await toolCall({ toolName: "bash", input: replayInput }, context(cwd)) as { block: boolean };
2041
+ assert.equal(replay.block, true);
2042
+ assert.equal(replayInput.command, command);
2043
+ assert.equal(validations, 3, "the replay may discover the binding once but must not revalidate or authorize it");
2044
+ });
2045
+
2046
+ test("a new approved candidate binding may authorize the same command and cwd later in the session", async (t) => {
2047
+ const cwd = repository(t);
2048
+ const command = "git commit -m reusable-command";
2049
+ const requests: Parameters<NativeReviewCli["validate"]>[0][] = [];
2050
+ const { toolCall } = runtime(fakeNative({
2051
+ validate: async (request) => {
2052
+ requests.push(request);
2053
+ const tree = git(cwd, "write-tree");
2054
+ const suffix = tree.slice(0, 8);
2055
+ return { allowed: true, result: "allow", action: "continue", reason: "candidate-bound receipt", gateContext: nativeGateContext(`lineage-${suffix}`, `revision-${suffix}`, tree) };
2056
+ },
2057
+ }));
2058
+ writeFileSync(join(cwd, "app.ts"), "export const value = 2;\n");
2059
+ git(cwd, "add", "--", "app.ts");
2060
+ const firstInput = { command };
2061
+ assert.equal(await toolCall({ toolName: "bash", input: firstInput }, context(cwd)), undefined);
2062
+ assert.notEqual(firstInput.command, command);
2063
+
2064
+ writeFileSync(join(cwd, "app.ts"), "export const value = 3;\n");
2065
+ git(cwd, "add", "--", "app.ts");
2066
+ const secondInput = { command };
2067
+ assert.equal(await toolCall({ toolName: "bash", input: secondInput }, context(cwd)), undefined);
2068
+ assert.notEqual(secondInput.command, command);
2069
+ assert.equal(requests.length, 4);
2070
+ assert.equal(requests[0]?.lineageId, undefined);
2071
+ assert.equal(requests[1]?.lineageId?.startsWith("lineage-"), true);
2072
+ assert.equal(requests[2]?.lineageId, undefined);
2073
+ assert.equal(requests[3]?.lineageId?.startsWith("lineage-"), true);
2074
+ });
2075
+
2076
+ test("a denied native discovery does not prevent a later valid receipt for the same command", async (t) => {
2077
+ const cwd = repository(t);
2078
+ writeFileSync(join(cwd, "app.ts"), "export const value = 2;\n");
2079
+ git(cwd, "add", "--", "app.ts");
2080
+ const tree = git(cwd, "write-tree");
2081
+ let validations = 0;
2082
+ const { toolCall } = runtime(fakeNative({
2083
+ validate: async () => {
2084
+ validations += 1;
2085
+ return validations === 1
2086
+ ? { allowed: false, result: "scope-changed", action: "create-new-lineage", reason: "not approved yet", gateContext: nativeGateContext("", "denied", tree) }
2087
+ : { allowed: true, result: "allow", action: "continue", reason: "now approved", gateContext: nativeGateContext("later-lineage", "later-revision", tree) };
2088
+ },
2089
+ }));
2090
+ const command = "git commit -m later-approved";
2091
+
2092
+ assert.equal((await toolCall({ toolName: "bash", input: { command } }, context(cwd)) as { block: boolean }).block, true);
2093
+ const approvedInput = { command };
2094
+ assert.equal(await toolCall({ toolName: "bash", input: approvedInput }, context(cwd)), undefined);
2095
+ assert.notEqual(approvedInput.command, command);
2096
+ assert.equal(validations, 3);
2097
+ });
2098
+
2099
+ test("a blocked bash-time native gate does not consume its receipt binding", async (t) => {
2100
+ const cwd = repository(t);
2101
+ writeFileSync(join(cwd, "app.ts"), "export const value = 2;\n");
2102
+ git(cwd, "add", "--", "app.ts");
2103
+ const tree = git(cwd, "write-tree");
2104
+ let validations = 0;
2105
+ const { toolCall } = runtime(fakeNative({
2106
+ validate: async () => {
2107
+ validations += 1;
2108
+ if (validations === 2) return { allowed: false, result: "invalidated", action: "explicit-maintainer-action", reason: "transient authority block", gateContext: nativeGateContext("retry-lineage", "retry-revision", tree) };
2109
+ return { allowed: true, result: "allow", action: "continue", reason: "approved", gateContext: nativeGateContext("retry-lineage", "retry-revision", tree) };
2110
+ },
2111
+ }));
2112
+ const command = "git commit -m retry-binding";
2113
+
2114
+ assert.equal((await toolCall({ toolName: "bash", input: { command } }, context(cwd)) as { block: boolean }).block, true);
2115
+ const retryInput = { command };
2116
+ assert.equal(await toolCall({ toolName: "bash", input: retryInput }, context(cwd)), undefined);
2117
+ assert.notEqual(retryInput.command, command);
2118
+ assert.equal(validations, 4);
2119
+ });
2120
+
2121
+ test("fresh pre-commit rejects an approved receipt for a different index tree", async (t) => {
2122
+ const cwd = repository(t);
2123
+ writeFileSync(join(cwd, "app.ts"), "export const value = 2;\n");
2124
+ git(cwd, "add", "--", "app.ts");
2125
+ let validations = 0;
2126
+ const { toolCall } = runtime(fakeNative({
2127
+ validate: async () => {
2128
+ validations += 1;
2129
+ return { allowed: true, result: "allow", action: "continue", reason: "stale receipt", gateContext: nativeGateContext("stale-lineage", "r1", "f".repeat(40)) };
2130
+ },
2131
+ }));
2132
+ const command = "git commit -m stale";
2133
+ const input = { command };
2134
+
2135
+ const result = await toolCall({ toolName: "bash", input }, context(cwd)) as { block: boolean; reason: string };
2136
+ assert.equal(result.block, true);
2137
+ assert.match(result.reason, /does not bind the exact current pre-commit tree/);
2138
+ assert.equal(validations, 1);
2139
+ assert.equal(input.command, command);
2140
+ });
2141
+
2142
+ test("fresh pre-commit honors native disabled/unmanaged delivery without restoring stale authority", async (t) => {
2143
+ const cwd = repository(t);
2144
+ writeFileSync(join(cwd, "app.ts"), "export const value = 2;\n");
2145
+ git(cwd, "add", "--", "app.ts");
2146
+ let validations = 0;
2147
+ const { toolCall } = runtime(fakeNative({
2148
+ validate: async () => {
2149
+ validations += 1;
2150
+ return {
2151
+ allowed: false,
2152
+ result: "invalidated",
2153
+ action: "repository-policy",
2154
+ reason: "receipt-driven development is disabled",
2155
+ gateContext: nativeGateContext("", "r1", git(cwd, "write-tree")),
2156
+ delivery: "disabled/unmanaged",
2157
+ };
2158
+ },
2159
+ targetStatus: async () => { throw new Error("disabled delivery must not restore stale authority"); },
2160
+ }));
2161
+ const command = "git commit -m unmanaged";
2162
+ const input = { command };
2163
+
2164
+ assert.equal(await toolCall({ toolName: "bash", input }, context(cwd)), undefined);
2165
+ assert.equal(validations, 1);
2166
+ assert.equal(input.command, command, "unmanaged delivery must remain an ordinary repository command");
1900
2167
  });
1901
2168
 
1902
2169
  test("native VALIDATE delivery disabled/unmanaged renders as a successful skipped envelope before the maintainer-exception check, minting no authorization", async (t) => {
@@ -1965,7 +2232,7 @@ test("native pre-commit after reload delegates exact-tree validation when no loc
1965
2232
  validations += 1;
1966
2233
  return { allowed: true, result: "allow", action: "continue", reason: "native receipt matches", gateContext: nativeGateContext("reloaded-lineage", "r1", git(cwd, "write-tree")) };
1967
2234
  },
1968
- targetStatus: async () => targetStatusFixture({ lineageId: "reloaded-lineage", baseTree: git(cwd, "rev-parse", "HEAD^{tree}"), currentCandidateTree: git(cwd, "write-tree"), paths: ["app.ts"] }),
2235
+ targetStatus: async () => targetStatusFixture({ lineageId: "reloaded-lineage", baseTree: git(cwd, "rev-parse", "HEAD^{tree}"), currentCandidateTree: git(cwd, "write-tree"), paths: ["app.ts"], projection: "staged" }),
1969
2236
  }), undefined, undefined, undefined, new CandidateViewRegistry());
1970
2237
  const validated = await controller.execute("reload-pre-commit", { operation: "validate", lineageId: "reloaded-lineage", idempotencyKey: "reload", command: "git commit -m reload", input: "{}" }, undefined, undefined, context(cwd));
1971
2238
  assert.equal(validations, 1);
@@ -3236,7 +3503,7 @@ test("native deny, target drift, and bash-time errors never restore an authoriza
3236
3503
  await drifting.controller.execute("allow", { operation: "validate", lineageId: "native-lineage", idempotencyKey: "key", command, input: "{}" }, undefined, undefined, context(cwd));
3237
3504
  assert.equal((await drifting.toolCall({ toolName: "bash", input: { command } }, context(cwd)) as { block: boolean }).block, true);
3238
3505
  assert.equal((await drifting.toolCall({ toolName: "bash", input: { command } }, context(cwd)) as { block: boolean }).block, true);
3239
- assert.equal(calls, 2);
3506
+ assert.equal(calls, 3, "a blocked gate is not consumed, so the retry performs one fresh fail-closed discovery");
3240
3507
 
3241
3508
  const failing = runtime(fakeNative({
3242
3509
  validate: async () => { throw new Error("native connection lost"); },
@@ -3851,7 +4118,7 @@ test("RECOVER rechecks a committed range against its frozen base instead of the
3851
4118
  const { controller } = runtime(fakeNative({
3852
4119
  targetStatus: async (request) => {
3853
4120
  statusRequests.push(request as Record<string, unknown>);
3854
- if (request.lineageId === undefined) return targetStatusFixture({ applicability: "unrelated", action: "start" });
4121
+ if (request.lineageId === undefined) return candidateStartTargetStatus(request);
3855
4122
  assert.equal(request.baseRef, baseRef);
3856
4123
  const status = targetStatusFixture({ lineageId: "native-lineage", action: "recover" });
3857
4124
  return { ...status, actionDisposition: "invalidated", authority: { ...status.authority!, revision: "rev-1" } };
@@ -3877,3 +4144,135 @@ test("RECOVER rechecks a committed range against its frozen base instead of the
3877
4144
  assert.equal(recovers.length, 1);
3878
4145
  candidateViews.cleanupTerminal("native-lineage", "approved");
3879
4146
  });
4147
+
4148
+ test("dangerous push confirmation precedes mode reconsult outside a repository", async (t) => {
4149
+ const cwd = mkdtempSync(join(tmpdir(), "gentle-pi-non-repository-push-"));
4150
+ t.after(() => rmSync(cwd, { recursive: true, force: true }));
4151
+ let modeCalls = 0;
4152
+ const { toolCall } = runtime(fakeNative({
4153
+ reviewMode: async () => {
4154
+ modeCalls += 1;
4155
+ throw new Error("mode lookup must not precede dangerous-command confirmation");
4156
+ },
4157
+ }));
4158
+ const interactive = interactiveContext(cwd);
4159
+ const deniedContext = { ...interactive, ui: { ...interactive.ui, confirm: async () => false } };
4160
+ const result = await toolCall(
4161
+ { toolName: "bash", input: { command: "git push" } },
4162
+ deniedContext,
4163
+ ) as { block: boolean; reason: string };
4164
+ assert.equal(result.block, true);
4165
+ assert.match(result.reason, /not confirmed/);
4166
+ assert.equal(modeCalls, 0);
4167
+ });
4168
+
4169
+ test("out-of-band review-mode disable discards stale lifecycle authorization and proceeds organically", async (t) => {
4170
+ const cwd = repository(t);
4171
+ let effective: "on" | "off" = "on";
4172
+ let validations = 0;
4173
+ const command = "git commit -m native";
4174
+ const { controller, toolCall } = runtime(fakeNative({
4175
+ reviewMode: async () => ({ operation: "status", scope: "both", status: { global: effective, cloneLocal: "", effective, source: effective === "off" ? "global" : "default" } }),
4176
+ validate: async () => { validations += 1; return { allowed: true, result: "allow", action: "continue", reason: "ok", gateContext: nativeGateContext() }; },
4177
+ targetStatus: async () => targetStatusFixture({ lineageId: "native-lineage", baseTree: git(cwd, "rev-parse", "HEAD^{tree}"), currentCandidateTree: git(cwd, "write-tree"), paths: [] }),
4178
+ }));
4179
+ const authorized = await controller.execute("authorize-before-disable", { operation: "validate", lineageId: "native-lineage", idempotencyKey: "disable-race", command, input: "{}" }, undefined, undefined, context(cwd));
4180
+ assert.notEqual((authorized.details as Record<string, unknown>).authorization, undefined);
4181
+ effective = "off";
4182
+ assert.equal(await toolCall({ toolName: "bash", input: { command } }, context(cwd)), undefined);
4183
+ assert.equal(validations, 1, "disabled organic delivery must not reuse or revalidate stale review authority");
4184
+ });
4185
+
4186
+ test("RDD-off commit and push canonicalize a git -C linked-worktree target before native mode reconsult", async (t) => {
4187
+ const sessionCwd = repository(t);
4188
+ const worktreeParent = mkdtempSync(join(tmpdir(), "gentle-pi-lifecycle-worktrees-"));
4189
+ const worktree = join(worktreeParent, "worktree B");
4190
+ const worktreeAlias = join(worktreeParent, "worktree B alias");
4191
+ git(sessionCwd, "worktree", "add", "-b", "issue-246-worktree", worktree);
4192
+ const windowsDrive = /^([A-Za-z]):[\\/](.*)$/.exec(worktree);
4193
+ const worktreeSpelling = process.platform === "win32"
4194
+ ? `/${windowsDrive?.[1]?.toLowerCase()}/${windowsDrive?.[2]?.replaceAll("\\", "/")}`
4195
+ : worktreeAlias;
4196
+ if (process.platform === "win32") assert.ok(windowsDrive, "Windows worktree must have a drive-qualified path");
4197
+ else symlinkSync(worktree, worktreeAlias, "dir");
4198
+ t.after(() => {
4199
+ try { git(sessionCwd, "worktree", "remove", "--force", worktree); } catch {}
4200
+ rmSync(worktreeParent, { recursive: true, force: true });
4201
+ });
4202
+ const canonicalWorktree = realpathSync(worktree);
4203
+ const commonDirectory = (cwd: string): string => realpathSync(resolve(cwd, git(cwd, "rev-parse", "--git-common-dir")));
4204
+ assert.equal(commonDirectory(sessionCwd), commonDirectory(canonicalWorktree));
4205
+ const parsed = __testing.resolveReviewLifecycleCommand(`git -C "${worktreeSpelling}" commit -m "issue 246"`, sessionCwd);
4206
+ assert.deepEqual(parsed?.gitGlobalArgs, ["-C", worktreeSpelling], "cwd canonicalization must preserve the exact typed Git selector");
4207
+
4208
+ const nativeCalls: Array<{ arguments: readonly string[]; cwd: string }> = [];
4209
+ const native = new NativeReviewCliV214(async (request) => {
4210
+ nativeCalls.push({ arguments: request.arguments, cwd: request.cwd });
4211
+ if (request.cwd !== canonicalWorktree) throw new Error(`native process cwd was not canonical: ${request.cwd}`);
4212
+ if (request.arguments[0] === "version") {
4213
+ return { stdout: "gentle-ai 2.2.2\n", stderr: "", exitCode: 0, signal: null, timedOut: false, outputLimitExceeded: false };
4214
+ }
4215
+ if (request.arguments[0] === "review" && request.arguments[1] === "mode") {
4216
+ return {
4217
+ stdout: JSON.stringify({
4218
+ schema: "gentle-ai.review-mode/v1",
4219
+ operation: "status",
4220
+ scope: "both",
4221
+ status: { schema: "gentle-ai.rdd-mode-status/v1", global: "off", clone_local: "off", effective: "off", source: "clone_local" },
4222
+ }),
4223
+ stderr: "",
4224
+ exitCode: 0,
4225
+ signal: null,
4226
+ timedOut: false,
4227
+ outputLimitExceeded: false,
4228
+ };
4229
+ }
4230
+ throw new Error(`unexpected native review operation: ${request.arguments.join(" ")}`);
4231
+ });
4232
+ const { toolCall } = runtime(native);
4233
+ for (const command of [
4234
+ `git -C "${worktreeSpelling}" commit -m "issue 246"`,
4235
+ `git -C "${worktreeSpelling}" push origin issue-246-worktree`,
4236
+ ]) {
4237
+ assert.equal(await toolCall({ toolName: "bash", input: { command } }, interactiveContext(sessionCwd)), undefined);
4238
+ }
4239
+ assert.equal(nativeCalls.length, 4);
4240
+ assert.equal(nativeCalls.every((call) => call.cwd === canonicalWorktree), true);
4241
+ assert.deepEqual(nativeCalls.filter((call) => call.arguments[0] === "review").map((call) => call.arguments), [
4242
+ ["review", "mode", "status", "--cwd", canonicalWorktree, "--json"],
4243
+ ["review", "mode", "status", "--cwd", canonicalWorktree, "--json"],
4244
+ ]);
4245
+ assert.equal(nativeCalls.some((call) => call.arguments.includes("validate")), false);
4246
+ });
4247
+
4248
+ test("git -C linked-worktree lifecycle commands remain fail-closed when mode reconsult genuinely fails", async (t) => {
4249
+ const sessionCwd = repository(t);
4250
+ const { toolCall } = runtime(fakeNative({ reviewMode: async () => { throw new Error("mode unavailable"); } }));
4251
+ for (const command of ["git -C . commit -m failure", "git -C . push origin main"]) {
4252
+ const result = await toolCall({ toolName: "bash", input: { command } }, interactiveContext(sessionCwd)) as { block: boolean; reason: string };
4253
+ assert.equal(result.block, true);
4254
+ assert.match(result.reason, /could not reconsult review mode and failed closed/);
4255
+ }
4256
+ });
4257
+
4258
+ test("successful /gentle:review-mode disable clears pending authorizations even after mode is re-enabled", async (t) => {
4259
+ const cwd = repository(t);
4260
+ let effective: "on" | "off" = "on";
4261
+ const command = "git commit -m native";
4262
+ const { controller, toolCall, commands } = runtime(fakeNative({
4263
+ reviewMode: async (request) => {
4264
+ if (request.operation === "disable") effective = "off";
4265
+ if (request.operation === "enable") effective = "on";
4266
+ return { operation: request.operation, scope: "clone", status: { global: "", cloneLocal: effective === "off" ? "off" : "", effective, source: effective === "off" ? "clone_local" : "default" } };
4267
+ },
4268
+ validate: async () => ({ allowed: true, result: "allow", action: "continue", reason: "ok", gateContext: nativeGateContext() }),
4269
+ targetStatus: async () => targetStatusFixture({ lineageId: "native-lineage", baseTree: git(cwd, "rev-parse", "HEAD^{tree}"), currentCandidateTree: git(cwd, "write-tree"), paths: [] }),
4270
+ }));
4271
+ await controller.execute("authorize-before-command-disable", { operation: "validate", lineageId: "native-lineage", idempotencyKey: "command-disable", command, input: "{}" }, undefined, undefined, context(cwd));
4272
+ const commandContext = { ...interactiveContext(cwd), ui: { confirm: async () => true, notify: () => {} } } as unknown as ExtensionContext;
4273
+ await commands.get("gentle:review-mode")!.handler("disable", commandContext);
4274
+ await commands.get("gentle:review-mode")!.handler("enable", commandContext);
4275
+ const result = await toolCall({ toolName: "bash", input: { command } }, context(cwd)) as { block: boolean; reason: string };
4276
+ assert.equal(result.block, true);
4277
+ assert.match(result.reason, /receipt consumption failed closed/, "re-enabled delivery must perform fresh receipt discovery rather than reuse the pre-disable authorization");
4278
+ });