gentle-pi 4.6.0 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/README.md +10 -11
  2. package/assets/agents/gentle-ai-explore.md +1 -0
  3. package/assets/agents/gentle-ai-verify.md +5 -2
  4. package/assets/agents/gentle-ai-worker.md +3 -0
  5. package/assets/agents/jd-fix-agent.md +1 -0
  6. package/assets/agents/jd-judge-a.md +1 -0
  7. package/assets/agents/jd-judge-b.md +1 -0
  8. package/assets/design-canvas/canvas.css +13 -1
  9. package/assets/design-canvas/canvas.js +11 -2
  10. package/assets/install-wizard/wizard.js +1 -0
  11. package/assets/migrations/agent-body-history.json +16 -1
  12. package/assets/orchestrator-delegation-reference.md +4 -4
  13. package/assets/orchestrator-delegation.md +1 -1
  14. package/assets/orchestrator-full-delegation-card.md +65 -0
  15. package/assets/orchestrator-full-delegation.md +34 -0
  16. package/assets/orchestrator-memory.md +3 -3
  17. package/assets/orchestrator-prompts.md +1 -1
  18. package/assets/orchestrator-skills.md +1 -1
  19. package/assets/orchestrator-verification.md +7 -5
  20. package/assets/orchestrator.md +3 -3
  21. package/bin/gentle-shell.mjs +164 -56
  22. package/docs/agent-status.md +61 -0
  23. package/docs/bundled-install.md +7 -5
  24. package/docs/delegated-verification.md +29 -7
  25. package/docs/gentle-agents-activity.md +14 -0
  26. package/docs/gentle-shell.md +54 -16
  27. package/docs/install-wizard.md +1 -1
  28. package/docs/permission-modes.md +9 -4
  29. package/docs/readme-reference.md +75 -30
  30. package/docs/render-cache-performance.md +11 -1
  31. package/docs/review-coordinator.md +33 -0
  32. package/docs/review-request-context.md +19 -0
  33. package/docs/review-windows-acl.md +18 -0
  34. package/docs/voice.md +6 -3
  35. package/docs/yolo-mode.md +5 -5
  36. package/extensions/ask-user-choice.ts +1 -0
  37. package/extensions/ask-user-question.ts +1 -0
  38. package/extensions/child-safety.ts +3 -0
  39. package/extensions/gentle-agent-status.ts +99 -0
  40. package/extensions/gentle-agents.ts +326 -34
  41. package/extensions/gentle-ai.ts +1496 -454
  42. package/extensions/gentle-shell.ts +293 -63
  43. package/extensions/gentle-todo.ts +18 -2
  44. package/extensions/gentle-tps.ts +48 -0
  45. package/extensions/quiet-tools.ts +38 -8
  46. package/extensions/skill-registry.ts +175 -18
  47. package/extensions/startup-banner.ts +30 -3
  48. package/lib/agent-profile-pin.ts +3 -3
  49. package/lib/agent-profiles.ts +160 -2
  50. package/lib/agent-status.ts +105 -0
  51. package/lib/agents-config.ts +46 -0
  52. package/lib/agents-history.ts +24 -5
  53. package/lib/agents-messaging.ts +47 -5
  54. package/lib/agents-runner.ts +183 -12
  55. package/lib/auto-permission-runtime.ts +1 -1
  56. package/lib/bounded-writer-admission.ts +13 -1
  57. package/lib/card-content-policy.ts +8 -6
  58. package/lib/command-palette.ts +133 -17
  59. package/lib/context-backstop.ts +14 -5
  60. package/lib/destructive-command-guard.ts +48 -4
  61. package/lib/execution-surface-guard.ts +20 -0
  62. package/lib/exploration-budget.ts +4 -2
  63. package/lib/gentle-ai-binary.ts +1 -1
  64. package/lib/gentle-design.ts +3 -0
  65. package/lib/gentle-shell-bundled.ts +6 -19
  66. package/lib/gentle-shell-launcher.ts +43 -8
  67. package/lib/herdr-activity.ts +14 -2
  68. package/lib/herdr-busy.ts +45 -0
  69. package/lib/image-attachments.ts +33 -0
  70. package/lib/image-disk-cache.ts +137 -0
  71. package/lib/inprocess-reviewer.ts +270 -140
  72. package/lib/jobs-view.ts +198 -11
  73. package/lib/model-routing-authority.ts +22 -4
  74. package/lib/native-choice-list.ts +20 -2
  75. package/lib/native-review-cli.ts +96 -19
  76. package/lib/orchestrator-mode-policy.ts +105 -0
  77. package/lib/questionnaire/questionnaire-view.ts +105 -12
  78. package/lib/rdd-mode-control.ts +32 -0
  79. package/lib/reply-language-anchor.ts +104 -0
  80. package/lib/review-blocker.ts +92 -0
  81. package/lib/review-candidate-symlink-scan.ts +136 -0
  82. package/lib/review-candidate-view-owner.ts +81 -44
  83. package/lib/review-continuation-registry.ts +99 -0
  84. package/lib/review-coordinator.ts +163 -0
  85. package/lib/review-failure-facts.ts +49 -0
  86. package/lib/review-host-relay.ts +46 -10
  87. package/lib/review-integration-v2.ts +7 -1
  88. package/lib/review-relay-phase-timing.ts +45 -0
  89. package/lib/review-start-context.ts +17 -0
  90. package/lib/session-profile-freeze.ts +4 -2
  91. package/lib/shell-bar.ts +140 -58
  92. package/lib/shell-changes.ts +2 -0
  93. package/lib/shell-panel.ts +17 -3
  94. package/lib/shell-sidebar-layout.ts +112 -40
  95. package/lib/shell-sidebar.ts +7 -0
  96. package/lib/shell-todo.ts +10 -3
  97. package/lib/verifier-admission.ts +1 -1
  98. package/lib/visual-customization-policy.ts +36 -16
  99. package/lib/visual-customize-view.ts +216 -21
  100. package/lib/visual-layout-preview.ts +9 -5
  101. package/lib/visual-profiles.ts +2 -2
  102. package/lib/windows-session-transport.ts +53 -2
  103. package/lib/yolo-session-policy.ts +40 -15
  104. package/package.json +2 -1
  105. package/runtime/gentle-ai-binary.mjs +1 -1
  106. package/runtime/gentle-shell-bundled.mjs +6 -19
  107. package/runtime/gentle-shell-launcher.mjs +42 -7
  108. package/runtime/native-review-cli.mjs +93 -16
  109. package/runtime/review-integration-v2.mjs +7 -1
  110. package/scripts/build-full-delegation-card.mjs +175 -0
  111. package/scripts/bundled-install.mjs +38 -8
  112. package/scripts/download-progress.mjs +68 -0
  113. package/scripts/gentle-ai-installer.mjs +41 -18
  114. package/scripts/gentle-ai-proxy.mjs +294 -0
  115. package/scripts/install-gentle-ai.mjs +14 -1
  116. package/scripts/installer-preflight.mjs +5 -5
  117. package/scripts/installer-runner.mjs +27 -12
  118. package/scripts/installer-server.mjs +8 -7
  119. package/scripts/render-cache-host.mjs +72 -0
  120. package/scripts/render-cache-performance-worker.mjs +5 -4
  121. package/scripts/render-cache-performance.mjs +6 -1
  122. package/scripts/run-test-suite.mjs +40 -28
  123. package/scripts/verify-package-files.mjs +12 -2
  124. package/scripts/voice-worker.cjs +32 -6
  125. package/skills/design/SKILL.md +11 -8
  126. package/skills/gentle-ai/SKILL.md +2 -2
  127. package/skills/gentle-ui-design/SKILL.md +46 -0
  128. package/skills/gentle-ui-design/references/adaptive-interfaces.md +46 -0
  129. package/skills/gentle-ui-design/references/browse-and-compare.md +62 -0
  130. package/skills/gentle-ui-design/references/composition-and-feedback.md +56 -0
  131. package/skills/gentle-ui-design/references/task-and-content.md +60 -0
  132. package/skills/skill-registry/SKILL.md +4 -2
  133. package/skills/work-unit-commits/SKILL.md +6 -7
  134. package/tests/agent-home.test.ts +28 -9
  135. package/tests/agent-profiles-workflow.test.ts +163 -0
  136. package/tests/agent-risk-escalation.test.ts +1 -1
  137. package/tests/agent-status.test.ts +143 -0
  138. package/tests/agents-config.test.ts +96 -0
  139. package/tests/agents-history.test.ts +31 -0
  140. package/tests/agents-jobs-frames.test.ts +93 -0
  141. package/tests/agents-prompt-lifecycle-runtime.test.ts +376 -0
  142. package/tests/agents-runner-drain.test.ts +193 -0
  143. package/tests/agents-runner.test.ts +178 -2
  144. package/tests/append-system-prompt-route.test.ts +4 -1
  145. package/tests/ask-user-choice.test.ts +4 -3
  146. package/tests/ask-user-question.test.ts +97 -0
  147. package/tests/auto-permission-runtime.test.ts +1 -1
  148. package/tests/autonomous-guard.test.ts +346 -10
  149. package/tests/bounded-stop-contract.test.ts +43 -3
  150. package/tests/bridge-cost.test.ts +19 -4
  151. package/tests/bundled-install.test.ts +30 -5
  152. package/tests/card-content-policy.test.ts +3 -3
  153. package/tests/chained-pr-skill.test.ts +8 -6
  154. package/tests/child-safety.test.ts +11 -0
  155. package/tests/codegraph-tools.test.ts +11 -5
  156. package/tests/command-palette.test.ts +284 -1
  157. package/tests/delegate-for-reason-contract.test.ts +3 -3
  158. package/tests/design-canvas-assets.test.ts +185 -2
  159. package/tests/destructive-command-guard.test.ts +52 -0
  160. package/tests/download-progress.test.ts +71 -0
  161. package/tests/execution-surface-guard.test.ts +55 -0
  162. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +9 -5
  163. package/tests/fixtures/proxy-tls/proxy.crt +19 -0
  164. package/tests/fixtures/proxy-tls/proxy.key +28 -0
  165. package/tests/fixtures/session-profile-v1/gentle-ai-reviewer.ts +89 -0
  166. package/tests/fixtures/session-profile-v1/replay.ts +53 -6
  167. package/tests/full-delegation-closure.test.ts +131 -0
  168. package/tests/full-delegation-notices.test.ts +76 -0
  169. package/tests/generic-agent-tools.test.ts +3 -3
  170. package/tests/gentle-agent-status.test.ts +74 -0
  171. package/tests/gentle-agents-child-jobs.test.ts +237 -0
  172. package/tests/gentle-agents.test.ts +1070 -12
  173. package/tests/gentle-ai-binary.test.ts +3 -1
  174. package/tests/gentle-ai-elapsed-store.test.ts +19 -0
  175. package/tests/gentle-ai-exploration-budget.test.ts +18 -2
  176. package/tests/gentle-ai-installer.test.ts +134 -51
  177. package/tests/gentle-ai-proxy.test.ts +434 -0
  178. package/tests/gentle-ai.test.ts +113 -38
  179. package/tests/gentle-design.test.ts +21 -0
  180. package/tests/gentle-herdr-activity.test.ts +9 -6
  181. package/tests/gentle-shell-bin.test.ts +123 -0
  182. package/tests/gentle-shell-bundled.test.ts +207 -31
  183. package/tests/gentle-shell-launcher.test.ts +77 -10
  184. package/tests/gentle-shell.test.ts +899 -59
  185. package/tests/gentle-todo.test.ts +19 -2
  186. package/tests/gentle-tps.test.ts +123 -0
  187. package/tests/gentle-ui-design-skill.test.ts +59 -0
  188. package/tests/herdr-busy.test.ts +59 -0
  189. package/tests/herdr-task-summary-policy.test.ts +8 -4
  190. package/tests/image-disk-cache.test.ts +163 -0
  191. package/tests/independent-recovery-delivery.test.ts +83 -0
  192. package/tests/inprocess-reviewer.test.ts +176 -4
  193. package/tests/installer-posix-bootstrap.test.ts +1 -1
  194. package/tests/installer-preflight.test.ts +5 -4
  195. package/tests/installer-runner.test.ts +79 -44
  196. package/tests/installer-server.test.ts +14 -11
  197. package/tests/jobs-view.test.ts +260 -6
  198. package/tests/modal-mouse-boundaries.test.ts +136 -0
  199. package/tests/model-routing-authority.test.ts +178 -2
  200. package/tests/native-choice-list.test.ts +77 -2
  201. package/tests/native-review-capability-contract.test.ts +7 -1
  202. package/tests/native-review-cli.test.ts +269 -1
  203. package/tests/no-self-pause-contract.test.ts +4 -1
  204. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  205. package/tests/orchestrator-budget.test.ts +7 -2
  206. package/tests/orchestrator-delegation-mode.test.ts +153 -0
  207. package/tests/orchestrator-mode-policy.test.ts +175 -0
  208. package/tests/orchestrator-prompt-budget.test.ts +3 -1
  209. package/tests/orchestrator-rdd-ownership.test.ts +2 -2
  210. package/tests/package-manifest.test.ts +11 -9
  211. package/tests/permission-allowlist.test.ts +202 -0
  212. package/tests/pi-update-launcher.test.ts +8 -0
  213. package/tests/pnpm-workspace-config.test.ts +58 -0
  214. package/tests/primary-session-prompt.test.ts +13 -0
  215. package/tests/profile-pin.test.ts +29 -2
  216. package/tests/profile-tier-footer.test.ts +5 -0
  217. package/tests/profiles-panel-delegation-mode.test.ts +422 -0
  218. package/tests/questionnaire-view.test.ts +115 -0
  219. package/tests/quiet-bash-runtime.test.ts +1 -1
  220. package/tests/quiet-tool-rendering.test.ts +48 -0
  221. package/tests/rdd-aware-verification-contract.test.ts +16 -11
  222. package/tests/rdd-customize.test.ts +287 -0
  223. package/tests/rdd-mode-cache.test.ts +450 -0
  224. package/tests/rdd-mode-control.test.ts +407 -0
  225. package/tests/rdd-mode-scope-regression.test.ts +137 -0
  226. package/tests/rdd-off-independent-regression.test.ts +69 -0
  227. package/tests/rdd-status-line.test.ts +18 -0
  228. package/tests/render-cache-performance.test.ts +171 -2
  229. package/tests/reply-language-anchor.test.ts +173 -0
  230. package/tests/review-agent-end-preflight.test.ts +1 -1
  231. package/tests/review-blocker.test.ts +193 -0
  232. package/tests/review-candidate-owner-retry.test.ts +1 -1
  233. package/tests/review-candidate-symlink-scan.test.ts +157 -0
  234. package/tests/review-candidate-view.test.ts +1 -1
  235. package/tests/review-candidate-windows-boundary.test.ts +131 -0
  236. package/tests/review-candidate-windows-probe.test.ts +63 -0
  237. package/tests/review-committed-restart-ack.test.ts +129 -0
  238. package/tests/review-continuation-registry.test.ts +76 -0
  239. package/tests/review-controller-native-routing.test.ts +261 -5
  240. package/tests/review-controller-workspace-root.test.ts +230 -3
  241. package/tests/review-controller.test.ts +96 -11
  242. package/tests/review-coordinator-runtime.test.ts +117 -0
  243. package/tests/review-coordinator.test.ts +195 -0
  244. package/tests/review-failure-facts.test.ts +87 -0
  245. package/tests/review-host-relay-routing.test.ts +258 -4
  246. package/tests/review-host-relay.test.ts +39 -0
  247. package/tests/review-integration-v2.test.ts +46 -3
  248. package/tests/review-json-arguments.test.ts +65 -10
  249. package/tests/review-last-event-closure.test.ts +68 -0
  250. package/tests/review-loadout-rdd-off-sdk.test.ts +65 -31
  251. package/tests/review-owner-identity.test.ts +60 -24
  252. package/tests/review-relay-phase-timing.test.ts +128 -0
  253. package/tests/review-relay-transport-agent.test.ts +12 -2
  254. package/tests/review-reviewer-evidence.test.ts +183 -0
  255. package/tests/review-risk-assessment.test.ts +74 -3
  256. package/tests/review-session-standing-permission-controller.test.ts +21 -1
  257. package/tests/review-start-context.test.ts +19 -0
  258. package/tests/review-tool-prose-budget.test.ts +121 -0
  259. package/tests/run-test-suite.test.ts +122 -1
  260. package/tests/runtime-harness.mjs +4 -1
  261. package/tests/sensitive-path-tools.test.ts +181 -5
  262. package/tests/session-profile-append-controller-pi.test.ts +60 -31
  263. package/tests/session-profile-binding.test.ts +19 -1
  264. package/tests/session-profile-disk-reader-pi.test.ts +58 -16
  265. package/tests/session-profile-v1-compat.test.ts +35 -1
  266. package/tests/shell-bar.test.ts +186 -42
  267. package/tests/shell-panel.test.ts +50 -22
  268. package/tests/shell-sidebar-fullscreen.test.ts +5 -5
  269. package/tests/shell-sidebar-layout.test.ts +294 -23
  270. package/tests/shell-sidebar-scroll-benchmark.test.ts +1 -1
  271. package/tests/shell-surface-transparent.test.ts +89 -0
  272. package/tests/shell-todo.test.ts +12 -0
  273. package/tests/skill-registry.test.ts +838 -5
  274. package/tests/startup-banner.test.ts +152 -1
  275. package/tests/startup-home-repo.test.ts +2 -0
  276. package/tests/support/review-coordinator-runtime.ts +69 -0
  277. package/tests/task-size-routing-contract.test.ts +5 -3
  278. package/tests/verifier-admission.test.ts +49 -0
  279. package/tests/verify-first-launch-contract.test.ts +78 -3
  280. package/tests/visual-customization-policy.test.ts +39 -6
  281. package/tests/visual-customize-view.test.ts +573 -9
  282. package/tests/visual-layout-preview.test.ts +15 -1
  283. package/tests/visual-profiles.test.ts +11 -0
  284. package/tests/voice-worker.test.ts +73 -2
  285. package/tests/windows-session-transport.test.ts +126 -0
  286. package/tests/work-continuity-contract.test.ts +28 -0
  287. package/tests/writer-feature-document-admission.test.ts +92 -0
  288. package/tests/yolo-customize.test.ts +27 -4
  289. package/tests/yolo-mode.test.ts +23 -18
  290. package/tests/yolo-session-policy.test.ts +270 -1
