create-principles-disciple 1.149.0 → 1.150.2

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 (258) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/ingestion/ingestion.d.ts +9 -7
  3. package/codex-adapter/dist/ingestion/ingestion.js +68 -144
  4. package/codex-adapter/dist/ingestion/transcript-decoder.d.ts +35 -44
  5. package/codex-adapter/dist/ingestion/transcript-decoder.js +23 -84
  6. package/codex-adapter/dist/ingestion/transcript-source.d.ts +29 -0
  7. package/codex-adapter/dist/ingestion/transcript-source.js +65 -0
  8. package/codex-adapter/dist/pd-hook.d.ts +27 -1
  9. package/codex-adapter/dist/pd-hook.js +88 -7
  10. package/codex-adapter/dist/worker/workspace-worker.d.ts +15 -0
  11. package/codex-adapter/dist/worker/workspace-worker.js +7 -36
  12. package/codex-adapter/package.json +1 -1
  13. package/console/dist/server/index.js +14 -0
  14. package/console/dist/server/models/ActivationsConsoleModel.d.ts +3 -17
  15. package/console/dist/server/models/ActivationsConsoleModel.js +5 -44
  16. package/console/dist/server/routes/diagnostician.d.ts +50 -0
  17. package/console/dist/server/routes/diagnostician.js +388 -0
  18. package/console/dist/server/routes/examiner-eligibility.d.ts +73 -0
  19. package/console/dist/server/routes/examiner-eligibility.js +326 -0
  20. package/console/dist/server/routes/examiner.js +66 -8
  21. package/console/dist/web/assets/app.css +40 -0
  22. package/console/dist/web/assets/app.js +30 -30
  23. package/core/dist/host/host-installer.d.ts +7 -0
  24. package/core/dist/host/host-installer.d.ts.map +1 -1
  25. package/core/dist/host/host-installer.js.map +1 -1
  26. package/core/dist/runtime/activation/index.d.ts +3 -3
  27. package/core/dist/runtime/activation/index.d.ts.map +1 -1
  28. package/core/dist/runtime/activation/index.js +1 -1
  29. package/core/dist/runtime/activation/index.js.map +1 -1
  30. package/core/dist/runtime/activation/promotion-readiness-evaluator.d.ts +25 -1
  31. package/core/dist/runtime/activation/promotion-readiness-evaluator.d.ts.map +1 -1
  32. package/core/dist/runtime/activation/promotion-readiness-evaluator.js +58 -1
  33. package/core/dist/runtime/activation/promotion-readiness-evaluator.js.map +1 -1
  34. package/core/dist/runtime/activation/promotion-readiness-reader.d.ts.map +1 -1
  35. package/core/dist/runtime/activation/promotion-readiness-reader.js +4 -2
  36. package/core/dist/runtime/activation/promotion-readiness-reader.js.map +1 -1
  37. package/core/dist/runtime/activation/rulecode-owner-decision-service.d.ts +28 -0
  38. package/core/dist/runtime/activation/rulecode-owner-decision-service.d.ts.map +1 -1
  39. package/core/dist/runtime/activation/rulecode-owner-decision-service.js +2 -0
  40. package/core/dist/runtime/activation/rulecode-owner-decision-service.js.map +1 -1
  41. package/core/dist/runtime/admission-gate.d.ts +8 -1
  42. package/core/dist/runtime/admission-gate.d.ts.map +1 -1
  43. package/core/dist/runtime/admission-gate.js +2 -1
  44. package/core/dist/runtime/admission-gate.js.map +1 -1
  45. package/core/dist/runtime/config/pd-config-defaults.d.ts.map +1 -1
  46. package/core/dist/runtime/config/pd-config-defaults.js +20 -2
  47. package/core/dist/runtime/config/pd-config-defaults.js.map +1 -1
  48. package/core/dist/runtime/config/pd-config-effective.d.ts.map +1 -1
  49. package/core/dist/runtime/config/pd-config-effective.js +5 -2
  50. package/core/dist/runtime/config/pd-config-effective.js.map +1 -1
  51. package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
  52. package/core/dist/runtime/config/pd-config-validate.js +18 -0
  53. package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
  54. package/core/dist/runtime/context-payload.d.ts +48 -3
  55. package/core/dist/runtime/context-payload.d.ts.map +1 -1
  56. package/core/dist/runtime/context-payload.js +38 -0
  57. package/core/dist/runtime/context-payload.js.map +1 -1
  58. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.d.ts +8 -2
  59. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.d.ts.map +1 -1
  60. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js +28 -2
  61. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js.map +1 -1
  62. package/core/dist/runtime/diagnostician-candidate.d.ts +24 -0
  63. package/core/dist/runtime/diagnostician-candidate.d.ts.map +1 -0
  64. package/core/dist/runtime/diagnostician-candidate.js +55 -0
  65. package/core/dist/runtime/diagnostician-candidate.js.map +1 -0
  66. package/core/dist/runtime/evidence-guards.d.ts +10 -4
  67. package/core/dist/runtime/evidence-guards.d.ts.map +1 -1
  68. package/core/dist/runtime/evidence-guards.js +12 -5
  69. package/core/dist/runtime/evidence-guards.js.map +1 -1
  70. package/core/dist/runtime/evolution/evolution-types.d.ts +4 -4
  71. package/core/dist/runtime/evolution/evolution-types.d.ts.map +1 -1
  72. package/core/dist/runtime/evolution/evolution-types.js +1 -0
  73. package/core/dist/runtime/evolution/evolution-types.js.map +1 -1
  74. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  75. package/core/dist/runtime/feature-flags/feature-flag-contract.js +14 -0
  76. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  77. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  78. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +16 -0
  79. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  80. package/core/dist/runtime/index.d.ts +5 -2
  81. package/core/dist/runtime/index.d.ts.map +1 -1
  82. package/core/dist/runtime/index.js +6 -1
  83. package/core/dist/runtime/index.js.map +1 -1
  84. package/core/dist/runtime/internalization/index.d.ts +1 -0
  85. package/core/dist/runtime/internalization/index.d.ts.map +1 -1
  86. package/core/dist/runtime/internalization/index.js +2 -0
  87. package/core/dist/runtime/internalization/index.js.map +1 -1
  88. package/core/dist/runtime/internalization/rule-host-contracts.d.ts +10 -0
  89. package/core/dist/runtime/internalization/rule-host-contracts.d.ts.map +1 -1
  90. package/core/dist/runtime/internalization/rule-host-evaluator.js +10 -10
  91. package/core/dist/runtime/internalization/rule-host-evaluator.js.map +1 -1
  92. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +7 -6
  93. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
  94. package/core/dist/runtime/internalization/rule-host-input-builder.js +6 -2
  95. package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
  96. package/core/dist/runtime/internalization/rule-host-result-normalizer.d.ts +33 -0
  97. package/core/dist/runtime/internalization/rule-host-result-normalizer.d.ts.map +1 -0
  98. package/core/dist/runtime/internalization/rule-host-result-normalizer.js +61 -0
  99. package/core/dist/runtime/internalization/rule-host-result-normalizer.js.map +1 -0
  100. package/core/dist/runtime/internalization/rule-host-validator.d.ts.map +1 -1
  101. package/core/dist/runtime/internalization/rule-host-validator.js +17 -0
  102. package/core/dist/runtime/internalization/rule-host-validator.js.map +1 -1
  103. package/core/dist/runtime/pain-ingress-payload.d.ts +27 -2
  104. package/core/dist/runtime/pain-ingress-payload.d.ts.map +1 -1
  105. package/core/dist/runtime/pain-ingress-payload.js +45 -3
  106. package/core/dist/runtime/pain-ingress-payload.js.map +1 -1
  107. package/core/dist/runtime/pain-ingress.d.ts +4 -2
  108. package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
  109. package/core/dist/runtime/pain-ingress.js +23 -3
  110. package/core/dist/runtime/pain-ingress.js.map +1 -1
  111. package/core/dist/runtime/pain-severity.d.ts +14 -0
  112. package/core/dist/runtime/pain-severity.d.ts.map +1 -0
  113. package/core/dist/runtime/pain-severity.js +14 -0
  114. package/core/dist/runtime/pain-severity.js.map +1 -0
  115. package/core/dist/runtime/pain-signal-bridge.d.ts +17 -3
  116. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  117. package/core/dist/runtime/pain-signal-bridge.js +6 -0
  118. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  119. package/core/dist/runtime/pain-signal-observability.d.ts.map +1 -1
  120. package/core/dist/runtime/pain-signal-observability.js +3 -2
  121. package/core/dist/runtime/pain-signal-observability.js.map +1 -1
  122. package/core/dist/runtime/pain-submit-capability.d.ts +164 -0
  123. package/core/dist/runtime/pain-submit-capability.d.ts.map +1 -0
  124. package/core/dist/runtime/pain-submit-capability.js +442 -0
  125. package/core/dist/runtime/pain-submit-capability.js.map +1 -0
  126. package/core/dist/runtime/pain-to-principle-service.d.ts +4 -0
  127. package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
  128. package/core/dist/runtime/pain-to-principle-service.js +2 -0
  129. package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
  130. package/core/dist/runtime/stalled-diagnostician-task-read-model.d.ts +56 -10
  131. package/core/dist/runtime/stalled-diagnostician-task-read-model.d.ts.map +1 -1
  132. package/core/dist/runtime/stalled-diagnostician-task-read-model.js +80 -4
  133. package/core/dist/runtime/stalled-diagnostician-task-read-model.js.map +1 -1
  134. package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts.map +1 -1
  135. package/core/dist/runtime/store/context/sqlite-context-assembler.js +11 -0
  136. package/core/dist/runtime/store/context/sqlite-context-assembler.js.map +1 -1
  137. package/core/dist/runtime/store/run/memory-run-store.d.ts +10 -0
  138. package/core/dist/runtime/store/run/memory-run-store.d.ts.map +1 -1
  139. package/core/dist/runtime/store/run/memory-run-store.js +21 -0
  140. package/core/dist/runtime/store/run/memory-run-store.js.map +1 -1
  141. package/core/dist/runtime/store/run/run-store.d.ts +12 -0
  142. package/core/dist/runtime/store/run/run-store.d.ts.map +1 -1
  143. package/core/dist/runtime/store/run/sqlite-run-store.d.ts +1 -0
  144. package/core/dist/runtime/store/run/sqlite-run-store.d.ts.map +1 -1
  145. package/core/dist/runtime/store/run/sqlite-run-store.js +14 -0
  146. package/core/dist/runtime/store/run/sqlite-run-store.js.map +1 -1
  147. package/core/dist/runtime/task-status.d.ts +9 -0
  148. package/core/dist/runtime/task-status.d.ts.map +1 -1
  149. package/core/dist/runtime/task-status.js +7 -1
  150. package/core/dist/runtime/task-status.js.map +1 -1
  151. package/core/dist/runtime/types/evidence-chain-contract.d.ts +18 -0
  152. package/core/dist/runtime/types/evidence-chain-contract.d.ts.map +1 -1
  153. package/core/dist/runtime/types/evidence-chain-contract.js +37 -7
  154. package/core/dist/runtime/types/evidence-chain-contract.js.map +1 -1
  155. package/core/package.json +5 -1
  156. package/dist/install-summary.d.ts +7 -0
  157. package/dist/install-summary.d.ts.map +1 -1
  158. package/dist/install-summary.js +4 -0
  159. package/dist/install-summary.js.map +1 -1
  160. package/dist/installer.d.ts +34 -1
  161. package/dist/installer.d.ts.map +1 -1
  162. package/dist/installer.js +84 -4
  163. package/dist/installer.js.map +1 -1
  164. package/dist/installers/codex-host-installer.d.ts +88 -1
  165. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  166. package/dist/installers/codex-host-installer.js +370 -11
  167. package/dist/installers/codex-host-installer.js.map +1 -1
  168. package/dist/installers/index.d.ts +23 -0
  169. package/dist/installers/index.d.ts.map +1 -1
  170. package/dist/installers/index.js +38 -1
  171. package/dist/installers/index.js.map +1 -1
  172. package/dist/installers/legacy-workbuddy-skill.d.ts +59 -0
  173. package/dist/installers/legacy-workbuddy-skill.d.ts.map +1 -0
  174. package/dist/installers/legacy-workbuddy-skill.js +168 -0
  175. package/dist/installers/legacy-workbuddy-skill.js.map +1 -0
  176. package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
  177. package/dist/installers/workbuddy-host-installer.js +7 -0
  178. package/dist/installers/workbuddy-host-installer.js.map +1 -1
  179. package/host-runtime/dist/adaptive-priority-provider.d.ts +101 -0
  180. package/host-runtime/dist/adaptive-priority-provider.js +194 -0
  181. package/host-runtime/dist/adaptive-selection.d.ts +164 -0
  182. package/host-runtime/dist/adaptive-selection.js +506 -0
  183. package/host-runtime/dist/adaptive-skip-decision.d.ts +61 -0
  184. package/host-runtime/dist/adaptive-skip-decision.js +114 -0
  185. package/host-runtime/dist/codex-ingestion-consent.d.ts +32 -95
  186. package/host-runtime/dist/codex-ingestion-consent.js +33 -205
  187. package/host-runtime/dist/conversation-ingestion/consent.d.ts +124 -0
  188. package/host-runtime/dist/conversation-ingestion/consent.js +531 -0
  189. package/host-runtime/dist/conversation-ingestion/index.d.ts +12 -0
  190. package/host-runtime/dist/conversation-ingestion/index.js +12 -0
  191. package/host-runtime/dist/conversation-ingestion/pipeline.d.ts +101 -0
  192. package/host-runtime/dist/conversation-ingestion/pipeline.js +162 -0
  193. package/host-runtime/dist/conversation-ingestion/source.d.ts +172 -0
  194. package/host-runtime/dist/conversation-ingestion/source.js +111 -0
  195. package/host-runtime/dist/conversation-ingestion/text-policy.d.ts +51 -0
  196. package/host-runtime/dist/conversation-ingestion/text-policy.js +68 -0
  197. package/host-runtime/dist/diagnostician-auto-run.d.ts +28 -0
  198. package/host-runtime/dist/diagnostician-auto-run.js +100 -0
  199. package/host-runtime/dist/governance-observation-store.d.ts +9 -7
  200. package/host-runtime/dist/governance-observation-store.js +20 -4
  201. package/host-runtime/dist/host-tool-semantic-resolver.d.ts +42 -1
  202. package/host-runtime/dist/host-tool-semantic-resolver.js +80 -14
  203. package/host-runtime/dist/index.d.ts +5 -0
  204. package/host-runtime/dist/index.js +12 -0
  205. package/host-runtime/dist/production-rulehost-gate.js +17 -17
  206. package/host-runtime/dist/rulecode-event-collection.d.ts +31 -0
  207. package/host-runtime/dist/rulecode-event-collection.js +62 -0
  208. package/host-runtime/package.json +1 -1
  209. package/package.json +3 -3
  210. package/pd-cli/dist/commands/diagnose.d.ts +30 -0
  211. package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
  212. package/pd-cli/dist/commands/diagnose.js +75 -0
  213. package/pd-cli/dist/commands/diagnose.js.map +1 -1
  214. package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
  215. package/pd-cli/dist/commands/pain-record.js +5 -4
  216. package/pd-cli/dist/commands/pain-record.js.map +1 -1
  217. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  218. package/pd-cli/dist/commands/pain-retry.js +2 -1
  219. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  220. package/pd-cli/dist/commands/runtime-activation.d.ts +6 -17
  221. package/pd-cli/dist/commands/runtime-activation.d.ts.map +1 -1
  222. package/pd-cli/dist/commands/runtime-activation.js +42 -48
  223. package/pd-cli/dist/commands/runtime-activation.js.map +1 -1
  224. package/pd-cli/dist/index.js +1 -0
  225. package/pd-cli/dist/index.js.map +1 -1
  226. package/pd-cli/dist/services/delivery-surfaces.js +1 -1
  227. package/pd-cli/dist/services/delivery-surfaces.js.map +1 -1
  228. package/pd-cli/package.json +1 -1
  229. package/pd-mcp-server/dist/budget.d.ts +1 -1
  230. package/pd-mcp-server/dist/budget.js +2 -2
  231. package/pd-mcp-server/dist/envelope.d.ts +15 -0
  232. package/pd-mcp-server/dist/envelope.js +49 -1
  233. package/pd-mcp-server/dist/index.d.ts +2 -0
  234. package/pd-mcp-server/dist/index.js +6 -0
  235. package/pd-mcp-server/dist/server.d.ts +83 -14
  236. package/pd-mcp-server/dist/server.js +251 -4
  237. package/pd-mcp-server/dist/version.d.ts +1 -1
  238. package/pd-mcp-server/dist/version.js +1 -1
  239. package/pd-mcp-server/dist/workspace.d.ts +4 -2
  240. package/pd-mcp-server/dist/workspace.js +5 -2
  241. package/pd-mcp-server/package.json +1 -1
  242. package/plugin/dist/bundle.js +449 -437
  243. package/plugin/dist/core/evolution-reducer.d.ts +2 -2
  244. package/plugin/dist/hooks/hook-tool-semantics.d.ts +25 -0
  245. package/plugin/dist/hooks/pain-ingress-adapter.d.ts +1 -1
  246. package/plugin/dist/openclaw.plugin.json +1 -1
  247. package/plugin/dist/rulehost-evidence.js +1 -1
  248. package/plugin/openclaw.plugin.json +1 -1
  249. package/plugin/package.json +1 -1
  250. package/release-manager/dist/installer.js +84 -4
  251. package/release-manager/dist/installers/codex-host-installer.js +370 -11
  252. package/release-manager/dist/installers/index.js +38 -1
  253. package/release-manager/dist/installers/legacy-workbuddy-skill.js +168 -0
  254. package/release-manager/dist/installers/workbuddy-host-installer.js +7 -0
  255. package/release-manager/package.json +1 -1
  256. package/workbuddy-adapter/dist/pd-hook.js +20 -4
  257. package/workbuddy-adapter/package.json +1 -1
  258. package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +123 -20
