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,99 @@
1
+ import type { NativeIntendedUntrackedSelectionSubmission } from "./native-review-cli.ts";
2
+ import type { ReviewStartContext } from "./review-start-context.ts";
3
+
4
+ export interface RetainedNativeUntrackedSelection {
5
+ readonly untrackedScope: "exclude" | "select";
6
+ readonly expectedUntrackedInventory: string;
7
+ readonly intendedUntracked: readonly string[];
8
+ readonly submission?: NativeIntendedUntrackedSelectionSubmission;
9
+ }
10
+ export interface RetainedPreLineageNativeUntrackedSelection {
11
+ readonly untrackedScope?: "exclude" | "select";
12
+ readonly expectedUntrackedInventory?: string;
13
+ readonly intendedUntracked?: readonly string[];
14
+ readonly submission?: NativeIntendedUntrackedSelectionSubmission;
15
+ readonly targetIdentity: string;
16
+ readonly candidateTree: string;
17
+ readonly baseRef?: string;
18
+ readonly committedOnly?: true;
19
+ }
20
+ export interface RetainedNativeCaptureRoute {
21
+ readonly workspaceRoot: string;
22
+ readonly lineageId: string;
23
+ readonly targetIdentity: string;
24
+ readonly baseRef?: string;
25
+ readonly committedOnly?: true;
26
+ }
27
+ export interface RetainedNativeUntrackedStopSelector {
28
+ readonly selectionBinding: string;
29
+ readonly targetIdentity: string;
30
+ readonly baseRef?: string;
31
+ readonly committedOnly?: true;
32
+ readonly startContext?: ReviewStartContext;
33
+ }
34
+
35
+ export type RetainedReviewContinuation =
36
+ | (RetainedNativeUntrackedSelection & { readonly kind: "selection" })
37
+ | (RetainedPreLineageNativeUntrackedSelection & { readonly kind: "pre-start" })
38
+ | (RetainedNativeCaptureRoute & { readonly kind: "capture" })
39
+ | (RetainedNativeUntrackedStopSelector & { readonly kind: "stop" });
40
+
41
+ const lifecycleKey = (root: string, lineage: string) => `${root}\u0000${lineage}`;
42
+ const captureKey = (binding: string) => `capture\u0000${binding}`;
43
+ const MAX_RETAINED_CONTINUATIONS = 64;
44
+ /** Strip the private discriminator from a retained routing payload. */
45
+ function payload<T extends RetainedReviewContinuation>(entry: T): Omit<T, "kind"> {
46
+ const { kind: _kind, ...value } = entry;
47
+ return value;
48
+ }
49
+
50
+ /** Process-local routing hints only. Native STATUS remains the authority. */
51
+ export class ReviewContinuationRegistry {
52
+ private readonly entries: Map<string, RetainedReviewContinuation>;
53
+ // Optional backing map keeps the existing __testing seam on this same store,
54
+ // without copying state or maintaining a second representation.
55
+ constructor(entries = new Map<string, RetainedReviewContinuation>()) { this.entries = entries; }
56
+ /** Reuse a registry or wrap the legacy backing map without copying state. */
57
+ static from(value: ReviewContinuationRegistry | Map<string, RetainedReviewContinuation>): ReviewContinuationRegistry {
58
+ return value instanceof ReviewContinuationRegistry ? value : new ReviewContinuationRegistry(value);
59
+ }
60
+ get size(): number { return this.entries.size; }
61
+ /** Bound retained hints by evicting the oldest key before a new insertion. */
62
+ private retain(key: string, entry: RetainedReviewContinuation): void {
63
+ if (!this.entries.has(key)) while (this.entries.size >= MAX_RETAINED_CONTINUATIONS) this.entries.delete(this.entries.keys().next().value!);
64
+ this.entries.set(key, Object.freeze(entry));
65
+ }
66
+ readSelection(root: string, lineage: string): RetainedNativeUntrackedSelection | undefined {
67
+ const entry = this.entries.get(lifecycleKey(root, lineage));
68
+ return entry?.kind === "selection" ? payload(entry) : undefined;
69
+ }
70
+ readPreStart(root: string): RetainedPreLineageNativeUntrackedSelection | undefined {
71
+ const entry = this.entries.get(lifecycleKey(root, ""));
72
+ return entry?.kind === "pre-start" ? payload(entry) : undefined;
73
+ }
74
+ readStop(root: string): RetainedNativeUntrackedStopSelector | undefined {
75
+ const entry = this.entries.get(lifecycleKey(root, ""));
76
+ return entry?.kind === "stop" ? payload(entry) : undefined;
77
+ }
78
+ readCapture(binding: string): RetainedNativeCaptureRoute | undefined {
79
+ const entry = this.entries.get(captureKey(binding));
80
+ return entry?.kind === "capture" ? payload(entry) : undefined;
81
+ }
82
+ retainSelection(root: string, lineage: string, value: RetainedNativeUntrackedSelection): void {
83
+ this.retain(lifecycleKey(root, lineage), { ...value, kind: "selection" });
84
+ }
85
+ retainPreStart(root: string, value: RetainedPreLineageNativeUntrackedSelection): void {
86
+ this.retain(lifecycleKey(root, ""), { ...value, kind: "pre-start" });
87
+ }
88
+ retainStop(root: string, value: RetainedNativeUntrackedStopSelector): void {
89
+ this.retain(lifecycleKey(root, ""), { ...value, kind: "stop" });
90
+ }
91
+ retainCapture(binding: string, value: RetainedNativeCaptureRoute): void {
92
+ this.retain(captureKey(binding), { ...value, kind: "capture" });
93
+ }
94
+ clearSelection(root: string, lineage: string): void { this.entries.delete(lifecycleKey(root, lineage)); }
95
+ clearCaptureRoutes(root: string, lineage: string, keepBindings: readonly string[] = []): void {
96
+ const keepKeys = new Set(keepBindings.map(captureKey));
97
+ for (const [key, entry] of this.entries) if (entry.kind === "capture" && entry.workspaceRoot === root && entry.lineageId === lineage && !keepKeys.has(key)) this.entries.delete(key);
98
+ }
99
+ }
@@ -0,0 +1,163 @@
1
+ /** Experimental host orchestration. All authority stays in the existing facade. */
2
+ export type ReviewCoordinatorTool = "gentle_review" | "gentle_review_capture" | "gentle_review_capture_group";
3
+ type Body = Record<string, unknown>;
4
+ const record = (value: unknown): Body => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Body : {};
5
+ const nonempty = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
6
+
7
+ export interface ReviewCoordinatorInput {
8
+ workspaceRoot?: string;
9
+ baseRef?: string;
10
+ committedOnly?: true;
11
+ lineageId?: string;
12
+ lenses?: string[];
13
+ lensesReason?: string;
14
+ requestContextPath?: string;
15
+ untrackedScope?: "exclude" | "select";
16
+ intendedUntracked?: string[];
17
+ }
18
+
19
+ export interface ReviewCoordinatorDeps {
20
+ invoke(tool: ReviewCoordinatorTool, parameters: Body): Promise<Body>;
21
+ /** True only after the host has displayed the entire informational forecast. */
22
+ presentForecast?(details: Body): Promise<boolean>;
23
+ signal?: AbortSignal;
24
+ now?: () => number;
25
+ }
26
+
27
+ export function parseReviewCoordinatorInput(value: unknown): ReviewCoordinatorInput {
28
+ const input = record(value);
29
+ if (input !== value) throw new Error("Review coordinator input must be an object");
30
+ const allowed = ["workspaceRoot", "baseRef", "committedOnly", "lineageId", "lenses", "lensesReason", "requestContextPath", "untrackedScope", "intendedUntracked"];
31
+ if (Object.keys(input).some((key) => !allowed.includes(key))) throw new Error("Unsupported review coordinator input");
32
+ for (const key of ["workspaceRoot", "baseRef", "lineageId", "lensesReason"]) {
33
+ if (input[key] !== undefined && !nonempty(input[key])) throw new Error(`${key} must be nonempty`);
34
+ }
35
+ if ((input.baseRef !== undefined) !== (input.committedOnly === true) || (input.committedOnly !== undefined && input.committedOnly !== true)) throw new Error("baseRef requires committedOnly: true and vice versa");
36
+ if ((input.lenses !== undefined) !== (input.lensesReason !== undefined)) throw new Error("lenses and lensesReason must be supplied together");
37
+ if (input.requestContextPath !== undefined && (!nonempty(input.requestContextPath) || input.requestContextPath.trim() !== input.requestContextPath || input.requestContextPath.includes("\0"))) throw new Error("Invalid requestContextPath");
38
+ if (input.requestContextPath !== undefined && input.lineageId !== undefined) throw new Error("requestContextPath requires a fresh review; existing lineage intent is immutable");
39
+ if (input.lenses !== undefined && (!Array.isArray(input.lenses) || input.lenses.length < 1 || input.lenses.length > 4 || !input.lenses.every((lens) => ["risk", "resilience", "readability", "reliability"].includes(lens)) || new Set(input.lenses).size !== input.lenses.length)) throw new Error("Invalid review lenses");
40
+ if (input.untrackedScope !== undefined && !["exclude", "select"].includes(String(input.untrackedScope))) throw new Error("Invalid untrackedScope");
41
+ if (input.untrackedScope === "select" && (!Array.isArray(input.intendedUntracked) || !input.intendedUntracked.every(nonempty))) throw new Error("select requires intendedUntracked");
42
+ if (input.intendedUntracked !== undefined && input.untrackedScope !== "select") throw new Error("intendedUntracked requires select");
43
+ return input as ReviewCoordinatorInput;
44
+ }
45
+
46
+ /** Follow bounded native continuations while retaining informational reviewer facts. */
47
+ export async function runReviewCoordinator(value: unknown, deps: ReviewCoordinatorDeps): Promise<Body> {
48
+ const input = parseReviewCoordinatorInput(value);
49
+ const now = deps.now ?? (() => performance.now());
50
+ const began = now();
51
+ const steps: Body[] = [];
52
+ const forecasts: Body[] = [];
53
+ const reviewerRuns: Body[] = [];
54
+ const workspace = input.workspaceRoot === undefined ? {} : { workspaceRoot: input.workspaceRoot };
55
+ const selector = input.baseRef === undefined ? {} : { baseRef: input.baseRef, committedOnly: true };
56
+ const selectorInput = input.baseRef === undefined ? {} : { input: JSON.stringify(selector) };
57
+ let lineage = input.lineageId;
58
+ let target: string | undefined;
59
+ let started = false;
60
+ const captured = new Set<string>();
61
+ const checkCancelled = () => {
62
+ if (deps.signal?.aborted) throw Object.assign(new Error("Review coordinator cancelled"), { name: "AbortError" });
63
+ };
64
+ const acknowledged = (body: Body) => body.outcome === "native-approved-acknowledgement-completed"
65
+ && body.status === "closed" && body.authority === "burned";
66
+ /** Record facade timing and evidence without changing routing or native authority. */
67
+ const invoke = async (tool: ReviewCoordinatorTool, parameters: Body) => {
68
+ checkCancelled();
69
+ const start = now();
70
+ const result = await deps.invoke(tool, { ...workspace, ...parameters });
71
+ if (result.outcome === "reviewer-model-run-forecast") forecasts.push(structuredClone(result));
72
+ if (tool !== "gentle_review" && result.outcome !== "reviewer-model-run-forecast") {
73
+ // Informational snapshots only: never route or total SDK cost from these.
74
+ // The transition limit bounds retention to this invocation. A group's new
75
+ // all-prepared records supersede its submitted-only legacy reviewers array.
76
+ const relay = record(result.host_relay);
77
+ if (Array.isArray(relay.reviewer_runs) && relay.reviewer_runs.length > 0) reviewerRuns.push(...structuredClone(relay.reviewer_runs.map(record)));
78
+ else if (relay.reviewer !== undefined) {
79
+ const facts = Object.fromEntries(["lens", "order", "subject_hash", "role", "prompt_bytes", "result_bytes"]
80
+ .filter(key => relay[key] !== undefined).map(key => [key, relay[key]]));
81
+ reviewerRuns.push(structuredClone({ ...facts, reviewer: relay.reviewer }));
82
+ } else if (record(result.failure).reviewer !== undefined) reviewerRuns.push(structuredClone({ reviewer: record(result.failure).reviewer }));
83
+ }
84
+ steps.push({ tool, operation: parameters.operation, elapsed_ms: now() - start,
85
+ request_bytes: Buffer.byteLength(JSON.stringify({ ...workspace, ...parameters })), response_bytes: Buffer.byteLength(JSON.stringify(result)) });
86
+ if (!acknowledged(result)) checkCancelled();
87
+ return result;
88
+ };
89
+ const finish = (outcome: string, result: Body) => ({ schema: "gentle-pi.review-coordinator-experiment/v1", outcome, result, forecasts, reviewer_runs: reviewerRuns,
90
+ ...(lineage === undefined ? {} : { lineage_id: lineage }), metrics: { elapsed_ms: now() - began, facade_calls: steps.length, steps } });
91
+ const status = () => invoke("gentle_review", { operation: "status", lineageId: lineage, ...selectorInput });
92
+ let details: Body;
93
+ if (lineage === undefined) {
94
+ const assessment = await invoke("gentle_review", { operation: "assess", ...selectorInput });
95
+ if (assessment.reviewDue === false && input.requestContextPath !== undefined) return finish("request-context-requires-fresh-review", assessment);
96
+ if (assessment.reviewDue !== true) return finish(assessment.reviewDue === false ? "not-due" : "assessment-unavailable", assessment);
97
+ details = await invoke("gentle_review", { operation: "inspect", ...selectorInput,
98
+ ...(input.untrackedScope === undefined ? {} : { untrackedScope: input.untrackedScope }),
99
+ ...(input.intendedUntracked === undefined ? {} : { intendedUntracked: input.intendedUntracked }) });
100
+ } else details = await status();
101
+ for (let count = 0; count < 24; count++) {
102
+ // Only STATUS/INSPECT supplies routing. Capture response state and native
103
+ // reason codes never participate in host decisions.
104
+ checkCancelled();
105
+ const native = record(details.result);
106
+ const offeredLineage = native.lineage_id ?? record(native.authority).lineage_id;
107
+ if (nonempty(offeredLineage)) {
108
+ if (input.requestContextPath !== undefined && !started) return finish("request-context-requires-fresh-review", details);
109
+ if (lineage !== undefined && lineage !== offeredLineage) return finish("binding-drift", details);
110
+ lineage = offeredLineage;
111
+ }
112
+ if (nonempty(native.target_identity)) {
113
+ if (target !== undefined && target !== native.target_identity) return finish("binding-drift", details);
114
+ target = native.target_identity;
115
+ }
116
+ if (details.failure !== undefined || details.native_failure !== undefined || details.reconciliation !== undefined || details.reconciliation_failure !== undefined) return finish("blocked", details);
117
+ const transition = record(native.next_transition);
118
+ if (transition.kind === "stop") return finish("stopped", details);
119
+ if (transition.kind === "execute") {
120
+ const operation = record(transition.execute).operation;
121
+ if (operation === "review.start") {
122
+ if (started || lineage !== undefined) return finish("blocked", details);
123
+ started = true;
124
+ details = await invoke("gentle_review", { operation: "start", input: JSON.stringify({ mode: "ordinary", ...selector,
125
+ ...(input.requestContextPath === undefined ? {} : { requestContextPath: input.requestContextPath }),
126
+ ...(input.lenses === undefined ? {} : { lenses: input.lenses, lensesReason: input.lensesReason }) }) });
127
+ if (details.outcome === "native-review-consent-required") return finish("consent-required", details);
128
+ const issued = record(details.result).lineage_id;
129
+ if (!nonempty(issued)) return finish("blocked", details);
130
+ lineage = issued;
131
+ } else if (operation === "review.acknowledge-approved") {
132
+ if (lineage === undefined || target === undefined) return finish("blocked", details);
133
+ const ack = await invoke("gentle_review", { operation: "acknowledge-approved", lineageId: lineage });
134
+ // The facade verifies the native ACK. Preserve that terminal envelope;
135
+ // never query STATUS/ASSESS or replay authority after its burn.
136
+ return finish(acknowledged(ack) && ack.lineage_id === lineage && ack.target_identity === target ? "closed" : "blocked", ack);
137
+ } else if (operation !== "review.status") return finish("handoff", details);
138
+ details = await status();
139
+ continue;
140
+ }
141
+ if (transition.kind !== "collect") return finish("blocked", details);
142
+ const entries = Array.isArray(details.collectBindings) ? details.collectBindings.map(record) : [];
143
+ // Native explicitly supplies the authored correction request. Do not derive
144
+ // host routing metadata from submission domains or inspect opaque bindings.
145
+ if (transition.correction_request !== undefined || entries.length === 0) return finish("input-required", details);
146
+ if (lineage === undefined || target === undefined) return finish("blocked", details);
147
+ const bindings = entries.map(entry => entry.collectBinding);
148
+ if (!bindings.every(nonempty)) return finish("blocked", details);
149
+ if (new Set(bindings).size !== bindings.length || bindings.some(binding => captured.has(binding))) return finish("repeated-capture", details);
150
+ bindings.forEach(binding => captured.add(binding));
151
+ const tool = bindings.length === 1 ? "gentle_review_capture" : "gentle_review_capture_group";
152
+ const parameters = bindings.length === 1 ? { lineageId: lineage, collectBinding: bindings[0] } : { lineageId: lineage, collectBindings: bindings };
153
+ let capture = await invoke(tool, parameters);
154
+ if (capture.outcome === "reviewer-model-run-forecast") {
155
+ if (await deps.presentForecast?.(capture) !== true) return finish("forecast", capture);
156
+ capture = await invoke(tool, { ...parameters, reviewerRunAcknowledged: true });
157
+ }
158
+ if (!["native-last-event-closure", "native-reviewer-result-captured"].includes(String(capture.outcome))
159
+ || capture.failure !== undefined || capture.reconciliation !== undefined) return finish("blocked", capture);
160
+ details = await status();
161
+ }
162
+ return finish("transition-limit", details);
163
+ }
@@ -0,0 +1,49 @@
1
+ import { NativeReviewCliError, NativeReviewConsentBindingError, NativeReviewIntegrationError, sanitizeForeignNativeReviewDiagnostics, type NativeReviewProcessDiagnostics } from "./native-review-cli.ts";
2
+
3
+ /** Narrow decoded objects before reading error facts. */
4
+ function record(value: unknown): value is Record<string, unknown> {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+
8
+ /** Recognize source/bundled CLI errors without trusting foreign diagnostics. */
9
+ export function asNativeReviewCliError(error: unknown): { code: string; diagnostics: NativeReviewProcessDiagnostics } | undefined {
10
+ if (error instanceof NativeReviewCliError) return error;
11
+ if (!record(error) || error.name !== "NativeReviewCliError" || typeof error.code !== "string") return undefined;
12
+ const diagnostics = sanitizeForeignNativeReviewDiagnostics(error.diagnostics);
13
+ return diagnostics === undefined || error.code !== diagnostics.error_code ? undefined : { code: error.code, diagnostics };
14
+ }
15
+
16
+ /** Read consent-binding failures across source and bundled module boundaries. */
17
+ function consentBindingFailure(error: unknown): { reason: string; message: string } | undefined {
18
+ if (error instanceof NativeReviewConsentBindingError) return { reason: error.reason, message: error.message };
19
+ if (!(error instanceof Error) || error.name !== "NativeReviewConsentBindingError") return undefined;
20
+ const reason = (error as unknown as { reason?: unknown }).reason;
21
+ return typeof reason !== "string" || reason.length === 0 ? undefined : { reason, message: error.message };
22
+ }
23
+
24
+ /**
25
+ * Read existing error facts once. This does not grant retry, infer authority,
26
+ * sanitize a provider envelope, or decide an operation's public outcome.
27
+ */
28
+ export function readReviewFailureFacts(error: unknown) {
29
+ const value = record(error) ? error : {};
30
+ const envelope = record(value.failureEnvelope) && record(value.failureEnvelope.raw) ? value.failureEnvelope : undefined;
31
+ return {
32
+ cli: asNativeReviewCliError(error),
33
+ consentBinding: consentBindingFailure(error),
34
+ // Group/status historically accept only decoded integration instances;
35
+ // keep that stricter provenance separate from the operation envelope.
36
+ integration: error instanceof NativeReviewIntegrationError ? error.failureEnvelope : undefined,
37
+ envelope: envelope === undefined ? undefined : {
38
+ raw: envelope.raw as Record<string, unknown>,
39
+ mutationOutcome: envelope.mutationOutcome,
40
+ replayability: typeof envelope.replayability === "string" ? envelope.replayability : undefined,
41
+ nextAction: typeof envelope.nextAction === "string" ? envelope.nextAction : undefined,
42
+ managedAssetsCommand: envelope.code === "managed_assets_outdated" && record(envelope.continuation) && typeof envelope.continuation.command === "string" ? envelope.continuation.command : undefined,
43
+ },
44
+ mutationOutcome: value.mutationOutcome === "unknown" ? "unknown" as const : "none" as const,
45
+ nextAction: value.nextAction,
46
+ auditRecord: record(value.auditRecord) ? value.auditRecord : undefined,
47
+ candidateViewPreNative: value.candidateViewPreNative === true,
48
+ };
49
+ }
@@ -37,6 +37,7 @@ import { completeSimple } from "@earendil-works/pi-ai/compat";
37
37
  import { gentleAiIsolationEnv, resolveGentleAiBinary } from "./gentle-ai-binary.ts";
38
38
  import {
39
39
  INPROCESS_REVIEWER_FAILURE,
40
+ resolveInProcessReviewerModel,
40
41
  runInProcessReviewer,
41
42
  type InProcessReviewerFailureCode,
42
43
  type InProcessReviewerOutcome,
@@ -45,6 +46,7 @@ import {
45
46
  } from "./inprocess-reviewer.ts";
46
47
  import { REVIEW_PROVIDER_ROLE_CAPTURE_OPERATION, REVIEW_PROVIDER_ROLE_CAPTURE_OPERATIONS, type ReviewCaptureSubmissionV1, type ReviewCollectInputV3 } from "./review-integration-v2.ts";
47
48
  import { GENTLE_PI_REVIEW_RELAY_CONTRACT, GENTLE_PI_REVIEW_RELAY_CONTRACT_ENV } from "./review-relay-contract.ts";
49
+ import { observeReviewRelayPhase, type ReviewRelayPhaseObserver } from "./review-relay-phase-timing.ts";
48
50
 
49
51
  export const REVIEW_HOST_RELAY_UNAVAILABLE_MESSAGE =
50
52
  "provider relay requires a gentle-ai build with the pi host relay surface";
@@ -361,6 +363,8 @@ export function resolveReviewHostRelaySubmission(submission: ReviewCaptureSubmis
361
363
  // ---------------------------------------------------------------------------
362
364
 
363
365
  export interface ReviewHostRelayRequest {
366
+ /** Optional host-only diagnostics; never receives prompts, outputs or binding data. */
367
+ readonly observePhase?: ReviewRelayPhaseObserver;
364
368
  readonly captureArgumentTokens: readonly string[];
365
369
  /** Canonical target worktree for coordinator-only native materialize/submit calls. */
366
370
  readonly targetCwd?: string;
@@ -401,6 +405,14 @@ export interface ReviewHostRelayRequest {
401
405
  readonly reviewerSessionId?: string;
402
406
  /** Names the routing config key (e.g. "review-risk") in refusal messages; defaults to a generic label when absent. */
403
407
  readonly routingKey?: string;
408
+ /**
409
+ * Fixed name of where the reviewer routing snapshot came from (binding, pin,
410
+ * frozen profile, or the global effective routing and its saved store path),
411
+ * named in the missing-model refusal (gentle-shell#2163). Never a secret.
412
+ */
413
+ readonly routingSource?: string;
414
+ /** Whether the snapshot has no entry at all for {@link ReviewHostRelayRequest.routingKey}, as opposed to an entry without a model. */
415
+ readonly routingEntryMissing?: boolean;
404
416
  /**
405
417
  * Overrides the reviewer bound entirely. Production leaves it unset and the
406
418
  * relay derives the bound from the materialized prompt bytes and
@@ -416,6 +428,8 @@ export interface ReviewHostRelayResult {
416
428
  readonly resultByteLength: number;
417
429
  /** Raw submission stdout (the provider's admitted-manifest JSON), opaque. */
418
430
  readonly submission: string;
431
+ /** Host-only reviewer facts. Never part of the submitted native artifact. */
432
+ readonly reviewerEvidence?: Readonly<Record<string, unknown>>;
419
433
  }
420
434
 
421
435
  /** Opaque materialize-and-review result, not yet submitted to the provider. */
@@ -424,6 +438,7 @@ export interface ReviewHostRelayPreparedResult {
424
438
  readonly request: ReviewHostRelayRequest;
425
439
  readonly promptByteLength: number;
426
440
  readonly resultByteLength: number;
441
+ readonly reviewerEvidence?: Readonly<Record<string, unknown>>;
427
442
  }
428
443
 
429
444
  const preparedResultBytes = new WeakMap<ReviewHostRelayPreparedResult, Buffer>();
@@ -612,10 +627,21 @@ function validateReviewerSelectionConfiguration(request: ReviewHostRelayRequest)
612
627
  );
613
628
  }
614
629
  if (typeof request.selection !== "string" || request.selection.length === 0) {
630
+ const origin = request.routingSource === undefined ? ""
631
+ : ` (routing source: ${request.routingSource}; the ${routingKey} entry ${request.routingEntryMissing === true ? "is missing" : "has no model"})`;
615
632
  throw new ReviewHostRelayError(
616
633
  REVIEW_HOST_RELAY_FAILURE.REVIEWER_CONFIG_INVALID,
617
634
  "pi",
618
- `Pi host relay reviewer launch configuration is invalid: no model is configured for ${routingKey}; assign it a model in the agent model routing config`,
635
+ `Pi host relay reviewer launch configuration is invalid: no model is configured for ${routingKey}${origin}; assign it a model in the agent model routing config`,
636
+ );
637
+ }
638
+ const model = resolveInProcessReviewerModel({ selection: request.selection, routingKey }, request.reviewerRegistry);
639
+ if (model.kind === "refused") {
640
+ throw new ReviewHostRelayError(
641
+ model.code === INPROCESS_REVIEWER_FAILURE.MODEL_NOT_FOUND ? REVIEW_HOST_RELAY_FAILURE.REVIEWER_MODEL_NOT_FOUND : REVIEW_HOST_RELAY_FAILURE.REVIEWER_CONFIG_INVALID,
642
+ "pi",
643
+ model.message,
644
+ model.evidence === undefined ? {} : { reviewerEvidence: model.evidence },
619
645
  );
620
646
  }
621
647
  return {
@@ -694,12 +720,12 @@ export async function prepareReviewHostRelaySlot(
694
720
  // materialize and the submit leg of one slot.
695
721
  let materialized: ProcessCapture;
696
722
  try {
697
- materialized = await collectGentleAiProcess(preparedRequest.gentleAiExecutable!, ["review", preparedRequest.submission!.operationToken, ...preparedRequest.captureArgumentTokens], {
723
+ materialized = await observeReviewRelayPhase(preparedRequest.observePhase, "materialize", () => collectGentleAiProcess(preparedRequest.gentleAiExecutable!, ["review", preparedRequest.submission!.operationToken, ...preparedRequest.captureArgumentTokens], {
698
724
  cwd: preparedRequest.targetCwd!,
699
725
  env: { ...preparedRequest.environment!, [GENTLE_PI_REVIEW_RELAY_CONTRACT_ENV]: GENTLE_PI_REVIEW_RELAY_CONTRACT },
700
726
  timeoutMs: preparedRequest.gentleAiTimeoutMs!,
701
727
  ...(preparedRequest.signal === undefined ? {} : { signal: preparedRequest.signal }),
702
- });
728
+ }), (result) => result.exitCode === 0 && !result.timedOut && result.stdout.length > 0);
703
729
  } catch (error) {
704
730
  throw new ReviewHostRelayError(REVIEW_HOST_RELAY_FAILURE.MATERIALIZE_FAILED, "materialize", `gentle-ai prompt materialization could not start: ${error instanceof Error ? error.message : String(error)}`);
705
731
  }
@@ -748,6 +774,7 @@ export async function prepareReviewHostRelaySlot(
748
774
  // child used to.
749
775
  const startedAt = Date.now();
750
776
  let outcome: InProcessReviewerOutcome;
777
+ let reviewerEvidence: Record<string, unknown> | undefined;
751
778
  try {
752
779
  outcome = await runReviewer(
753
780
  {
@@ -761,14 +788,15 @@ export async function prepareReviewHostRelaySlot(
761
788
  ...(preparedRequest.signal === undefined ? {} : { signal: preparedRequest.signal }),
762
789
  routingKey: preparedRequest.routingKey!,
763
790
  },
764
- { registry: preparedRequest.reviewerRegistry!, complete: completeSimple },
791
+ { registry: preparedRequest.reviewerRegistry!, complete: completeSimple,
792
+ onEvidence: (evidence) => { reviewerEvidence = evidence; } },
765
793
  );
766
794
  } catch (error) {
767
795
  throw new ReviewHostRelayError(
768
796
  REVIEW_HOST_RELAY_FAILURE.PI_FAILED,
769
797
  "pi",
770
798
  `the reviewer completion could not run: ${error instanceof Error ? error.message : String(error)}`,
771
- { elapsedMs: Date.now() - startedAt, timeoutMs: piTimeoutMs },
799
+ { elapsedMs: Date.now() - startedAt, timeoutMs: piTimeoutMs, ...(reviewerEvidence === undefined ? {} : { reviewerEvidence }) },
772
800
  );
773
801
  }
774
802
  if (outcome.kind === "refused") {
@@ -779,6 +807,7 @@ export async function prepareReviewHostRelaySlot(
779
807
  request: preparedRequest,
780
808
  promptByteLength: promptBytes.length,
781
809
  resultByteLength: resultBytes.length,
810
+ ...(outcome.evidence === undefined && reviewerEvidence === undefined ? {} : { reviewerEvidence: structuredClone(outcome.evidence ?? reviewerEvidence!) }),
782
811
  });
783
812
  preparedResultBytes.set(prepared, resultBytes);
784
813
  return prepared;
@@ -796,6 +825,10 @@ export async function runReviewHostRelayReviewerGroup(
796
825
  if (requests.length === 0) {
797
826
  throw new TypeError("Pi host relay reviewer group requires at least one provider-bound request");
798
827
  }
828
+ // Validate the complete caller-owned routing set before any sibling can
829
+ // materialize a prompt or spend a model run. Completion rechecks its live
830
+ // registry later; this preflight does not freeze provider or auth authority.
831
+ for (const request of requests) validateReviewerSelectionConfiguration(request);
799
832
  const settled = await Promise.allSettled(requests.map(async (request) => await prepare(request)));
800
833
  const failed = settled.find((result) => result.status === "rejected");
801
834
  if (failed?.status === "rejected") throw failed.reason;
@@ -810,6 +843,7 @@ export async function submitReviewHostRelayPreparedResult(prepared: ReviewHostRe
810
843
  const resultBytes = preparedResultBytes.get(prepared);
811
844
  if (resultBytes === undefined) throw new TypeError("Pi host relay requires a recognized prepared result");
812
845
  const { request } = prepared;
846
+ const reviewerFacts = prepared.reviewerEvidence === undefined ? {} : { reviewerEvidence: structuredClone(prepared.reviewerEvidence) };
813
847
  assertTokens("capture", request.captureArgumentTokens);
814
848
  const submissionBinding = resolveReviewHostRelaySubmission(request.submission);
815
849
  const stagingDirectory = await mkdtemp(join(tmpdir(), "gentle-pi-host-relay-result-"));
@@ -826,18 +860,18 @@ export async function submitReviewHostRelayPreparedResult(prepared: ReviewHostRe
826
860
  );
827
861
  let submission: ProcessCapture;
828
862
  try {
829
- submission = await collectGentleAiProcess(request.gentleAiExecutable!, ["review", submissionBinding.operationToken, ...submitTokens], {
863
+ submission = await observeReviewRelayPhase(request.observePhase, "submit", () => collectGentleAiProcess(request.gentleAiExecutable!, ["review", submissionBinding.operationToken, ...submitTokens], {
830
864
  cwd: request.targetCwd!,
831
865
  env: { ...request.environment!, [GENTLE_PI_REVIEW_RELAY_CONTRACT_ENV]: GENTLE_PI_REVIEW_RELAY_CONTRACT },
832
866
  timeoutMs: request.gentleAiTimeoutMs!,
833
867
  ...(request.signal === undefined ? {} : { signal: request.signal }),
834
- });
868
+ }), (result) => result.exitCode === 0 && !result.timedOut && result.stdout.length > 0);
835
869
  } catch (error) {
836
- throw new ReviewHostRelayError(REVIEW_HOST_RELAY_FAILURE.SUBMISSION_REFUSED, "submit", `gentle-ai capture submission could not start: ${error instanceof Error ? error.message : String(error)}`);
870
+ throw new ReviewHostRelayError(REVIEW_HOST_RELAY_FAILURE.SUBMISSION_REFUSED, "submit", `gentle-ai capture submission could not start: ${error instanceof Error ? error.message : String(error)}`, reviewerFacts);
837
871
  }
838
872
  if (submission.exitCode !== 0 || submission.timedOut || submission.stdout.length === 0) {
839
873
  const stderr = submission.stderr.toString("utf8");
840
- const details = { exitCode: submission.exitCode, stderr, timedOut: submission.timedOut, elapsedMs: submission.elapsedMs, timeoutMs: request.gentleAiTimeoutMs! };
874
+ const details = { exitCode: submission.exitCode, stderr, timedOut: submission.timedOut, elapsedMs: submission.elapsedMs, timeoutMs: request.gentleAiTimeoutMs!, ...reviewerFacts };
841
875
  // A typed admission refusal proves the provider consumed no slot.
842
876
  // Every other launched submission stays unknown pending fresh STATUS.
843
877
  if (isReviewHostRelayAdmissionRefusal(submission, stderr)) {
@@ -853,6 +887,7 @@ export async function submitReviewHostRelayPreparedResult(prepared: ReviewHostRe
853
887
  return {
854
888
  promptByteLength: prepared.promptByteLength,
855
889
  resultByteLength: prepared.resultByteLength,
890
+ ...reviewerFacts,
856
891
  submission: submission.stdout.toString("utf8"),
857
892
  };
858
893
  } catch (error) {
@@ -860,13 +895,14 @@ export async function submitReviewHostRelayPreparedResult(prepared: ReviewHostRe
860
895
  throw error;
861
896
  } finally {
862
897
  try {
863
- await rm(stagingDirectory, { recursive: true, force: true });
898
+ await observeReviewRelayPhase(request.observePhase, "cleanup", () => rm(stagingDirectory, { recursive: true, force: true }));
864
899
  } catch (error) {
865
900
  if (!primaryFailure) {
866
901
  throw new ReviewHostRelayError(
867
902
  REVIEW_HOST_RELAY_FAILURE.SUBMISSION_REFUSED,
868
903
  "submit",
869
904
  `Pi host relay result staging cleanup failed: ${error instanceof Error ? error.message : String(error)}`,
905
+ reviewerFacts,
870
906
  );
871
907
  }
872
908
  }
@@ -217,6 +217,8 @@ const CAPABILITIES_SCHEMA_IDENTITIES: Readonly<Record<string, { protocolMinor: n
217
217
  }),
218
218
  });
219
219
  const OPTIONAL_FEATURE_NAMES = Object.freeze([
220
+ "start_request_context",
221
+ "start_options_preflight",
220
222
  "base_ref_workspace_overlay",
221
223
  "bounded_process_waits",
222
224
  "classified_authority_repair",
@@ -236,6 +238,8 @@ const OPTIONAL_FEATURE_NAMES = Object.freeze([
236
238
  "validating_result_reopen",
237
239
  ] as const);
238
240
  const FEATURE_NAMES = Object.freeze([
241
+ "start_request_context",
242
+ "start_options_preflight",
239
243
  "base_ref_workspace_overlay",
240
244
  "bounded_process_waits",
241
245
  "classified_authority_repair",
@@ -1599,6 +1603,7 @@ function decodeCorrectionPlanRequestV1(value: unknown, label: string): ReviewCor
1599
1603
  };
1600
1604
  }
1601
1605
 
1606
+ /** Decode frozen validation evidence, preserving an explicit empty policy and rejecting absence. */
1602
1607
  export function decodeReviewTargetedValidationRequestV1(value: unknown, label = "targeted_validation_request"): ReviewTargetedValidationRequestV1 {
1603
1608
  const body = exactRecord(value, label, [
1604
1609
  "schema", "request_hash", "lineage_id", "expected_revision", "target_identity", "fix_finding_ids", "policy_content", "fix_findings", "fix_classifications",
@@ -1641,7 +1646,8 @@ export function decodeReviewTargetedValidationRequestV1(value: unknown, label =
1641
1646
  expectedRevision: sha256(body.expected_revision, `${label}.expected_revision`),
1642
1647
  targetIdentity: sha256(body.target_identity, `${label}.target_identity`),
1643
1648
  fixFindingIds,
1644
- policyContent: nonempty(body.policy_content, `${label}.policy_content`),
1649
+ // A frozen empty policy is valid; missing historical policy is not.
1650
+ policyContent: text(body.policy_content, `${label}.policy_content`),
1645
1651
  fixFindings,
1646
1652
  fixClassifications,
1647
1653
  projection: enumeration(body.projection, REQUIRED_PROJECTIONS, `${label}.projection`),
@@ -0,0 +1,45 @@
1
+ export type ReviewRelayPhase = "materialize" | "submit" | "cleanup";
2
+ export interface ReviewRelayPhaseTiming {
3
+ readonly phase: ReviewRelayPhase;
4
+ /** Host-observed invocation/cleanup duration, not native internal CPU time. */
5
+ readonly duration_ms: number;
6
+ /** Invocation produced usable bytes, or cleanup resolved; never a review verdict. */
7
+ readonly outcome: "success" | "failure";
8
+ }
9
+ export type ReviewRelayPhaseObserver = (sample: ReviewRelayPhaseTiming) => unknown;
10
+
11
+ /** Ignore invalid or throwing clocks so instrumentation cannot alter settlement. */
12
+ function readClock(clock: () => number): number | undefined {
13
+ try {
14
+ const value = clock();
15
+ return Number.isFinite(value) && value >= 0 ? value : undefined;
16
+ } catch { return undefined; }
17
+ }
18
+
19
+ /** Observe an existing operation only; callbacks never participate in settlement. */
20
+ export async function observeReviewRelayPhase<T>(
21
+ observer: ReviewRelayPhaseObserver | undefined,
22
+ phase: ReviewRelayPhase,
23
+ run: () => Promise<T>,
24
+ succeeded: (result: T) => boolean = () => true,
25
+ clock: () => number = () => performance.now(),
26
+ ): Promise<T> {
27
+ if (typeof observer !== "function") return run();
28
+ const start = readClock(clock);
29
+ let success = false;
30
+ try {
31
+ const result = await run();
32
+ try { success = succeeded(result); } catch { /* Classification is observational. */ }
33
+ return result;
34
+ } finally {
35
+ const end = readClock(clock);
36
+ if (start !== undefined && end !== undefined && end >= start) {
37
+ try {
38
+ const pending = observer(Object.freeze({ phase, duration_ms: end - start, outcome: success ? "success" : "failure" }));
39
+ // Consume async rejection without awaiting it, including callbacks
40
+ // that return promises which never settle.
41
+ void Promise.resolve(pending).catch(() => undefined);
42
+ } catch { /* Diagnostics cannot replace the result or primary failure. */ }
43
+ }
44
+ }
45
+ }
@@ -0,0 +1,17 @@
1
+ import type { NativeStartRequest } from "./native-review-cli.ts";
2
+
3
+ /** Validated intent for a fresh START, never native authority or a candidate identity. */
4
+ export type ReviewStartContext = Readonly<Pick<NativeStartRequest,
5
+ "requestContextPath" | "policyPath" | "focus" | "lenses" | "lensesReason"
6
+ >>;
7
+
8
+ /** Snapshot only intent fields; mutable caller arrays cannot change a retained request. */
9
+ export function snapshotReviewStartContext(input: ReviewStartContext): ReviewStartContext {
10
+ return Object.freeze({
11
+ ...(input.requestContextPath === undefined ? {} : { requestContextPath: input.requestContextPath }),
12
+ ...(input.policyPath === undefined ? {} : { policyPath: input.policyPath }),
13
+ ...(input.focus === undefined ? {} : { focus: input.focus }),
14
+ ...(input.lenses === undefined ? {} : { lenses: Object.freeze([...input.lenses]) }),
15
+ ...(input.lensesReason === undefined ? {} : { lensesReason: input.lensesReason }),
16
+ });
17
+ }
@@ -287,8 +287,10 @@ export function sessionProfileRoutingAt(
287
287
  resolution: SessionProfileResolution,
288
288
  target: InheritedProfileOptions & { foreignRepository?: boolean },
289
289
  ): AgentModelConfig | undefined {
290
- // A binding keeps the whole profile, the reserved orchestrator key included;
291
- // subagent routing carries only role keys, like the pin and global layers.
290
+ // A binding keeps the whole profile, the reserved orchestrator key included,
291
+ // but launch routing returns role keys only, like the pin and global layers.
292
+ // The provider review roles read the orchestrator from the resolution's full
293
+ // modelProfiles (readReviewerModelConfig), not from this routing.
292
294
  if (resolution.kind === "explicit") return roleRouting(resolution.modelProfiles);
293
295
  if (resolution.kind === "inherited") {
294
296
  if (resolution.profile !== undefined || target.foreignRepository !== true) return resolution.profile?.modelProfiles;