@@ -0,0 +1,32 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { NativeReviewModeSource } from "./native-review-cli.ts";
3
+
4
+ /** The owner supplies the live UI; consumers cannot provide a context or a mode setter. */
5
+ export interface RddModeControl {
6
+ read(): Promise<{ effective: "on" | "off"; source: NativeReviewModeSource } | undefined>;
7
+ open(): Promise<void>;
8
+ }
9
+
10
+ export const RDD_MODE_CONTROL_CHANNEL = "gentle:rdd:host-ui";
11
+
12
+ /** Discover the current session owner for a human-operated UI, if one is available. */
13
+ export function discoverRddModeControl(pi: ExtensionAPI): Promise<RddModeControl | undefined> {
14
+ return new Promise((resolve) => {
15
+ let settled = false;
16
+ const timer = setTimeout(() => { settled = true; resolve(undefined); }, 100);
17
+ try {
18
+ pi.events.emit(RDD_MODE_CONTROL_CHANNEL, {
19
+ respond(value: RddModeControl) {
20
+ if (settled || typeof value?.read !== "function" || typeof value?.open !== "function") return;
21
+ settled = true;
22
+ clearTimeout(timer);
23
+ resolve(value);
24
+ },
25
+ });
26
+ } catch {
27
+ settled = true;
28
+ clearTimeout(timer);
29
+ resolve(undefined);
30
+ }
31
+ });
32
+ }
@@ -0,0 +1,104 @@
1
+ // Reply-language anchor (full-delegation-mode-conflicts S9).
2
+ //
3
+ // The primary session replies in the human's language, while subagent results,
4
+ // wakes, job notices and summaries are English and reach the model with the user
5
+ // role. A prompt rule ("reply in the language of the human's own last message")
6
+ // did not hold on its own: in a long session that message sits far up the
7
+ // transcript, and after compaction it is gone. So the harness records the human's
8
+ // own text and, when the model is about to answer right after an automated
9
+ // message, adds one anchor that quotes the start of it. No language detection:
10
+ // the human's words carry their language.
11
+ //
12
+ // The anchor is added only when the context's tail is automated, never mid tool
13
+ // loop, and only when no anchor already follows that tail. The caller persists it
14
+ // once, so the following requests stay append-only and the provider's prompt
15
+ // cache keeps its prefix (gentle-shell#1662, #2195). Pure: no pi imports.
16
+
17
+ import type { ContextEvent } from "@earendil-works/pi-coding-agent";
18
+
19
+ type AgentMessage = ContextEvent["messages"][number];
20
+
21
+ export const REPLY_LANGUAGE_ANCHOR_TYPE = "gentle-pi.reply-language";
22
+
23
+ /** Custom messages that never ask the model to answer, so they neither trigger nor hide an anchor. */
24
+ const PASSIVE_TYPES = new Set(["gentle-todo-state", "gentle-todo-reminder", REPLY_LANGUAGE_ANCHOR_TYPE]);
25
+ /** Every automated wake opens with this disowning prefix (extensions/gentle-agents.ts PARENT_WAKE_TEXT). */
26
+ const AUTOMATED_USER_PREFIX = "[System-generated ";
27
+ const EXCERPT_CHARS = 100;
28
+
29
+ type Message = { role?: unknown; customType?: unknown; content?: unknown };
30
+
31
+ function text(content: unknown): string {
32
+ if (typeof content === "string") return content;
33
+ if (!Array.isArray(content)) return "";
34
+ return content
35
+ .map((part) => (part && typeof part === "object" && (part as { type?: unknown }).type === "text" ? String((part as { text?: unknown }).text ?? "") : ""))
36
+ .join(" ");
37
+ }
38
+
39
+ /** Typed by the human: interactive or RPC input, never extension-sent text, commands, or shell escapes. */
40
+ export function isHumanInput(source: string, input: string): boolean {
41
+ const trimmed = input.trim();
42
+ return source !== "extension" && trimmed !== "" && !trimmed.startsWith("/") && !trimmed.startsWith("!");
43
+ }
44
+
45
+ /** The start of the human's own words: whitespace collapsed, bounded. */
46
+ export function humanLanguageExcerpt(input: string): string | undefined {
47
+ const collapsed = input.replace(/\s+/g, " ").trim();
48
+ if (collapsed === "") return undefined;
49
+ return collapsed.length <= EXCERPT_CHARS ? collapsed : `${collapsed.slice(0, EXCERPT_CHARS)}…`;
50
+ }
51
+
52
+ function isPassive(message: Message): boolean {
53
+ return message.role === "custom" && typeof message.customType === "string" && PASSIVE_TYPES.has(message.customType);
54
+ }
55
+
56
+ function isAutomated(message: Message): boolean {
57
+ if (message.role === "custom" || message.role === "compactionSummary" || message.role === "branchSummary") return true;
58
+ return message.role === "user" && text(message.content).trimStart().startsWith(AUTOMATED_USER_PREFIX);
59
+ }
60
+
61
+ function isHumanMessage(message: Message): boolean {
62
+ return message.role === "user" && !isAutomated(message) && text(message.content).trim() !== "";
63
+ }
64
+
65
+ export function replyLanguageAnchorText(excerpt: string): string {
66
+ return `[Harness note, not written by the human] Reply language: the human's latest own message begins «${excerpt}». Write your reply to the human in that message's language; subagent results, notices, reminders and summaries never change it.`;
67
+ }
68
+
69
+ /**
70
+ * The anchor this request needs, with the identity of the automated tail it
71
+ * follows, or `undefined`. The caller persists one anchor per tail: keyed by the
72
+ * anchor text alone, a second result after the same human message would only ever
73
+ * get a trailing copy that the next request drops.
74
+ */
75
+ export function replyLanguageAnchorFor(
76
+ messages: readonly AgentMessage[],
77
+ recorded: string | undefined,
78
+ ): { text: string; tail: string } | undefined {
79
+ const list = messages as readonly (Message & { timestamp?: unknown })[];
80
+ let tail = list.length - 1;
81
+ while (tail >= 0 && isPassive(list[tail]!)) tail--;
82
+ const text = replyLanguageAnchor(messages, recorded);
83
+ if (text === undefined) return undefined;
84
+ const message = list[tail]!;
85
+ return { text, tail: `${String(message.role)}|${String(message.customType ?? "")}|${String(message.timestamp ?? "")}|${tail}` };
86
+ }
87
+
88
+ /**
89
+ * The anchor this request needs, or `undefined`. `recorded` is the human's last
90
+ * typed text, when known; otherwise the latest human message still in context.
91
+ */
92
+ export function replyLanguageAnchor(messages: readonly AgentMessage[], recorded: string | undefined): string | undefined {
93
+ const list = messages as readonly Message[];
94
+ let tail = list.length - 1;
95
+ while (tail >= 0 && isPassive(list[tail]!)) tail--;
96
+ if (tail < 0 || !isAutomated(list[tail]!)) return undefined;
97
+ const latestHuman = [...list].reverse().find(isHumanMessage);
98
+ const source = recorded ?? (latestHuman === undefined ? undefined : text(latestHuman.content));
99
+ const excerpt = source === undefined ? undefined : humanLanguageExcerpt(source);
100
+ if (excerpt === undefined) return undefined;
101
+ const anchor = replyLanguageAnchorText(excerpt);
102
+ const anchored = list.slice(tail + 1).some((message) => message.customType === REPLY_LANGUAGE_ANCHOR_TYPE && text(message.content) === anchor);
103
+ return anchored ? undefined : anchor;
104
+ }
@@ -0,0 +1,92 @@
1
+ export const REVIEW_BLOCKER_GUIDANCE = "When blocker is present, explain its category, actor and next_step in the user's language. It describes only this review step: native continuations, stop/no-retry rules, consent and ordinary repository delivery policy remain authoritative. Do not infer a need to contact a remote maintainer from maintainerAuthorization alone.";
2
+
3
+ /** Informational host diagnosis; native continuations and repository policy remain authoritative. */
4
+ export interface ReviewBlocker {
5
+ category: "configuration" | "input" | "consent" | "continuation" | "stale-binding" | "provider-capability" | "provider-unavailable" | "admission-refused" | "generation-invalid" | "authority-unavailable" | "provider-stop" | "diagnosis-required";
6
+ scope: "review-step";
7
+ actor: "user" | "caller" | "authorized-operator" | "unknown";
8
+ next_step: string;
9
+ automatic_retry: false;
10
+ native_next_action?: string;
11
+ }
12
+
13
+ /** Read object-shaped diagnostic fields without interpreting scalars or arrays. */
14
+ function record(value: unknown): Record<string, unknown> {
15
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : {};
16
+ }
17
+
18
+ /** Classify structured facts only, never provider prose, prompts or stderr. */
19
+ export function withReviewBlocker(result: Record<string, unknown>): Record<string, unknown> {
20
+ if (result.status !== "blocked") return result;
21
+ const native = record(result.native_failure);
22
+ const transition = record(record(result.result).next_transition);
23
+ const failure = record(result.failure);
24
+ const nativeAction = typeof native.next_action === "string" ? native.next_action : undefined;
25
+ const diagnose = (category: ReviewBlocker["category"], actor: ReviewBlocker["actor"], next_step: string): Record<string, unknown> => ({
26
+ ...result,
27
+ blocker: { category, scope: "review-step", actor, next_step, automatic_retry: false,
28
+ ...(nativeAction === undefined ? {} : { native_next_action: nativeAction }) } satisfies ReviewBlocker,
29
+ });
30
+ // Uncertainty takes precedence over convenient local remedies. A diagnosis
31
+ // must not suggest re-running an operation that may already have committed.
32
+ if (result.mutation_outcome === "unknown" || result.mutation_outcome === "partial_unknown") {
33
+ return diagnose("authority-unavailable", "unknown", "Follow the returned native reconciliation or stop action. Do not replay an operation with an unknown outcome.");
34
+ }
35
+ if (nativeAction === "explicit-maintainer-action") {
36
+ return diagnose("authority-unavailable", "authorized-operator", "Use the provider-supported maintenance route with its required fresh authorization. Do not infer permission to repair or replay.");
37
+ }
38
+ if (nativeAction !== "stop" && transition.kind !== "stop" && (result.outcome === "native-status-unsupported" || result.outcome === "request-context-unsupported" || failure.kind === "relay-unavailable" || failure.kind === "handshake-refused" || result.outcome === "pi-host-relay-handshake-refused" || result.outcome === "pi-host-relay-unavailable" || result.outcome === "pi-host-relay-transport-unavailable")) {
39
+ return diagnose("provider-capability", "user", "Check the package-selected native provider, its supported capabilities and the host handshake; reload the host after a supported installation change. Escalate only if the required capability is still unavailable.");
40
+ }
41
+ if (result.outcome === "native-status-package-binary-missing" || native.code === "managed_assets_outdated") {
42
+ return diagnose("configuration", "user", "Use the returned installation or managed-asset remediation. Keep any provider stop and authorization requirements in force.");
43
+ }
44
+ if (["reviewer-config-invalid", "reviewer-model-not-found", "reviewer-thinking-invalid"].includes(String(failure.kind))) {
45
+ return diagnose("configuration", "user", "Configure the indicated review routing key with an available model and supported thinking setting. Then follow the returned continuation; this does not authorize a model run or retry.");
46
+ }
47
+ if (failure.kind === "reviewer-auth-unavailable") {
48
+ return diagnose("configuration", "user", "Resolve authentication for the configured reviewer provider, then follow the returned continuation without replaying an uncertain submission.");
49
+ }
50
+ if (failure.kind === "submission-refused") {
51
+ return diagnose("admission-refused", "caller", "The provider refused the generated submission. Preserve its evidence and exact next action; do not strip fields, fabricate a verdict or retry automatically.");
52
+ }
53
+ if (["reviewer-tool-call-attempted", "reviewer-empty-output", "reviewer-output-too-large"].includes(String(failure.kind))) {
54
+ return diagnose("generation-invalid", "caller", "The completion did not satisfy the reviewer boundary. Follow the returned native continuation; do not substitute a result or assume another generation is authorized.");
55
+ }
56
+ if (result.outcome === "native-review-consent-required" || result.outcome === "reviewer-model-run-forecast" || result.outcome === "consent-binding-invalid") {
57
+ return diagnose("consent", "user", "Resolve the returned consent or model-run confirmation through the host using its current binding. This diagnostic grants no consent.");
58
+ }
59
+ if (result.outcome === "consent-binding-stale" || (result.outcome === "intended-untracked-selection-binding-rejected" && ["binding-mismatch", "status-field-mismatch"].includes(String(result.reason)))) {
60
+ return diagnose("stale-binding", "caller", "Do not resend this binding. Follow the host's current continuation to obtain the exact binding for the current candidate, preserving any stop or authorization requirement.");
61
+ }
62
+ // A blocked facade response can be a normal offer awaiting its next host
63
+ // operation. Do not diagnose a ready ACK or collect offer as an unknown error.
64
+ if (result.outcome === undefined && result.failure === undefined && result.native_failure === undefined && result.reconciliation_failure === undefined && result.reconciliation === undefined && transition.kind === "collect" && transition.reason_code === "empty_candidate_base_ref_required") {
65
+ return diagnose("input", "caller", "The current candidate needs an explicit baseRef with committedOnly: true if a committed range is intended. To check a previously acknowledged candidate, use ASSESS with its original committed range and follow the returned evidence. This input request does not establish that an earlier review failed or remains open; it does not authorize another review, acknowledgement or maintenance operation.");
66
+ }
67
+ if (result.outcome === undefined && result.failure === undefined && result.native_failure === undefined && result.reconciliation_failure === undefined && result.reconciliation === undefined && (
68
+ (transition.kind === "execute" && ["review.start", "review.status", "review.acknowledge-approved"].includes(String(record(transition.execute).operation))) ||
69
+ (Array.isArray(result.collectBindings) && result.collectBindings.length > 0)
70
+ )) {
71
+ return diagnose("continuation", "caller", "Follow the exact offered host continuation and its required model-run confirmation or consent. This is a pending review step, not an unknown failure or a new execution permission.");
72
+ }
73
+ if (native.code === "invalid_request" || typeof result.selectionBinding === "string" || Array.isArray(result.collectBindings) || result.outcome === "capture-binding-rejected" || result.outcome === "capture-group-rejected" || (typeof result.outcome === "string" && result.outcome.startsWith("native-start-"))) {
74
+ return diagnose("input", "caller", "Supply the exact requested fields or current host-issued binding. Follow any native stop or no-retry action; a corrected input is not automatic replay permission.");
75
+ }
76
+ if (nativeAction === "stop" || transition.kind === "stop") {
77
+ return diagnose("provider-stop", "unknown", "The provider stopped this review step. Use only a recovery or continuation it explicitly offers; otherwise preserve the diagnostic for investigation.");
78
+ }
79
+ if (result.outcome === "native-status-timed-out") {
80
+ return diagnose("provider-unavailable", "user", "The read-only review inventory read timed out before it completed. Nothing was mutated; rerun the returned remediation_command when ready. Pi does not retry automatically.");
81
+ }
82
+ if (record(result.diagnostics).timed_out === true) {
83
+ return diagnose("provider-unavailable", "unknown", "The native process timed out; its internal phase is not established. Follow the returned action without assuming lock contention, deleting locks or retrying automatically.");
84
+ }
85
+ if (result.outcome === "capture-route-registration-rejected" || result.inventory_complete === false) {
86
+ return diagnose("authority-unavailable", "unknown", "The current authority or routing evidence is incomplete. Preserve the diagnostic and use only the supported native continuation; do not reset or rebuild authority locally.");
87
+ }
88
+ if (failure.kind === "pi-timed-out" || failure.kind === "materialize-failed" || failure.kind === "pi-failed" || result.outcome === "native-operation-failed" || result.outcome === "native-status-unavailable" || result.outcome === "native-status-failed") {
89
+ return diagnose("provider-unavailable", "unknown", "Inspect the returned phase and sanitized diagnostics. A timeout alone does not identify a lock or permit a retry; follow the returned native action.");
90
+ }
91
+ return diagnose("diagnosis-required", "unknown", "Use the structured diagnostic and the supported continuation to identify the cause. No maintainer intervention, retry or authority mutation is implied.");
92
+ }
@@ -0,0 +1,136 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { closeSync, fstatSync, lstatSync, openSync, opendirSync, readSync, realpathSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { CANDIDATE_GIT_MAX_BUFFER_BYTES, resolveCandidateGitTimeoutMs, type CandidateGitExecutor } from "./review-candidate-view.ts";
5
+
6
+ export type CandidateTreeSymlinkScan = "tracks-symlinks" | "no-symlinks" | "unconfirmed";
7
+ type DefinitiveScan = Exclude<CandidateTreeSymlinkScan, "unconfirmed">;
8
+ const MAX_REF_METADATA_BYTES = 1024 * 1024;
9
+
10
+ /** Read exactly the inspected size; concurrent size changes make eligibility unknown. */
11
+ function readBoundedFile(path: string, size: number): string | undefined {
12
+ const fd = openSync(path, "r");
13
+ try {
14
+ // A concurrent grow/replacement must not turn a small supported read
15
+ // into unbounded allocation or a truncated cache eligibility answer.
16
+ const bytes = Buffer.alloc(size + 1);
17
+ const length = readSync(fd, bytes, 0, bytes.length, 0);
18
+ return length === size && fstatSync(fd).size === size ? bytes.subarray(0, length).toString("utf8") : undefined;
19
+ } finally { closeSync(fd); }
20
+ }
21
+
22
+ /** Fingerprint ref/config metadata without following a symbolic link. */
23
+ function identity(path: string): string | undefined {
24
+ const value = lstatSync(path, { bigint: true, throwIfNoEntry: false });
25
+ return value === undefined ? undefined : [value.dev, value.ino, value.size, value.mtimeNs, value.ctimeNs].join(":");
26
+ }
27
+
28
+ /** Accept only the bounded, sorted files-backend format with no replacement refs. */
29
+ function isCanonicalPackedRefs(contents: string): boolean {
30
+ if (!contents.endsWith("\n")) return false;
31
+ const lines = contents.split("\n");
32
+ if (!/^# pack-refs with: (?:peeled )?(?:fully-peeled )?sorted $/.test(lines.shift() ?? "")) return false;
33
+ lines.pop(); // The required final newline is not an empty ref record.
34
+ let previousName = "", peelable = false, oidLength = 0;
35
+ for (const line of lines) {
36
+ if (line.startsWith("^")) {
37
+ if (!peelable || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(line.slice(1)) || line.length !== oidLength + 1) return false;
38
+ peelable = false; continue;
39
+ }
40
+ const match = /^([0-9a-f]{40}|[0-9a-f]{64}) (refs\/[A-Za-z0-9._/-]+)$/.exec(line);
41
+ if (match === null) return false;
42
+ const [, oid, name] = match;
43
+ if (name.includes("..") || name.split("/").some(part => part === "" || part.startsWith(".") || part.endsWith(".") || part.endsWith(".lock"))
44
+ || name.startsWith("refs/replace/") || name <= previousName || (oidLength !== 0 && oid.length !== oidLength)) return false;
45
+ previousName = name; oidLength = oid.length; peelable = name.startsWith("refs/tags/");
46
+ }
47
+ return true;
48
+ }
49
+
50
+ /** Default files backend only; uncertain configuration is never cache authority. */
51
+ function replacementFreeView(commonDir: string): string | undefined {
52
+ const config = join(commonDir, "config");
53
+ const beforeConfig = identity(config);
54
+ const configDetails = lstatSync(config);
55
+ if (!configDetails.isFile() || configDetails.isSymbolicLink() || configDetails.size > MAX_REF_METADATA_BYTES) return undefined;
56
+ const configContents = readBoundedFile(config, configDetails.size);
57
+ // Includes and an explicitly selected backend need Git interpretation;
58
+ // retaining an uncached scan avoids implementing its configuration parser.
59
+ if (configContents === undefined || /refstorage|\[\s*include/i.test(configContents)) return undefined;
60
+ const refs = lstatSync(join(commonDir, "refs"));
61
+ if (!refs.isDirectory() || refs.isSymbolicLink() || lstatSync(join(commonDir, "reftable"), { throwIfNoEntry: false }) !== undefined) return undefined;
62
+ const loose = join(commonDir, "refs", "replace");
63
+ const beforeLoose = identity(loose);
64
+ if (beforeLoose !== undefined) {
65
+ const details = lstatSync(loose);
66
+ if (!details.isDirectory() || details.isSymbolicLink()) return undefined;
67
+ const directory = opendirSync(loose);
68
+ try { if (directory.readSync() !== null) return undefined; } finally { directory.closeSync(); }
69
+ }
70
+ const packed = join(commonDir, "packed-refs");
71
+ const beforePacked = identity(packed);
72
+ if (beforePacked !== undefined) {
73
+ const details = lstatSync(packed);
74
+ if (!details.isFile() || details.isSymbolicLink() || details.size > MAX_REF_METADATA_BYTES) return undefined;
75
+ const contents = readBoundedFile(packed, details.size);
76
+ if (contents === undefined || !isCanonicalPackedRefs(contents)) return undefined;
77
+ }
78
+ return beforeLoose === identity(loose) && beforePacked === identity(packed) && beforeConfig === identity(config) ? beforeConfig : undefined;
79
+ }
80
+
81
+ /** Discovery only: materialization, filesystem identity and authority stay fresh. */
82
+ export class CandidateTreeSymlinkScanner {
83
+ private readonly entries = new Map<string, DefinitiveScan>();
84
+ private readonly execute: CandidateGitExecutor;
85
+ private readonly capacity: number;
86
+ constructor(execute: CandidateGitExecutor = (file, args, options) => execFileSync(file, args, options), capacity = 128) {
87
+ if (!Number.isSafeInteger(capacity) || capacity < 1) throw new TypeError("Invalid scan cache capacity");
88
+ this.execute = execute;
89
+ this.capacity = capacity;
90
+ }
91
+
92
+ /** Reuse definitive literal-tree scans only while fresh local metadata proves eligibility. */
93
+ scan(cwd: string, candidateTree: string, verifiedCommonDir?: string): CandidateTreeSymlinkScan {
94
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toUpperCase().startsWith("GIT_")));
95
+ const options = { cwd, env, encoding: "utf8" as const, windowsHide: true,
96
+ stdio: ["ignore", "pipe", "pipe"] as ["ignore", "pipe", "pipe"],
97
+ timeout: resolveCandidateGitTimeoutMs(), maxBuffer: CANDIDATE_GIT_MAX_BUFFER_BYTES };
98
+ let key: string | undefined;
99
+ try {
100
+ if (verifiedCommonDir !== undefined && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(candidateTree)) {
101
+ const root = realpathSync(cwd);
102
+ const common = realpathSync(verifiedCommonDir);
103
+ // No extra Git process on a warm scan. Unknown backend, oversized
104
+ // or malformed refs and active replacements always scan uncached.
105
+ const view = replacementFreeView(common);
106
+ if (view !== undefined) key = `${root}\0${common}\0${view}\0${candidateTree}`;
107
+ }
108
+ } catch { /* An unavailable cache eligibility check never borrows old data. */ }
109
+ if (key !== undefined) {
110
+ const cached = this.entries.get(key);
111
+ if (cached !== undefined) {
112
+ this.entries.delete(key); this.entries.set(key, cached);
113
+ return cached;
114
+ }
115
+ }
116
+ try {
117
+ // Cache only literal object contents: a replacement appearing during
118
+ // this scan cannot poison the reusable answer. With active/unknown
119
+ // replacements keep the original Git interpretation instead.
120
+ const listing = this.execute("git", [...(key === undefined ? [] : ["--no-replace-objects"]),
121
+ "ls-tree", "-r", "--full-tree", candidateTree], options).toString();
122
+ const result: DefinitiveScan = listing.split("\n").some(line => line.startsWith("120000 ")) ? "tracks-symlinks" : "no-symlinks";
123
+ if (key !== undefined) {
124
+ this.entries.set(key, result);
125
+ if (this.entries.size > this.capacity) this.entries.delete(this.entries.keys().next().value!);
126
+ }
127
+ return result;
128
+ } catch { return "unconfirmed"; }
129
+ }
130
+ }
131
+
132
+ const scanner = new CandidateTreeSymlinkScanner();
133
+ /** Classify a tree for discovery; an unconfirmed scan never authorizes materialization. */
134
+ export function scanCandidateTreeForSymlinks(cwd: string, candidateTree: string, verifiedCommonDir?: string): CandidateTreeSymlinkScan {
135
+ return scanner.scan(cwd, candidateTree, verifiedCommonDir);
136
+ }
@@ -28,7 +28,7 @@ const WINDOWS_ADMINISTRATORS = "S-1-5-32-544";
28
28
  const WINDOWS_SYSTEM_DIRECTORY = "\\\\?\\GLOBALROOT\\SystemRoot\\System32";
29
29
 
30
30
  // Cold or contended Windows hosts can take several seconds to start a process
31
- // (whoami/PowerShell/icacls), and owner preparation runs many probes in
31
+ // (whoami/PowerShell), and owner preparation runs many probes in
32
32
  // sequence. Each probe gets a bounded, configurable timeout, plus one bounded
33
33
  // retry of the idempotent system probe; authority validation is never retried
34
34
  // or weakened because it happens after the probe returns.
@@ -56,7 +56,7 @@ export function withWindowsSystemProbeRetry<T>(probe: () => T): T {
56
56
  }
57
57
  }