@@ -0,0 +1,506 @@
1
+ /**
2
+ * Adaptive Activation — shared selection protocol (SPEC v0.6 §4/§7/§9).
3
+ *
4
+ * ONE implementation of the bounded "current turn → pick at most one candidate"
5
+ * protocol, shared by the selector lab and the production host runtimes.
6
+ *
7
+ * Contract highlights (PRI-1122 measurement findings):
8
+ * - Candidates are sent with a LOCALLY PRECOMPUTED digest. The model can only
9
+ * copy it; it is never asked to compute a hash. A payload without digests
10
+ * makes every `selected` answer invalid by construction.
11
+ * - The incremental deadline is a FIRST-BYTE deadline, not a whole-generation
12
+ * wall clock. Once the endpoint has started answering, generation is bounded
13
+ * by its own window; late completions are still discarded.
14
+ * - One real send per turn, zero retries, zero repair, zero provider fallback.
15
+ * - Diagnostics never carry the raw prompt, the raw response, or credentials.
16
+ */
17
+ import crypto from 'node:crypto';
18
+ import { PiAiRuntimeAdapter, StoreEventEmitter, } from '@principles/core/runtime';
19
+ import { readPromptActivationCandidates } from './active-principle-prompt.js';
20
+ import { revalidateAdaptivePrinciple } from './adaptive-principle-revalidation.js';
21
+ export const ADAPTIVE_SELECTION_LIMITS = {
22
+ maxCandidates: 12,
23
+ maxCandidateChars: 600,
24
+ maxPriorMessages: 4,
25
+ maxPriorMessageChars: 1200,
26
+ maxInputChars: 6000,
27
+ /** Admission (time-to-first-byte) deadline for the incremental step. */
28
+ firstByteTimeoutMs: 10_000,
29
+ /** Bounded completion window once the endpoint has started answering. */
30
+ generationTimeoutMs: 10_000,
31
+ maxOutputTokens: 512,
32
+ };
33
+ export function hash(value) {
34
+ return crypto.createHash('sha256').update(value, 'utf8').digest('hex');
35
+ }
36
+ export const ADAPTIVE_SELECTOR_SYSTEM = [
37
+ '你是 Principles Disciple 的原则选择器。只判断:当前用户输入是否需要追加一条已批准原则。',
38
+ '候选只在「当前输入明确要求交付、实现、修复、审查或验证,且这条原则会改变你这一步的做法」时才算适用。',
39
+ '通用礼貌、闲聊、元问题、与当前任务无关的原则一律不选。',
40
+ '只能返回下面三种 JSON 之一,不要 Markdown、不要解释:',
41
+ '{"status":"selected","id":"候选引用(例如 c1)","digest":"该候选随附的 digest 原样复制;不要计算或改写","reason":"一句话理由"}',
42
+ '{"status":"none_applicable","id":null,"digest":null,"reason":"一句话理由"}',
43
+ '{"status":"uncertain","id":null,"digest":null,"reason":"一句话理由"}',
44
+ 'digest 由本地预计算并随候选下发;必须逐字符原样返回所选候选的 digest。',
45
+ '最多只能选一条。',
46
+ ].join('\n');
47
+ function boundText(value, max) {
48
+ const text = value.replace(/\s+/gu, ' ').trim();
49
+ if (text.length <= max)
50
+ return text;
51
+ return `${text.slice(0, max - 1)}…`;
52
+ }
53
+ export function buildBoundedSelectionInput(input) {
54
+ const currentInstruction = input.currentInput.trim();
55
+ if (!currentInstruction)
56
+ return { ok: false, reason: 'CURRENT_INSTRUCTION_EMPTY' };
57
+ if (currentInstruction.length > ADAPTIVE_SELECTION_LIMITS.maxInputChars) {
58
+ return { ok: false, reason: 'CURRENT_INSTRUCTION_TOO_LARGE' };
59
+ }
60
+ const priorMessages = input.priorMessages ?? [];
61
+ const selectedPrior = priorMessages.slice(-ADAPTIVE_SELECTION_LIMITS.maxPriorMessages);
62
+ const boundedPrior = selectedPrior.map((message, index) => ({
63
+ text: boundText(message.text, ADAPTIVE_SELECTION_LIMITS.maxPriorMessageChars),
64
+ source: message.source ?? 'prior',
65
+ index,
66
+ }));
67
+ const entries = [];
68
+ for (const principle of input.candidates) {
69
+ if (!principle.artifactContentSha256)
70
+ continue;
71
+ if (!principle.text.trim())
72
+ continue;
73
+ const candidateText = boundText(principle.text, ADAPTIVE_SELECTION_LIMITS.maxCandidateChars);
74
+ entries.push({
75
+ ref: `c${entries.length + 1}`,
76
+ text: candidateText,
77
+ // Digest the body exactly as it goes on the wire, so the model can copy it
78
+ // and anyone can recompute it from the request it actually received.
79
+ digest: hash(candidateText),
80
+ principle,
81
+ });
82
+ if (entries.length >= ADAPTIVE_SELECTION_LIMITS.maxCandidates)
83
+ break;
84
+ }
85
+ if (entries.length === 0)
86
+ return { ok: false, reason: 'NO_CANDIDATES' };
87
+ return {
88
+ ok: true,
89
+ input: {
90
+ payload: {
91
+ currentInstruction,
92
+ priorMessages: boundedPrior,
93
+ // The digest is part of the outbound contract: the model copies it.
94
+ candidates: entries.map((entry) => ({ ref: entry.ref, text: entry.text, digest: entry.digest })),
95
+ },
96
+ entries,
97
+ priorDropped: Math.max(0, priorMessages.length - selectedPrior.length),
98
+ },
99
+ };
100
+ }
101
+ /** rc-1/rc-2: parsed payloads are unknown until this guard passes. */
102
+ function isRecord(value) {
103
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
104
+ }
105
+ export function parseSelectionShape(value) {
106
+ if (!isRecord(value)) {
107
+ return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
108
+ }
109
+ const { status } = value;
110
+ const { id } = value;
111
+ const { digest } = value;
112
+ if (status === 'selected') {
113
+ if (typeof id !== 'string' || !id)
114
+ return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
115
+ if (typeof digest !== 'string' || !digest)
116
+ return { ok: false, reason: 'SELECTION_DIGEST_INVALID' };
117
+ return { ok: true, selection: { status: 'selected', id, digest } };
118
+ }
119
+ if (status === 'none_applicable' || status === 'uncertain') {
120
+ if (id !== null && id !== undefined)
121
+ return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
122
+ if (digest !== null && digest !== undefined)
123
+ return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
124
+ return { ok: true, selection: { status, id: null, digest: null } };
125
+ }
126
+ return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
127
+ }
128
+ export function validateSelectionResult(value, entries) {
129
+ const parsed = parseSelectionShape(value);
130
+ if (!parsed.ok) {
131
+ return {
132
+ ok: false,
133
+ reason: parsed.reason,
134
+ refValid: null,
135
+ digestValid: null,
136
+ };
137
+ }
138
+ const { selection } = parsed;
139
+ if (selection.status !== 'selected') {
140
+ return {
141
+ ok: true,
142
+ selected: null,
143
+ outcome: selection.status === 'uncertain' ? 'uncertain' : 'no_increment',
144
+ };
145
+ }
146
+ const entry = entries.find((candidate) => candidate.ref === selection.id);
147
+ if (!entry) {
148
+ return { ok: false, reason: 'SELECTION_REFERENCE_INVALID', refValid: false, digestValid: null };
149
+ }
150
+ // Two independent computations of the wire-body digest must agree: the value
151
+ // frozen into the candidate table and a fresh hash of the frozen body.
152
+ if (selection.digest !== entry.digest || selection.digest !== hash(entry.text)) {
153
+ return { ok: false, reason: 'SELECTION_DIGEST_INVALID', refValid: true, digestValid: false };
154
+ }
155
+ if (entries.some((candidate) => candidate !== entry && candidate.principle.principleId === entry.principle.principleId)) {
156
+ return { ok: false, reason: 'SELECTION_AMBIGUOUS', refValid: true, digestValid: true };
157
+ }
158
+ return { ok: true, selected: entry, outcome: 'selected' };
159
+ }
160
+ export function localFailureCode(reason) {
161
+ if (reason === 'SELECTION_OUTPUT_INVALID')
162
+ return 'SELECTION_OUTPUT_INVALID';
163
+ if (reason === 'SELECTION_DIGEST_INVALID')
164
+ return 'SELECTION_DIGEST_INVALID';
165
+ if (reason === 'SELECTION_REFERENCE_INVALID')
166
+ return 'SELECTION_REFERENCE_INVALID';
167
+ if (reason === 'SELECTION_AMBIGUOUS')
168
+ return 'SELECTION_AMBIGUOUS';
169
+ if (reason === 'SELECTION_EXPIRED')
170
+ return 'SELECTION_EXPIRED';
171
+ return 'SELECTION_OUTPUT_INVALID';
172
+ }
173
+ function outerDeadlineReached(now, outerDeadlineAt, signal) {
174
+ // Without an outer deadline this is an ordinary caller signal; keep the
175
+ // previous SELECTION_EXPIRED / TRANSPORT_FAILED classification for it.
176
+ return outerDeadlineAt !== undefined && (signal?.aborted === true || now() >= outerDeadlineAt);
177
+ }
178
+ function emptyDiagnostics(admissionDeadlineAt) {
179
+ return {
180
+ stage: 'idle',
181
+ admissionDeadlineAt,
182
+ completionDeadlineAt: null,
183
+ firstByteAt: null,
184
+ generationEndedAt: null,
185
+ cancelledAt: null,
186
+ httpStatus: null,
187
+ finishReason: 'unknown',
188
+ usage: null,
189
+ failures: [],
190
+ };
191
+ }
192
+ function parseFinishMetadata(raw) {
193
+ const result = { finishReason: 'unknown', usage: null };
194
+ const absorb = (parsed) => {
195
+ if (!isRecord(parsed))
196
+ return;
197
+ const { choices } = parsed;
198
+ if (Array.isArray(choices) && choices.length > 0) {
199
+ const [first] = choices;
200
+ if (isRecord(first)) {
201
+ const finish = first.finish_reason;
202
+ if (typeof finish === 'string' && finish)
203
+ result.finishReason = finish;
204
+ }
205
+ }
206
+ const { usage } = parsed;
207
+ if (isRecord(usage)) {
208
+ const input = usage.prompt_tokens ?? usage.input_tokens;
209
+ const output = usage.completion_tokens ?? usage.output_tokens;
210
+ result.usage = {
211
+ inputTokens: typeof input === 'number' ? input : null,
212
+ outputTokens: typeof output === 'number' ? output : null,
213
+ };
214
+ }
215
+ };
216
+ const trimmed = raw.trim();
217
+ if (!trimmed)
218
+ return result;
219
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
220
+ try {
221
+ absorb(JSON.parse(trimmed));
222
+ return result;
223
+ }
224
+ catch {
225
+ return result;
226
+ }
227
+ }
228
+ for (const line of trimmed.split(/\r?\n/u)) {
229
+ const payload = line.startsWith('data:') ? line.slice(5).trim() : '';
230
+ if (!payload || payload === '[DONE]')
231
+ continue;
232
+ try {
233
+ absorb(JSON.parse(payload));
234
+ }
235
+ catch {
236
+ // Ignore non-JSON keep-alives; diagnostics stay 'unknown' rather than guessing.
237
+ }
238
+ }
239
+ return result;
240
+ }
241
+ export function createSingleModelSelector(options) {
242
+ const now = options.now ?? Date.now;
243
+ const Adapter = options.PiAiRuntimeAdapterImpl ?? PiAiRuntimeAdapter;
244
+ const generationTimeoutMs = options.generationTimeoutMs ?? ADAPTIVE_SELECTION_LIMITS.generationTimeoutMs;
245
+ const maxTokens = options.maxTokens ?? ADAPTIVE_SELECTION_LIMITS.maxOutputTokens;
246
+ const diagnostics = emptyDiagnostics(options.admissionDeadlineAt);
247
+ let sends = 0;
248
+ let status = 'not_sent';
249
+ let failure = null;
250
+ let finishMetadata = Promise.resolve({ finishReason: 'unknown', usage: null });
251
+ const fail = (code) => {
252
+ failure = code;
253
+ status = 'failed';
254
+ diagnostics.failures.push(code);
255
+ throw new Error(code);
256
+ };
257
+ const selector = async (input) => {
258
+ if (sends > 0)
259
+ fail('TRANSPORT_NOT_SENT');
260
+ if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)) {
261
+ diagnostics.cancelledAt = now();
262
+ fail('TURN_DEADLINE_EXCEEDED');
263
+ }
264
+ if (now() >= options.admissionDeadlineAt) {
265
+ diagnostics.cancelledAt = now();
266
+ fail('SELECTION_EXPIRED');
267
+ }
268
+ const remainingAdmission = Math.max(1, options.admissionDeadlineAt - now());
269
+ const ttfbController = new AbortController();
270
+ const ttfbTimer = setTimeout(() => ttfbController.abort(new Error('ADMISSION_DEADLINE')), remainingAdmission);
271
+ ttfbTimer.unref?.();
272
+ let firstByteAt = null;
273
+ let completionDeadlineAt = null;
274
+ const guardedFetch = async (resource, init) => {
275
+ const url = resource instanceof Request ? resource.url : String(resource);
276
+ const requestInit = init ?? {};
277
+ if (options.model.url) {
278
+ if (url !== options.model.url)
279
+ fail('TRANSPORT_NOT_SENT');
280
+ }
281
+ else if (options.model.baseUrl) {
282
+ if (!url.startsWith(options.model.baseUrl))
283
+ fail('TRANSPORT_NOT_SENT');
284
+ }
285
+ else if (!url.startsWith('https://')) {
286
+ fail('TRANSPORT_NOT_SENT');
287
+ }
288
+ let body;
289
+ try {
290
+ const parsed = typeof requestInit.body === 'string' ? JSON.parse(requestInit.body) : null;
291
+ body = isRecord(parsed) ? parsed : null;
292
+ }
293
+ catch {
294
+ body = null;
295
+ }
296
+ if (!body || body.model !== options.model.model)
297
+ fail('TRANSPORT_NOT_SENT');
298
+ if (body.max_tokens !== maxTokens)
299
+ fail('TRANSPORT_NOT_SENT');
300
+ const apiKey = process.env[options.model.apiKeyEnv];
301
+ if (!apiKey)
302
+ fail('TRANSPORT_NOT_SENT');
303
+ sends += 1;
304
+ status = 'sent';
305
+ diagnostics.stage = 'admission';
306
+ const combined = AbortSignal.any([
307
+ ...(requestInit.signal ? [requestInit.signal] : []),
308
+ ttfbController.signal,
309
+ ...(options.signal ? [options.signal] : []),
310
+ ]);
311
+ let response;
312
+ try {
313
+ response = await (options.fetchImpl ?? fetch)(url, { ...requestInit, signal: combined, redirect: 'error' });
314
+ }
315
+ catch (error) {
316
+ diagnostics.cancelledAt = now();
317
+ diagnostics.stage = 'admission';
318
+ fail(outerDeadlineReached(now, options.outerDeadlineAt, options.signal)
319
+ ? 'TURN_DEADLINE_EXCEEDED'
320
+ : ttfbController.signal.aborted ? 'SELECTION_EXPIRED' : 'TRANSPORT_FAILED');
321
+ throw error;
322
+ }
323
+ // First byte is here: stop the admission clock, start the completion window.
324
+ firstByteAt = now();
325
+ diagnostics.firstByteAt = firstByteAt;
326
+ diagnostics.httpStatus = response.status;
327
+ clearTimeout(ttfbTimer);
328
+ if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)) {
329
+ diagnostics.cancelledAt = firstByteAt;
330
+ fail('TURN_DEADLINE_EXCEEDED');
331
+ }
332
+ if (firstByteAt >= options.admissionDeadlineAt) {
333
+ diagnostics.cancelledAt = firstByteAt;
334
+ fail('SELECTION_EXPIRED');
335
+ }
336
+ // Headers arriving is not completion: the generation window may never
337
+ // extend past the host deadline.
338
+ completionDeadlineAt = options.outerDeadlineAt === undefined
339
+ ? firstByteAt + generationTimeoutMs
340
+ : Math.min(firstByteAt + generationTimeoutMs, options.outerDeadlineAt);
341
+ diagnostics.completionDeadlineAt = completionDeadlineAt;
342
+ diagnostics.stage = 'generation';
343
+ try {
344
+ const clone = response.clone();
345
+ finishMetadata = clone
346
+ .text()
347
+ .then((raw) => parseFinishMetadata(raw))
348
+ .catch(() => ({ finishReason: 'unknown', usage: null }));
349
+ }
350
+ catch {
351
+ finishMetadata = Promise.resolve({ finishReason: 'unknown', usage: null });
352
+ }
353
+ return response;
354
+ };
355
+ try {
356
+ const adapter = new Adapter({
357
+ provider: options.model.provider,
358
+ model: options.model.model,
359
+ ...(options.model.baseUrl ? { baseUrl: options.model.baseUrl } : {}),
360
+ apiKeyEnv: options.model.apiKeyEnv,
361
+ maxRetries: 0,
362
+ maxRepairAttempts: 0,
363
+ outputPathStrategy: 'free_form_only',
364
+ reasoning: 'low',
365
+ timeoutMs: remainingAdmission + generationTimeoutMs,
366
+ maxTokens,
367
+ fetch: guardedFetch,
368
+ eventEmitter: new StoreEventEmitter(),
369
+ });
370
+ const run = await adapter.startRun({
371
+ agentSpec: { agentId: 'adaptive-principle-selector', schemaVersion: 'current' },
372
+ inputPayload: input.payload,
373
+ contextItems: [],
374
+ timeoutMs: remainingAdmission + generationTimeoutMs,
375
+ maxTokens,
376
+ systemPrompt: ADAPTIVE_SELECTOR_SYSTEM,
377
+ });
378
+ const output = await adapter.fetchOutput(run.runId);
379
+ const endedAt = now();
380
+ diagnostics.generationEndedAt = endedAt;
381
+ if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)) {
382
+ diagnostics.cancelledAt = endedAt;
383
+ fail('TURN_DEADLINE_EXCEEDED');
384
+ }
385
+ if (!output)
386
+ fail('SELECTION_OUTPUT_INVALID');
387
+ if (completionDeadlineAt !== null && endedAt > completionDeadlineAt) {
388
+ diagnostics.cancelledAt = endedAt;
389
+ fail('SELECTION_EXPIRED');
390
+ }
391
+ const metadata = await finishMetadata;
392
+ diagnostics.finishReason = metadata.finishReason;
393
+ diagnostics.usage = metadata.usage;
394
+ diagnostics.stage = 'validate';
395
+ return output.payload;
396
+ }
397
+ catch (error) {
398
+ // An abort can surface while the adapter reads the body (the fetch call
399
+ // itself already resolved), so classify it here, at the transport edge.
400
+ if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)) {
401
+ diagnostics.cancelledAt = now();
402
+ fail('TURN_DEADLINE_EXCEEDED');
403
+ }
404
+ throw error;
405
+ }
406
+ finally {
407
+ clearTimeout(ttfbTimer);
408
+ }
409
+ };
410
+ return {
411
+ select: selector,
412
+ report: () => ({ sends, status, failure, diagnostics }),
413
+ };
414
+ }
415
+ /**
416
+ * Minimal host-facing selection step: read the current frozen candidates,
417
+ * make at most one bounded model call, verify ref+digest, then independently
418
+ * revalidate the chosen principle's content/revision/authorization.
419
+ */
420
+ export async function runAdaptiveSelection(options) {
421
+ const earlyDiagnostics = emptyDiagnostics(options.admissionDeadlineAt);
422
+ const unavailable = (reason, stage) => {
423
+ earlyDiagnostics.stage = stage;
424
+ return { status: 'unavailable', target: null, reason, sends: 0, diagnostics: earlyDiagnostics };
425
+ };
426
+ const read = await readPromptActivationCandidates({
427
+ workspaceDir: options.workspaceDir,
428
+ includeAuthority: true,
429
+ });
430
+ if (read.aborted || read.warnings.length > 0) {
431
+ return unavailable(`candidates_unavailable:${read.warnings[0] ?? 'aborted'}`, 'idle');
432
+ }
433
+ const built = buildBoundedSelectionInput({
434
+ currentInput: options.currentPrompt,
435
+ candidates: read.principles,
436
+ });
437
+ if (!built.ok)
438
+ return unavailable(built.reason, 'idle');
439
+ const selector = createSingleModelSelector({
440
+ admissionDeadlineAt: options.admissionDeadlineAt,
441
+ model: options.model,
442
+ ...(options.generationTimeoutMs !== undefined ? { generationTimeoutMs: options.generationTimeoutMs } : {}),
443
+ ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),
444
+ ...(options.signal ? { signal: options.signal } : {}),
445
+ ...(options.outerDeadlineAt !== undefined ? { outerDeadlineAt: options.outerDeadlineAt } : {}),
446
+ ...(options.now ? { now: options.now } : {}),
447
+ ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
448
+ ...(options.PiAiRuntimeAdapterImpl
449
+ ? { PiAiRuntimeAdapterImpl: options.PiAiRuntimeAdapterImpl }
450
+ : {}),
451
+ });
452
+ let payload;
453
+ try {
454
+ payload = await selector.select(built.input);
455
+ }
456
+ catch {
457
+ const report = selector.report();
458
+ // The selector owns the failing stage and the failure code; do not
459
+ // overwrite either with a coarser guess.
460
+ const { diagnostics } = report;
461
+ const reason = report.failure ?? 'TRANSPORT_FAILED';
462
+ if (!diagnostics.failures.includes(reason))
463
+ diagnostics.failures.push(reason);
464
+ return { status: 'none', target: null, reason, sends: report.sends, diagnostics };
465
+ }
466
+ // The selector owns the timing facts (first byte, completion, cancellation).
467
+ const report = selector.report();
468
+ const { diagnostics } = report;
469
+ const { sends } = report;
470
+ const validated = validateSelectionResult(payload, built.input.entries);
471
+ if (!validated.ok) {
472
+ diagnostics.stage = 'validate';
473
+ diagnostics.failures.push(localFailureCode(validated.reason));
474
+ return { status: 'none', target: null, reason: validated.reason, sends, diagnostics };
475
+ }
476
+ if (!validated.selected) {
477
+ diagnostics.stage = 'done';
478
+ return { status: 'none', target: null, reason: validated.outcome, sends, diagnostics };
479
+ }
480
+ const target = validated.selected.principle;
481
+ diagnostics.stage = 'revalidate';
482
+ const now = options.now ?? Date.now;
483
+ const revalidationBudgetMs = options.generationTimeoutMs ?? ADAPTIVE_SELECTION_LIMITS.generationTimeoutMs;
484
+ const signal = options.signal ?? AbortSignal.timeout(options.outerDeadlineAt === undefined
485
+ ? revalidationBudgetMs
486
+ : Math.max(1, Math.min(revalidationBudgetMs, options.outerDeadlineAt - now())));
487
+ const stillValid = await revalidateAdaptivePrinciple(options.workspaceDir, target, signal);
488
+ const stale = outerDeadlineReached(now, options.outerDeadlineAt, options.signal);
489
+ if (!stillValid || stale) {
490
+ diagnostics.stage = 'done';
491
+ if (stale && !diagnostics.failures.includes('TURN_DEADLINE_EXCEEDED')) {
492
+ diagnostics.failures.push('TURN_DEADLINE_EXCEEDED');
493
+ }
494
+ if (stale)
495
+ diagnostics.cancelledAt = diagnostics.cancelledAt ?? now();
496
+ return {
497
+ status: 'none',
498
+ target: null,
499
+ reason: stale ? 'TURN_DEADLINE_EXCEEDED' : 'revalidation_failed',
500
+ sends,
501
+ diagnostics,
502
+ };
503
+ }
504
+ diagnostics.stage = 'done';
505
+ return { status: 'selected', target, reason: 'selected', sends, diagnostics };
506
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Adaptive Activation — deterministic pre-selection gate (PRI-1181).
3
+ *
4
+ * This gate runs BEFORE any candidate read and before any transport send.
5
+ * Its job is to spend ZERO model calls when the turn provably cannot benefit
6
+ * from a selection:
7
+ *
8
+ * - the Adaptive switch is off — enforced at construction time by
9
+ * `resolveAdaptiveSelectionModel`, so the provider is never created and no
10
+ * read/send happens (this module therefore has no "disabled" branch: a
11
+ * second check would be a second source of truth for the same switch);
12
+ * - the host did not bind the current turn (`sessionId`/`turnId`) or the
13
+ * prompt body is blank;
14
+ * - the remaining hook budget cannot cover even the slowest first byte ever
15
+ * observed on this path (see `minRemainingBudgetMs`);
16
+ * - the prompt is a pure social acknowledgement ("好的", "谢谢", "ok").
17
+ *
18
+ * Everything else — including short instructions and task continuations —
19
+ * keeps the existing fast single-send selection. "Simple" is decided by the
20
+ * acknowledgement vocabulary below, never by length alone: "继续" and
21
+ * "执行一下" look short but can carry a stage change.
22
+ */
23
+ export declare const ADAPTIVE_SKIP_LIMITS: {
24
+ /**
25
+ * Measured on this path (PRI-1170 v0.3, Codex exec, 2026-11): time-to-first-
26
+ * byte was 789 / 868 / 1426 ms. Below 1500 ms remaining, no answer has ever
27
+ * started; spending the send would only collide with the Native reserve.
28
+ * This is a gate, not a tuning knob for failing cases — the default runtime
29
+ * budget is 4200 ms, so the normal path is unaffected.
30
+ */
31
+ readonly minRemainingBudgetMs: 1500;
32
+ /** Longest acknowledgement (after normalization) still treated as pure social. */
33
+ readonly maxConfirmationChars: 12;
34
+ };
35
+ /**
36
+ * True only when the WHOLE normalized prompt is one or more acknowledgements.
37
+ * Removal is greedy on the longest token first, so a substantive sentence that
38
+ * merely contains an acknowledgement ("可以帮我修复这个 bug 吗") never matches.
39
+ */
40
+ export declare function isTrivialConfirmation(prompt: string): boolean;
41
+ export type AdaptiveSkipReason = 'missing_identity' | 'empty_prompt' | 'budget_insufficient' | 'trivial_confirmation';
42
+ export interface AdaptiveSkipInput {
43
+ readonly kind: string;
44
+ readonly sessionId?: string | undefined;
45
+ readonly turnId?: string | undefined;
46
+ readonly prompt: string;
47
+ /** Undefined = no outer host deadline (direct/lab calls): never budget-skip. */
48
+ readonly remainingBudgetMs?: number | undefined;
49
+ readonly minRemainingBudgetMs?: number | undefined;
50
+ }
51
+ export type AdaptiveSkipDecision = {
52
+ readonly skip: false;
53
+ } | {
54
+ readonly skip: true;
55
+ readonly reason: AdaptiveSkipReason;
56
+ };
57
+ /**
58
+ * Deterministic and ordered: identity first (it also proves lineage, rc-6),
59
+ * then the prompt itself, then the time budget, then the social check.
60
+ */
61
+ export declare function decideAdaptiveSkip(input: AdaptiveSkipInput): AdaptiveSkipDecision;
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Adaptive Activation — deterministic pre-selection gate (PRI-1181).
3
+ *
4
+ * This gate runs BEFORE any candidate read and before any transport send.
5
+ * Its job is to spend ZERO model calls when the turn provably cannot benefit
6
+ * from a selection:
7
+ *
8
+ * - the Adaptive switch is off — enforced at construction time by
9
+ * `resolveAdaptiveSelectionModel`, so the provider is never created and no
10
+ * read/send happens (this module therefore has no "disabled" branch: a
11
+ * second check would be a second source of truth for the same switch);
12
+ * - the host did not bind the current turn (`sessionId`/`turnId`) or the
13
+ * prompt body is blank;
14
+ * - the remaining hook budget cannot cover even the slowest first byte ever
15
+ * observed on this path (see `minRemainingBudgetMs`);
16
+ * - the prompt is a pure social acknowledgement ("好的", "谢谢", "ok").
17
+ *
18
+ * Everything else — including short instructions and task continuations —
19
+ * keeps the existing fast single-send selection. "Simple" is decided by the
20
+ * acknowledgement vocabulary below, never by length alone: "继续" and
21
+ * "执行一下" look short but can carry a stage change.
22
+ */
23
+ export const ADAPTIVE_SKIP_LIMITS = {
24
+ /**
25
+ * Measured on this path (PRI-1170 v0.3, Codex exec, 2026-11): time-to-first-
26
+ * byte was 789 / 868 / 1426 ms. Below 1500 ms remaining, no answer has ever
27
+ * started; spending the send would only collide with the Native reserve.
28
+ * This is a gate, not a tuning knob for failing cases — the default runtime
29
+ * budget is 4200 ms, so the normal path is unaffected.
30
+ */
31
+ minRemainingBudgetMs: 1500,
32
+ /** Longest acknowledgement (after normalization) still treated as pure social. */
33
+ maxConfirmationChars: 12,
34
+ };
35
+ /**
36
+ * Acknowledgements, longest first so the greedy removal below never leaves a
37
+ * fragment behind ("明白了" must be consumed before "明白").
38
+ * Deliberately excludes continuations such as 继续 / 开始 / 执行 / 再来.
39
+ */
40
+ const ACKNOWLEDGEMENTS = [
41
+ 'thankyouverymuch',
42
+ 'thanksalot',
43
+ 'soundsgood',
44
+ 'thankyou',
45
+ 'gotit',
46
+ '好的好的',
47
+ '明白了',
48
+ '收到啦',
49
+ '辛苦了',
50
+ '没问题',
51
+ '好的',
52
+ '好嘞',
53
+ '谢谢',
54
+ '多谢',
55
+ '收到',
56
+ '明白',
57
+ '可以',
58
+ '确认',
59
+ '了解',
60
+ '嗯嗯',
61
+ 'okay',
62
+ 'thanks',
63
+ 'thank',
64
+ 'yep',
65
+ 'yes',
66
+ 'ok',
67
+ '嗯',
68
+ '好',
69
+ '行',
70
+ ];
71
+ /** Strip whitespace, punctuation and emoji-ish separators before matching. */
72
+ function normalize(prompt) {
73
+ return prompt
74
+ .toLowerCase()
75
+ .replace(/[\s,。!?、,.!?~~…::;;"'“”‘’()()[\]【】{}<>《》/\\|+*=_-]+/g, '');
76
+ }
77
+ /**
78
+ * True only when the WHOLE normalized prompt is one or more acknowledgements.
79
+ * Removal is greedy on the longest token first, so a substantive sentence that
80
+ * merely contains an acknowledgement ("可以帮我修复这个 bug 吗") never matches.
81
+ */
82
+ export function isTrivialConfirmation(prompt) {
83
+ let rest = normalize(prompt);
84
+ if (rest.length === 0)
85
+ return true;
86
+ if (rest.length > ADAPTIVE_SKIP_LIMITS.maxConfirmationChars)
87
+ return false;
88
+ for (const token of ACKNOWLEDGEMENTS) {
89
+ if (rest.includes(token))
90
+ rest = rest.split(token).join('');
91
+ if (rest.length === 0)
92
+ return true;
93
+ }
94
+ return rest.length === 0;
95
+ }
96
+ /**
97
+ * Deterministic and ordered: identity first (it also proves lineage, rc-6),
98
+ * then the prompt itself, then the time budget, then the social check.
99
+ */
100
+ export function decideAdaptiveSkip(input) {
101
+ if (input.kind !== 'before_prompt_build')
102
+ return { skip: true, reason: 'missing_identity' };
103
+ if (!input.sessionId || !input.turnId)
104
+ return { skip: true, reason: 'missing_identity' };
105
+ if (!input.prompt.trim())
106
+ return { skip: true, reason: 'empty_prompt' };
107
+ const minimum = input.minRemainingBudgetMs ?? ADAPTIVE_SKIP_LIMITS.minRemainingBudgetMs;
108
+ if (input.remainingBudgetMs !== undefined && input.remainingBudgetMs < minimum) {
109
+ return { skip: true, reason: 'budget_insufficient' };
110
+ }
111
+ if (isTrivialConfirmation(input.prompt))
112
+ return { skip: true, reason: 'trivial_confirmation' };
113
+ return { skip: false };
114
+ }