58
58
 
59
- function windowsSystemExecutable(name: "whoami.exe" | "icacls.exe" | "WindowsPowerShell\\v1.0\\powershell.exe"): string {
59
+ function windowsSystemExecutable(name: "whoami.exe" | "WindowsPowerShell\\v1.0\\powershell.exe"): string {
60
60
  try {
61
61
  return realpathSync.native(join(WINDOWS_SYSTEM_DIRECTORY, name));
62
62
  } catch {
@@ -71,28 +71,6 @@ function windowsUserSid(): string {
71
71
  return matches[0]!.toUpperCase();
72
72
  }
73
73
 
74
- function windowsLocalAdministratorSid(): string {
75
- const script = "$ErrorActionPreference='Stop';$descriptor=New-Object System.Security.AccessControl.RawSecurityDescriptor 'D:(A;;FA;;;LA)';$descriptor.DiscretionaryAcl[0].SecurityIdentifier.Value";
76
- const systemRoot = dirname(dirname(windowsSystemExecutable("whoami.exe")));
77
- const output = withWindowsSystemProbeRetry(() => execFileSync(windowsSystemExecutable("WindowsPowerShell\\v1.0\\powershell.exe"), ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { encoding: "utf8", timeout: resolveWindowsSystemProbeTimeoutMs(), maxBuffer: 4096, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, env: { ...process.env, SystemRoot: systemRoot } }));
78
- const matches = output.match(/S-\d+(?:-\d+)+/gi) ?? [];
79
- if (matches.length !== 1 || !isWindowsSid(matches[0]!)) throw new Error("Windows local Administrator SID is unavailable");
80
- return matches[0]!.toUpperCase();
81
- }
82
-
83
- function windowsDacl(path: string): string {
84
- const archive = `.gentle-ai-acl-${randomUUID()}.txt`;
85
- const archivePath = join(dirname(path), archive);
86
- try {
87
- withWindowsSystemProbeRetry(() => execFileSync(windowsSystemExecutable("icacls.exe"), [path, "/save", archive, "/c"], { cwd: dirname(path), encoding: "utf8", timeout: resolveWindowsSystemProbeTimeoutMs(), maxBuffer: 16384, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }));
88
- const sddl = readFileSync(archivePath, "utf16le").match(/D:[^\r\n]+/)?.[0];
89
- if (sddl === undefined) throw new Error("Windows DACL is unavailable");
90
- return sddl;
91
- } finally {
92
- try { unlinkSync(archivePath); } catch {}
93
- }
94
- }
95
-
96
74
  export type WindowsDaclValidationReason = "protection" | "ace-count" | "ace-shape" | "ace-type" | "ace-flags" | "ace-rights" | "ace-reserved-fields" | "ace-trustee" | "ace-duplicate";
97
75
  export type WindowsDaclTrusteeClassification = "OW" | "CO" | "BU" | "AU" | "WD" | "LA" | "sid" | "other" | "missing";
98
76
 
@@ -168,8 +146,68 @@ interface WindowsAclIdentity {
168
146
 
169
147
  type WindowsObjectKind = "file" | "directory";
170
148
 
171
- function windowsAclIdentity(): WindowsAclIdentity {
172
- return { user: windowsUserSid(), localAdministrator: windowsLocalAdministratorSid() };
149
+ interface WindowsAclProbeSnapshot extends WindowsAclIdentity {
150
+ entries: readonly { index: number; owner: string; dacl: string }[];
151
+ }
152
+
153
+ export function decodeWindowsAclProbe(payload: string, count: number): WindowsAclProbeSnapshot {
154
+ const invalid = () => new Error("Windows ACL probe response is invalid");
155
+ if (!Number.isInteger(count) || count < 1 || count > 3 || payload.length > 65536) throw invalid();
156
+ let parsed: unknown;
157
+ try { parsed = JSON.parse(payload); } catch { throw invalid(); }
158
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw invalid();
159
+ const value = parsed as Record<string, unknown>;
160
+ if (Object.keys(value).sort().join(",") !== "entries,localAdministrator,schema,user" || value.schema !== "gentle-pi.windows-acl-probe/v1" ||
161
+ typeof value.user !== "string" || !isWindowsSid(value.user) || typeof value.localAdministrator !== "string" || !isWindowsSid(value.localAdministrator) ||
162
+ !Array.isArray(value.entries) || value.entries.length !== count) throw invalid();
163
+ const entries = value.entries.map((entry: unknown, index) => {
164
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) throw invalid();
165
+ const item = entry as Record<string, unknown>;
166
+ if (Object.keys(item).sort().join(",") !== "dacl,index,owner" || item.index !== index || typeof item.owner !== "string" || !isWindowsSid(item.owner) ||
167
+ typeof item.dacl !== "string" || item.dacl.length === 0 || item.dacl.length > 16384) throw invalid();
168
+ return { index, owner: item.owner.toUpperCase(), dacl: item.dacl };
169
+ });
170
+ return { user: value.user.toUpperCase(), localAdministrator: value.localAdministrator.toUpperCase(), entries };
171
+ }
172
+
173
+ // One fresh, read-only observation per synchronous boundary. Never retain a
174
+ // snapshot across calls, Git or makeWritable callbacks. Paths travel through
175
+ // UTF-8 stdin, not interpolated script text or length-limited environment values.
176
+ function windowsAclProbe(requests: readonly { path: string; kind: WindowsObjectKind }[]): WindowsAclProbeSnapshot {
177
+ if (requests.length < 1 || requests.length > 3 || requests.some(request => request.path.length === 0 || request.path.length > 32767 || request.path.includes("\0") || !["file", "directory"].includes(request.kind))) throw new WindowsOwnerValidationError();
178
+ const script = `$ErrorActionPreference='Stop'
179
+ $ProgressPreference='SilentlyContinue'
180
+ [Console]::InputEncoding=[System.Text.Encoding]::UTF8
181
+ [object[]]$requests=ConvertFrom-Json -InputObject ([Console]::In.ReadToEnd())
182
+ $user=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
183
+ $descriptor=New-Object System.Security.AccessControl.RawSecurityDescriptor 'D:(A;;FA;;;LA)'
184
+ $administrator=$descriptor.DiscretionaryAcl[0].SecurityIdentifier.Value
185
+ $sections=[System.Security.AccessControl.AccessControlSections]::Owner -bor [System.Security.AccessControl.AccessControlSections]::Access
186
+ $entries=@(for($i=0;$i -lt $requests.Count;$i++) {
187
+ $request=$requests[$i]
188
+ if($request.kind -eq 'file') { $acl=[System.IO.File]::GetAccessControl($request.path,$sections) }
189
+ elseif($request.kind -eq 'directory') { $acl=[System.IO.Directory]::GetAccessControl($request.path,$sections) }
190
+ else { throw 'Invalid object kind' }
191
+ [pscustomobject]@{index=$i;owner=$acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value;dacl=$acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)}
192
+ })
193
+ @{schema='gentle-pi.windows-acl-probe/v1';user=$user;localAdministrator=$administrator;entries=$entries} | ConvertTo-Json -Compress -Depth 4`;
194
+ const systemRoot = dirname(dirname(windowsSystemExecutable("whoami.exe")));
195
+ let output: string;
196
+ try {
197
+ output = withWindowsSystemProbeRetry(() => execFileSync(windowsSystemExecutable("WindowsPowerShell\\v1.0\\powershell.exe"), ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { encoding: "utf8", input: JSON.stringify(requests), timeout: resolveWindowsSystemProbeTimeoutMs(), maxBuffer: 65536, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, env: { ...process.env, SystemRoot: systemRoot } }));
198
+ } catch { throw new WindowsOwnerValidationError(); }
199
+ // Invalid responses and authority failures are validated outside the retry.
200
+ return decodeWindowsAclProbe(output, requests.length);
201
+ }
202
+
203
+ function assertWindowsAclObservations(requests: readonly { path: string; kind: WindowsObjectKind; protectedDacl: boolean }[], identity?: WindowsAclIdentity): WindowsAclIdentity {
204
+ const snapshot = windowsAclProbe(requests);
205
+ if (identity !== undefined && (snapshot.user !== identity.user || snapshot.localAdministrator !== identity.localAdministrator)) throw new WindowsOwnerValidationError();
206
+ for (const entry of snapshot.entries) {
207
+ validatePrivateWindowsOwner(entry.owner, snapshot.user);
208
+ validatePrivateWindowsDacl(entry.dacl, snapshot.user, requests[entry.index]!.protectedDacl, snapshot.localAdministrator);
209
+ }
210
+ return { user: snapshot.user, localAdministrator: snapshot.localAdministrator };
173
211
  }
174
212
 
175
213
  function windowsOwnerSid(path: string, kind: WindowsObjectKind): string {
@@ -193,12 +231,11 @@ export function assertTrustedWindowsOwner(path: string, kind: WindowsObjectKind)
193
231
  validatePrivateWindowsOwner(windowsOwnerSid(path, kind), windowsUserSid());
194
232
  }
195
233
 
196
- function assertPrivateWindowsDacl(path: string, kind: WindowsObjectKind, protectedDacl: boolean, identity: WindowsAclIdentity = windowsAclIdentity()): void {
197
- validatePrivateWindowsOwner(windowsOwnerSid(path, kind), identity.user);
198
- validatePrivateWindowsDacl(windowsDacl(path), identity.user, protectedDacl, identity.localAdministrator);
234
+ function assertPrivateWindowsDacl(path: string, kind: WindowsObjectKind, protectedDacl: boolean, identity?: WindowsAclIdentity): void {
235
+ assertWindowsAclObservations([{ path, kind, protectedDacl }], identity);
199
236
  }
200
237
 
201
- function enforcePrivateWindowsDacl(path: string, identity: WindowsAclIdentity = windowsAclIdentity()): void {
238
+ function enforcePrivateWindowsDacl(path: string, identity: WindowsAclIdentity): void {
202
239
  validatePrivateWindowsOwner(windowsOwnerSid(path, "directory"), identity.user);
203
240
  const { user, localAdministrator } = identity;
204
241
  const sddl = `D:P(A;OICI;FA;;;${user})(A;OICI;FA;;;${WINDOWS_SYSTEM})(A;OICI;FA;;;${WINDOWS_ADMINISTRATORS})`;
@@ -208,25 +245,26 @@ function enforcePrivateWindowsDacl(path: string, identity: WindowsAclIdentity =
208
245
  assertPrivateWindowsDacl(path, "directory", true, identity);
209
246
  }
210
247
 
211
- function privateWindowsDacl(path: string, kind: WindowsObjectKind, protectedDacl: boolean, enforce = false, windowsIdentity?: WindowsAclIdentity): void {
248
+ function privateWindowsDacl(path: string, kind: WindowsObjectKind, protectedDacl: boolean, windowsIdentity?: WindowsAclIdentity): void {
212
249
  if (testingWindowsAclAuthority !== undefined) return testingWindowsAclAuthority(path);
213
- if (enforce) enforcePrivateWindowsDacl(path, windowsIdentity);
214
- else assertPrivateWindowsDacl(path, kind, protectedDacl, windowsIdentity);
250
+ assertPrivateWindowsDacl(path, kind, protectedDacl, windowsIdentity);
215
251
  }
216
252
 
217
- function privateWindowsCandidateOwnerBoundary(commonDir: string, enforce = false, windowsIdentity?: WindowsAclIdentity): void {
253
+ function privateWindowsCandidateOwnerBoundary(commonDir: string, enforce = false): WindowsAclIdentity | undefined {
218
254
  const boundary = [commonDir, join(commonDir, "gentle-ai"), join(commonDir, "gentle-ai", "candidate-views")];
219
255
  if (testingWindowsAclAuthority !== undefined) {
220
256
  for (const path of boundary) testingWindowsAclAuthority(path);
221
257
  return;
222
258
  }
223
- const identity = windowsIdentity ?? windowsAclIdentity();
224
- if (enforce) {
225
- for (const path of boundary) validatePrivateWindowsOwner(windowsOwnerSid(path, "directory"), identity.user);
226
- for (const path of boundary) enforcePrivateWindowsDacl(path, identity);
227
- return;
228
- }
229
- for (const path of boundary) assertPrivateWindowsDacl(path, "directory", true, identity);
259
+ if (!enforce) return assertWindowsAclObservations(boundary.map(path => ({ path, kind: "directory", protectedDacl: true })));
260
+ // Take the identity from the same probe that later reads owners and DACLs
261
+ // back, so enforcement never compares two different identity sources. The
262
+ // DACLs are not validated yet: this boundary is about to rewrite them.
263
+ const snapshot = windowsAclProbe(boundary.map(path => ({ path, kind: "directory" })));
264
+ const identity = { user: snapshot.user, localAdministrator: snapshot.localAdministrator };
265
+ for (const entry of snapshot.entries) validatePrivateWindowsOwner(entry.owner, identity.user);
266
+ for (const path of boundary) enforcePrivateWindowsDacl(path, identity);
267
+ return identity;
230
268
  }
231
269
 
232
270
  // A hostname or a repository-local nonce cannot prove that a PID is local.
@@ -311,8 +349,7 @@ function checkedCandidateOwnerParent(commonDir: string, platform: NodeJS.Platfor
311
349
  const parent = join(commonDir, "gentle-ai", "candidate-views");
312
350
  if (platform === "win32") {
313
351
  directory(parent, false, platform);
314
- const windowsIdentity = testingWindowsAclAuthority === undefined ? windowsAclIdentity() : undefined;
315
- privateWindowsCandidateOwnerBoundary(commonDir, false, windowsIdentity);
352
+ const windowsIdentity = privateWindowsCandidateOwnerBoundary(commonDir);
316
353
  return { parent, windowsIdentity };
317
354
  }
318
355
  directory(parent, true, platform, true);
@@ -342,7 +379,7 @@ function regular(path: string, privateMode = false, platform: NodeJS.Platform =
342
379
  const uid = process.getuid?.();
343
380
  if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1n || !samePath(realpathSync(path), path, platform) || stat.size > 16384n ||
344
381
  (privateMode && platform !== "win32" && (uid === undefined || stat.uid !== BigInt(uid) || (stat.mode & 0o777n) !== 0o600n))) throw new Error("Unsafe candidate owner file");
345
- if (privateMode && platform === "win32") privateWindowsDacl(path, "file", false, false, windowsIdentity);
382
+ if (privateMode && platform === "win32") privateWindowsDacl(path, "file", false, windowsIdentity);
346
383
  return `${stat.dev}:${stat.ino}`;
347
384
  }
348
385