create-principles-disciple 1.152.4 → 1.153.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 (149) hide show
  1. package/_release/product-identity.json +2 -2
  2. package/agent-skill/pd-setup/SKILL.md +70 -0
  3. package/codex-adapter/dist/background-selection.d.ts +9 -0
  4. package/codex-adapter/dist/background-selection.js +142 -0
  5. package/codex-adapter/dist/ingestion/adaptive-append-state.d.ts +209 -0
  6. package/codex-adapter/dist/ingestion/adaptive-append-state.js +544 -0
  7. package/codex-adapter/dist/pd-hook.js +329 -5
  8. package/codex-adapter/package.json +1 -1
  9. package/console/dist/server/config/pd-config-store.d.ts +11 -15
  10. package/console/dist/server/config/pd-config-store.js +92 -17
  11. package/console/dist/server/models/AdaptiveActivationConsoleModel.d.ts +43 -4
  12. package/console/dist/server/models/AdaptiveActivationConsoleModel.js +36 -7
  13. package/console/dist/server/routes/config.js +34 -8
  14. package/console/dist/web/assets/app.css +6 -0
  15. package/console/dist/web/assets/app.js +22 -22
  16. package/core/dist/runtime/activation/sqlite-approval-store.d.ts.map +1 -1
  17. package/core/dist/runtime/activation/sqlite-approval-store.js +7 -1
  18. package/core/dist/runtime/activation/sqlite-approval-store.js.map +1 -1
  19. package/core/dist/runtime/config/pd-config-feature-flags.d.ts +10 -0
  20. package/core/dist/runtime/config/pd-config-feature-flags.d.ts.map +1 -1
  21. package/core/dist/runtime/config/pd-config-feature-flags.js +14 -0
  22. package/core/dist/runtime/config/pd-config-feature-flags.js.map +1 -1
  23. package/core/dist/runtime/config/pd-config-types.d.ts +9 -0
  24. package/core/dist/runtime/config/pd-config-types.d.ts.map +1 -1
  25. package/core/dist/runtime/config/pd-config-types.js.map +1 -1
  26. package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
  27. package/core/dist/runtime/config/pd-config-validate.js +10 -2
  28. package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
  29. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  30. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +13 -2
  31. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  32. package/core/dist/runtime/intent/intent-doc.d.ts +22 -0
  33. package/core/dist/runtime/intent/intent-doc.d.ts.map +1 -1
  34. package/core/dist/runtime/intent/intent-doc.js +79 -0
  35. package/core/dist/runtime/intent/intent-doc.js.map +1 -1
  36. package/core/dist/runtime/intent/intent-friction-block.d.ts +7 -0
  37. package/core/dist/runtime/intent/intent-friction-block.d.ts.map +1 -1
  38. package/core/dist/runtime/intent/intent-friction-block.js +34 -1
  39. package/core/dist/runtime/intent/intent-friction-block.js.map +1 -1
  40. package/core/dist/runtime/intent/intent-snapshot.d.ts +44 -5
  41. package/core/dist/runtime/intent/intent-snapshot.d.ts.map +1 -1
  42. package/core/dist/runtime/intent/intent-snapshot.js +83 -15
  43. package/core/dist/runtime/intent/intent-snapshot.js.map +1 -1
  44. package/core/dist/runtime/intent/strategic-conflict-gate.d.ts +19 -0
  45. package/core/dist/runtime/intent/strategic-conflict-gate.d.ts.map +1 -1
  46. package/core/dist/runtime/intent/strategic-conflict-gate.js +94 -26
  47. package/core/dist/runtime/intent/strategic-conflict-gate.js.map +1 -1
  48. package/core/dist/runtime/internalization/diag-rootcause-runner.d.ts +22 -11
  49. package/core/dist/runtime/internalization/diag-rootcause-runner.d.ts.map +1 -1
  50. package/core/dist/runtime/internalization/diag-rootcause-runner.js +101 -28
  51. package/core/dist/runtime/internalization/diag-rootcause-runner.js.map +1 -1
  52. package/core/dist/runtime/internalization/dreamer-prompt-builder.d.ts.map +1 -1
  53. package/core/dist/runtime/internalization/dreamer-prompt-builder.js +1 -0
  54. package/core/dist/runtime/internalization/dreamer-prompt-builder.js.map +1 -1
  55. package/core/dist/runtime/internalization/dreamer-runner.d.ts +9 -2
  56. package/core/dist/runtime/internalization/dreamer-runner.d.ts.map +1 -1
  57. package/core/dist/runtime/internalization/dreamer-runner.js +11 -1
  58. package/core/dist/runtime/internalization/dreamer-runner.js.map +1 -1
  59. package/core/dist/runtime/internalization/evaluator-runner.d.ts.map +1 -1
  60. package/core/dist/runtime/internalization/evaluator-runner.js +7 -0
  61. package/core/dist/runtime/internalization/evaluator-runner.js.map +1 -1
  62. package/core/dist/runtime/internalization/formation-context.d.ts +16 -0
  63. package/core/dist/runtime/internalization/formation-context.d.ts.map +1 -1
  64. package/core/dist/runtime/internalization/formation-context.js +109 -8
  65. package/core/dist/runtime/internalization/formation-context.js.map +1 -1
  66. package/core/dist/runtime/internalization/index.d.ts +2 -2
  67. package/core/dist/runtime/internalization/index.d.ts.map +1 -1
  68. package/core/dist/runtime/internalization/index.js +1 -1
  69. package/core/dist/runtime/internalization/index.js.map +1 -1
  70. package/core/dist/runtime/internalization/intent-contract.d.ts +55 -4
  71. package/core/dist/runtime/internalization/intent-contract.d.ts.map +1 -1
  72. package/core/dist/runtime/internalization/intent-contract.js +111 -30
  73. package/core/dist/runtime/internalization/intent-contract.js.map +1 -1
  74. package/core/dist/runtime/internalization/philosopher-runner.d.ts +9 -2
  75. package/core/dist/runtime/internalization/philosopher-runner.d.ts.map +1 -1
  76. package/core/dist/runtime/internalization/philosopher-runner.js +11 -1
  77. package/core/dist/runtime/internalization/philosopher-runner.js.map +1 -1
  78. package/core/dist/runtime/internalization/scribe-runner.d.ts.map +1 -1
  79. package/core/dist/runtime/internalization/scribe-runner.js +17 -7
  80. package/core/dist/runtime/internalization/scribe-runner.js.map +1 -1
  81. package/core/dist/runtime/store/intent/sqlite-intent-decision-store.d.ts +10 -0
  82. package/core/dist/runtime/store/intent/sqlite-intent-decision-store.d.ts.map +1 -1
  83. package/core/dist/runtime/store/intent/sqlite-intent-decision-store.js +15 -4
  84. package/core/dist/runtime/store/intent/sqlite-intent-decision-store.js.map +1 -1
  85. package/core/dist/telemetry-event.d.ts +2 -2
  86. package/core/dist/telemetry-event.d.ts.map +1 -1
  87. package/core/dist/telemetry-event.js +6 -0
  88. package/core/dist/telemetry-event.js.map +1 -1
  89. package/core/package.json +1 -1
  90. package/dist/agent-skill.d.ts +59 -0
  91. package/dist/agent-skill.d.ts.map +1 -0
  92. package/dist/agent-skill.js +198 -0
  93. package/dist/agent-skill.js.map +1 -0
  94. package/dist/i18n.d.ts.map +1 -1
  95. package/dist/i18n.js +12 -0
  96. package/dist/i18n.js.map +1 -1
  97. package/dist/index.d.ts +3 -1
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +171 -3
  100. package/dist/index.js.map +1 -1
  101. package/dist/install-summary.d.ts +52 -0
  102. package/dist/install-summary.d.ts.map +1 -1
  103. package/dist/install-summary.js +104 -0
  104. package/dist/install-summary.js.map +1 -1
  105. package/dist/update/release-metadata-publisher.d.ts +3 -1
  106. package/dist/update/release-metadata-publisher.d.ts.map +1 -1
  107. package/dist/update/release-metadata-publisher.js +33 -2
  108. package/dist/update/release-metadata-publisher.js.map +1 -1
  109. package/dist/update/trust-metadata.d.ts +21 -0
  110. package/dist/update/trust-metadata.d.ts.map +1 -1
  111. package/dist/update/trust-metadata.js +192 -4
  112. package/dist/update/trust-metadata.js.map +1 -1
  113. package/host-runtime/dist/adaptive-background-append.d.ts +70 -0
  114. package/host-runtime/dist/adaptive-background-append.js +165 -0
  115. package/host-runtime/dist/index.d.ts +1 -0
  116. package/host-runtime/dist/index.js +5 -0
  117. package/host-runtime/package.json +1 -1
  118. package/package.json +3 -2
  119. package/pd-cli/dist/commands/health-console.d.ts +21 -0
  120. package/pd-cli/dist/commands/health-console.d.ts.map +1 -0
  121. package/pd-cli/dist/commands/health-console.js +106 -0
  122. package/pd-cli/dist/commands/health-console.js.map +1 -0
  123. package/pd-cli/dist/commands/health.d.ts +159 -0
  124. package/pd-cli/dist/commands/health.d.ts.map +1 -1
  125. package/pd-cli/dist/commands/health.js +162 -2
  126. package/pd-cli/dist/commands/health.js.map +1 -1
  127. package/pd-cli/dist/commands/mcp-probe.d.ts +48 -0
  128. package/pd-cli/dist/commands/mcp-probe.d.ts.map +1 -0
  129. package/pd-cli/dist/commands/mcp-probe.js +479 -0
  130. package/pd-cli/dist/commands/mcp-probe.js.map +1 -0
  131. package/pd-cli/dist/commands/runtime-internalization-run-once.js +2 -2
  132. package/pd-cli/dist/commands/runtime-internalization-run-once.js.map +1 -1
  133. package/pd-cli/dist/program.d.ts.map +1 -1
  134. package/pd-cli/dist/program.js +57 -0
  135. package/pd-cli/dist/program.js.map +1 -1
  136. package/pd-cli/dist/services/console-launcher.d.ts +3 -0
  137. package/pd-cli/dist/services/console-launcher.d.ts.map +1 -1
  138. package/pd-cli/dist/services/console-launcher.js +3 -2
  139. package/pd-cli/dist/services/console-launcher.js.map +1 -1
  140. package/pd-cli/package.json +1 -1
  141. package/plugin/dist/bundle.js +533 -449
  142. package/plugin/dist/openclaw.plugin.json +1 -1
  143. package/plugin/openclaw.plugin.json +1 -1
  144. package/plugin/package.json +1 -1
  145. package/release-manager/dist/i18n.js +12 -0
  146. package/release-manager/dist/update/trust-metadata.js +192 -4
  147. package/release-manager/package.json +2 -1
  148. package/workbuddy-adapter/dist/pd-hook.js +37 -3
  149. package/workbuddy-adapter/package.json +1 -1
@@ -0,0 +1,544 @@
1
+ /**
2
+ * PRI-1196 — short-lived state for the background Adaptive append.
3
+ *
4
+ * One turn's state lives under `<workspace>/.state`:
5
+ * started_<session>_<turn>.json this turn is tracked (tool observations)
6
+ * job_<session>_<turn>.json what the background process must decide
7
+ * result_<session>_<turn>.json the ONE ready decision (ids only, no text)
8
+ * tools_<session>_<turn>.jsonl pre/post tool observations of this turn
9
+ * reported_<session>_<turn>.json one-shot marker for a terminal fact
10
+ * ended_<session>_<turn>.json Stop marker a late selector must observe
11
+ *
12
+ * The `started` marker is what keeps the ordering gate alive for the whole
13
+ * turn: the selector withdraws the job as soon as it starts, and the result
14
+ * does not exist until scoring ends, so "job or result exists" would leave the
15
+ * entire scoring window unobserved (P1-1). Stop removes the turn state.
16
+ * SessionStart cannot address one turn (its payload has no `turn_id`), so it
17
+ * only sweeps residue above the age bound.
18
+ *
19
+ * Nothing here is durable governance truth: the files are bound to one
20
+ * host-supplied `session_id` + `turn_id` and expire after a 20 s window.
21
+ * Delivery is claimed with `renameSync`, so a replayed or concurrent
22
+ * PostToolUse can emit at most one append.
23
+ */
24
+ import { randomUUID, createHash } from 'node:crypto';
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+ import { spawn } from 'node:child_process';
28
+ import { fileURLToPath } from 'node:url';
29
+ import { appendEventLogLine } from '@principles/core/runtime';
30
+ export const ADAPTIVE_APPEND_SCHEMA_VERSION = 1;
31
+ /** Whole-turn window for a background decision to still be usable. */
32
+ export const ADAPTIVE_APPEND_TTL_MS = 20_000;
33
+ /** Residue bound for files an abnormal exit left behind. */
34
+ export const ADAPTIVE_APPEND_MAX_AGE_MS = 10 * 60_000;
35
+ /** Maximum complete turn history accepted at the append boundary. */
36
+ export const ADAPTIVE_APPEND_MAX_OBSERVATIONS = 64;
37
+ const PREFIX = 'pd_adaptive_append_';
38
+ function stateDir(workspaceDir) {
39
+ return path.join(workspaceDir, '.state');
40
+ }
41
+ function keyOf(value) {
42
+ return createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
43
+ }
44
+ function suffix(sessionId, turnId) {
45
+ return `${keyOf(sessionId)}_${keyOf(turnId)}`;
46
+ }
47
+ function jobPathFor(workspaceDir, sessionId, turnId) {
48
+ return path.join(stateDir(workspaceDir), `${PREFIX}job_${suffix(sessionId, turnId)}.json`);
49
+ }
50
+ function resultPathFor(workspaceDir, sessionId, turnId) {
51
+ return path.join(stateDir(workspaceDir), `${PREFIX}result_${suffix(sessionId, turnId)}.json`);
52
+ }
53
+ function toolsPathFor(workspaceDir, sessionId, turnId) {
54
+ return path.join(stateDir(workspaceDir), `${PREFIX}tools_${suffix(sessionId, turnId)}.jsonl`);
55
+ }
56
+ function reportedPathFor(workspaceDir, sessionId, turnId) {
57
+ return path.join(stateDir(workspaceDir), `${PREFIX}reported_${suffix(sessionId, turnId)}.json`);
58
+ }
59
+ function startedPathFor(workspaceDir, sessionId, turnId) {
60
+ return path.join(stateDir(workspaceDir), `${PREFIX}started_${suffix(sessionId, turnId)}.json`);
61
+ }
62
+ function endedPathFor(workspaceDir, sessionId, turnId) {
63
+ return path.join(stateDir(workspaceDir), `${PREFIX}ended_${suffix(sessionId, turnId)}.json`);
64
+ }
65
+ /**
66
+ * Turn-scoped "track this turn" marker. Written once at UserPromptSubmit,
67
+ * before the selector can withdraw the job, so the ordering gate keeps
68
+ * observing Pre/PostToolUse for the whole scoring window.
69
+ *
70
+ * The return value is also the "at most one scoring request per turn" gate:
71
+ * `exists` means a replayed prompt for the same turn must not spawn again.
72
+ */
73
+ export function markAdaptiveTurnStarted(input) {
74
+ try {
75
+ fs.mkdirSync(stateDir(input.workspaceDir), { recursive: true });
76
+ fs.writeFileSync(startedPathFor(input.workspaceDir, input.sessionId, input.turnId), JSON.stringify({ at: Date.now() }), { flag: 'wx' });
77
+ return 'created';
78
+ }
79
+ catch (error) {
80
+ if (error instanceof Error && Object.hasOwn(error, 'code') && Reflect.get(error, 'code') === 'EEXIST')
81
+ return 'exists';
82
+ return 'failed';
83
+ }
84
+ }
85
+ /** True while this turn may still record observations or has a decision artifact. */
86
+ export function hasAdaptiveAppendTurn(input) {
87
+ try {
88
+ return fs.existsSync(startedPathFor(input.workspaceDir, input.sessionId, input.turnId))
89
+ || fs.existsSync(jobPathFor(input.workspaceDir, input.sessionId, input.turnId))
90
+ || fs.existsSync(resultPathFor(input.workspaceDir, input.sessionId, input.turnId));
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ }
96
+ /**
97
+ * Mark the turn as finished before the cleanup. A background selector that
98
+ * finishes after Stop checks this marker and discards its decision, so a
99
+ * late result can never surface as this turn's outcome.
100
+ */
101
+ export function markAdaptiveTurnEnded(input) {
102
+ try {
103
+ fs.mkdirSync(stateDir(input.workspaceDir), { recursive: true });
104
+ fs.writeFileSync(endedPathFor(input.workspaceDir, input.sessionId, input.turnId), JSON.stringify({ at: Date.now() }), { flag: 'wx' });
105
+ }
106
+ catch {
107
+ // Already marked (or unwritable): the conservative branch is unchanged.
108
+ }
109
+ }
110
+ export function adaptiveTurnEnded(input) {
111
+ try {
112
+ return fs.existsSync(endedPathFor(input.workspaceDir, input.sessionId, input.turnId));
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ }
118
+ /** The installed hook entry of the process that wrote the job. */
119
+ export function currentHookIdentity() {
120
+ const [, entryPath] = process.argv;
121
+ if (typeof entryPath !== 'string' || entryPath.length === 0)
122
+ return null;
123
+ try {
124
+ return { entryPath, mtimeMs: fs.statSync(entryPath).mtimeMs };
125
+ }
126
+ catch {
127
+ return null;
128
+ }
129
+ }
130
+ function isRecord(value) {
131
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
132
+ }
133
+ function isFiniteNonNegative(value) {
134
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
135
+ }
136
+ /** rc-1/rc-3: strict job validation; an invalid job is unusable, never guessed. */
137
+ export function parseAdaptiveAppendJob(value) {
138
+ if (!isRecord(value))
139
+ return null;
140
+ if (value.schemaVersion !== ADAPTIVE_APPEND_SCHEMA_VERSION)
141
+ return null;
142
+ if (!isFiniteNonNegative(value.createdAt))
143
+ return null;
144
+ if (typeof value.sessionId !== 'string' || value.sessionId.length === 0)
145
+ return null;
146
+ if (typeof value.turnId !== 'string' || value.turnId.length === 0)
147
+ return null;
148
+ if (typeof value.workspaceDir !== 'string' || value.workspaceDir.length === 0)
149
+ return null;
150
+ if (typeof value.promptContent !== 'string')
151
+ return null;
152
+ if (!Array.isArray(value.nativeActivationIds) || !value.nativeActivationIds.every((id) => typeof id === 'string'))
153
+ return null;
154
+ if (!isFiniteNonNegative(value.nativeChars) || !isFiniteNonNegative(value.budgetChars))
155
+ return null;
156
+ let hookIdentity = null;
157
+ if (value.hookIdentity !== null && value.hookIdentity !== undefined) {
158
+ if (!isRecord(value.hookIdentity)
159
+ || typeof value.hookIdentity.entryPath !== 'string'
160
+ || typeof value.hookIdentity.mtimeMs !== 'number')
161
+ return null;
162
+ hookIdentity = { entryPath: value.hookIdentity.entryPath, mtimeMs: value.hookIdentity.mtimeMs };
163
+ }
164
+ return {
165
+ schemaVersion: ADAPTIVE_APPEND_SCHEMA_VERSION,
166
+ createdAt: value.createdAt,
167
+ sessionId: value.sessionId,
168
+ turnId: value.turnId,
169
+ workspaceDir: value.workspaceDir,
170
+ promptContent: value.promptContent,
171
+ nativeActivationIds: [...value.nativeActivationIds],
172
+ nativeChars: value.nativeChars,
173
+ budgetChars: value.budgetChars,
174
+ hookIdentity,
175
+ };
176
+ }
177
+ export function parseAdaptiveAppendResult(value) {
178
+ if (!isRecord(value))
179
+ return null;
180
+ if (value.schemaVersion !== ADAPTIVE_APPEND_SCHEMA_VERSION)
181
+ return null;
182
+ if (!isFiniteNonNegative(value.createdAt) || !isFiniteNonNegative(value.startedAt))
183
+ return null;
184
+ if (typeof value.sessionId !== 'string' || typeof value.turnId !== 'string')
185
+ return null;
186
+ if (!isRecord(value.target))
187
+ return null;
188
+ const { target } = value;
189
+ if (typeof target.revisionFingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(target.revisionFingerprint))
190
+ return null;
191
+ if (typeof target.principleId !== 'string' || typeof target.activationId !== 'string' || typeof target.artifactId !== 'string')
192
+ return null;
193
+ if (!isFiniteNonNegative(value.directiveChars) || !isFiniteNonNegative(value.budgetChars) || !isFiniteNonNegative(value.nativeChars))
194
+ return null;
195
+ if (!Array.isArray(value.nativeActivationIds) || !value.nativeActivationIds.every((id) => typeof id === 'string'))
196
+ return null;
197
+ let hookIdentity = null;
198
+ if (value.hookIdentity !== null && value.hookIdentity !== undefined) {
199
+ if (!isRecord(value.hookIdentity)
200
+ || typeof value.hookIdentity.entryPath !== 'string'
201
+ || typeof value.hookIdentity.mtimeMs !== 'number')
202
+ return null;
203
+ hookIdentity = { entryPath: value.hookIdentity.entryPath, mtimeMs: value.hookIdentity.mtimeMs };
204
+ }
205
+ return {
206
+ schemaVersion: ADAPTIVE_APPEND_SCHEMA_VERSION,
207
+ createdAt: value.createdAt,
208
+ startedAt: value.startedAt,
209
+ sessionId: value.sessionId,
210
+ turnId: value.turnId,
211
+ target: { principleId: target.principleId, activationId: target.activationId, artifactId: target.artifactId, revisionFingerprint: target.revisionFingerprint },
212
+ directiveChars: value.directiveChars,
213
+ nativeActivationIds: [...value.nativeActivationIds],
214
+ nativeChars: value.nativeChars,
215
+ budgetChars: value.budgetChars,
216
+ hookIdentity,
217
+ };
218
+ }
219
+ function writeAtomic(target, body, mode) {
220
+ fs.mkdirSync(path.dirname(target), { recursive: true });
221
+ const temp = `${target}.${process.pid}.${randomUUID()}.tmp`;
222
+ fs.writeFileSync(temp, JSON.stringify(body), mode === undefined ? undefined : { mode });
223
+ fs.renameSync(temp, target);
224
+ }
225
+ function unlinkQuietly(target) {
226
+ try {
227
+ fs.unlinkSync(target);
228
+ }
229
+ catch {
230
+ // ENOENT and an in-use file both mean "nothing to release".
231
+ }
232
+ }
233
+ /**
234
+ * Parent side: create the job ONCE per turn, then hand it to a DETACHED
235
+ * process. `wx` is the gate behind "at most one scoring request per turn": a
236
+ * retried/replayed UserPromptSubmit for the same turn cannot replace the job
237
+ * and spawn a second selector. The job carries the Owner prompt for the
238
+ * decision request only, so the file is owner-only (0600) and is withdrawn by
239
+ * the selector as soon as it reads it; a write that never reaches the selector
240
+ * is removed here or aged out by the residue sweep.
241
+ */
242
+ export function writeAdaptiveAppendJob(job) {
243
+ const jobPath = jobPathFor(job.workspaceDir, job.sessionId, job.turnId);
244
+ try {
245
+ fs.mkdirSync(path.dirname(jobPath), { recursive: true });
246
+ fs.writeFileSync(jobPath, JSON.stringify(job), { flag: 'wx', mode: 0o600 });
247
+ return { ok: true, jobPath };
248
+ }
249
+ catch (error) {
250
+ if (error instanceof Error && Object.hasOwn(error, 'code') && Reflect.get(error, 'code') === 'EEXIST') {
251
+ return { ok: false, reason: 'already_started' };
252
+ }
253
+ return { ok: false, reason: 'job_write_failed' };
254
+ }
255
+ }
256
+ /** A job that could not be handed off must not leave the prompt on disk. */
257
+ export function discardAdaptiveAppendJob(jobPath) {
258
+ unlinkQuietly(jobPath);
259
+ }
260
+ /**
261
+ * Spawn the background selector. `stdio: 'ignore'` is mandatory: a detached
262
+ * child that inherited the hook's stdout pipe would keep that pipe open and
263
+ * hold the host's first request until the decision finished.
264
+ */
265
+ export function spawnAdaptiveBackgroundSelection(jobPath) {
266
+ try {
267
+ const entry = fileURLToPath(new URL('../background-selection.js', import.meta.url));
268
+ const child = spawn(process.execPath, [entry, jobPath], {
269
+ detached: true,
270
+ stdio: 'ignore',
271
+ windowsHide: true,
272
+ env: process.env,
273
+ });
274
+ // Async spawn failures arrive as an 'error' event, not a throw. Without a
275
+ // listener that event is an uncaught exception in the hook process, which
276
+ // would break the fail-open contract; the failure is already represented by
277
+ // the job file the residue sweep will remove.
278
+ child.on('error', () => undefined);
279
+ child.unref();
280
+ if (child.pid === undefined)
281
+ return { ok: false, reason: 'spawn_no_pid' };
282
+ return { ok: true, pid: child.pid };
283
+ }
284
+ catch (error) {
285
+ return { ok: false, reason: error instanceof Error ? error.message.slice(0, 160) : 'spawn_failed' };
286
+ }
287
+ }
288
+ /** Child side: read and immediately withdraw the job (the prompt is not kept). */
289
+ export function takeAdaptiveAppendJob(jobPath) {
290
+ let raw;
291
+ try {
292
+ raw = fs.readFileSync(jobPath, 'utf8');
293
+ }
294
+ catch {
295
+ return null;
296
+ }
297
+ try {
298
+ fs.unlinkSync(jobPath);
299
+ }
300
+ catch {
301
+ // The job is single-use; a leftover file is aged out by the residue sweep.
302
+ }
303
+ try {
304
+ return parseAdaptiveAppendJob(JSON.parse(raw));
305
+ }
306
+ catch {
307
+ return null;
308
+ }
309
+ }
310
+ /** Persist the ONE ready decision for this turn. */
311
+ export function writeAdaptiveAppendResultFor(workspaceDir, result) {
312
+ writeAtomic(resultPathFor(workspaceDir, result.sessionId, result.turnId), result, 0o600);
313
+ }
314
+ /** Withdraw a result whose turn ended while it was being written. */
315
+ export function discardAdaptiveAppendResult(workspaceDir, sessionId, turnId) {
316
+ unlinkQuietly(resultPathFor(workspaceDir, sessionId, turnId));
317
+ }
318
+ /**
319
+ * Atomically claim the ready result. `renameSync` is the mutex: exactly one
320
+ * concurrent consumer can move the file, so a replayed callback emits nothing.
321
+ */
322
+ export function claimAdaptiveAppendResult(input) {
323
+ const resultPath = resultPathFor(input.workspaceDir, input.sessionId, input.turnId);
324
+ const claimPath = `${resultPath}.claimed_${process.pid}_${randomUUID()}`;
325
+ try {
326
+ fs.renameSync(resultPath, claimPath);
327
+ }
328
+ catch (error) {
329
+ if (error instanceof Error && Object.hasOwn(error, 'code') && Reflect.get(error, 'code') === 'ENOENT') {
330
+ return { status: 'absent' };
331
+ }
332
+ return { status: 'invalid', reason: 'claim_failed' };
333
+ }
334
+ let parsed;
335
+ try {
336
+ parsed = parseAdaptiveAppendResult(JSON.parse(fs.readFileSync(claimPath, 'utf8')));
337
+ }
338
+ catch {
339
+ parsed = null;
340
+ }
341
+ if (!parsed) {
342
+ unlinkQuietly(claimPath);
343
+ return { status: 'invalid', reason: 'result_unreadable' };
344
+ }
345
+ if (parsed.sessionId !== input.sessionId || parsed.turnId !== input.turnId) {
346
+ unlinkQuietly(claimPath);
347
+ return { status: 'invalid', reason: 'identity_mismatch' };
348
+ }
349
+ if (!Number.isFinite(parsed.startedAt) || input.now - parsed.startedAt > ADAPTIVE_APPEND_TTL_MS) {
350
+ unlinkQuietly(claimPath);
351
+ return { status: 'expired', reason: 'ttl_expired' };
352
+ }
353
+ return { status: 'ready', result: parsed, claimPath };
354
+ }
355
+ export function releaseAdaptiveAppendClaim(claimPath) {
356
+ unlinkQuietly(claimPath);
357
+ }
358
+ export function appendToolObservation(input) {
359
+ const target = toolsPathFor(input.workspaceDir, input.sessionId, input.turnId);
360
+ try {
361
+ fs.mkdirSync(path.dirname(target), { recursive: true });
362
+ fs.appendFileSync(target, `${JSON.stringify(input.observation)}\n`);
363
+ }
364
+ catch {
365
+ // Observation loss downgrades to the conservative branch: no proof of
366
+ // ordering means no append. Never fail the tool call.
367
+ }
368
+ }
369
+ export function readToolObservations(input) {
370
+ let raw;
371
+ try {
372
+ raw = fs.readFileSync(toolsPathFor(input.workspaceDir, input.sessionId, input.turnId), 'utf8');
373
+ }
374
+ catch {
375
+ return [];
376
+ }
377
+ const lines = raw.split('\n').filter((line) => line.trim().length > 0);
378
+ // A partial history cannot establish that the current tool preceded the first write.
379
+ if (lines.length > ADAPTIVE_APPEND_MAX_OBSERVATIONS)
380
+ return [];
381
+ const observations = [];
382
+ for (const line of lines) {
383
+ try {
384
+ const value = JSON.parse(line);
385
+ if (!isRecord(value))
386
+ return [];
387
+ if (value.phase !== 'pre' && value.phase !== 'post')
388
+ return [];
389
+ if (typeof value.toolCallId !== 'string' || typeof value.toolName !== 'string')
390
+ return [];
391
+ if (typeof value.canonicalKind !== 'string' || typeof value.readOnly !== 'boolean' || !isFiniteNonNegative(value.at))
392
+ return [];
393
+ observations.push({
394
+ phase: value.phase,
395
+ toolCallId: value.toolCallId,
396
+ toolName: value.toolName,
397
+ canonicalKind: value.canonicalKind,
398
+ readOnly: value.readOnly,
399
+ at: value.at,
400
+ });
401
+ }
402
+ catch {
403
+ return [];
404
+ }
405
+ }
406
+ return observations;
407
+ }
408
+ /**
409
+ * The ordering gate:
410
+ * - the CURRENT call must have been observed at both boundaries — a lone
411
+ * post proves nothing about what happened before it;
412
+ * - a `write` call anywhere in this turn ends the opportunity;
413
+ * - an execute call that is not classified `safe`, or an unresolved kind,
414
+ * is "semantics unknown" and ends it too;
415
+ * - another call opened and not yet closed means the completion order of a
416
+ * parallel batch cannot be proven; a replayed post is a duplicate callback.
417
+ */
418
+ export function evaluateAppendOrdering(observations, currentToolCallId) {
419
+ if (observations.length === 0)
420
+ return { ok: false, reason: 'ordering_unprovable' };
421
+ const opened = new Set(observations.filter((entry) => entry.phase === 'pre').map((entry) => entry.toolCallId));
422
+ const closed = new Set(observations.filter((entry) => entry.phase === 'post').map((entry) => entry.toolCallId));
423
+ let sawCurrentPost = false;
424
+ for (const entry of observations) {
425
+ if (entry.toolCallId === currentToolCallId && entry.phase === 'post') {
426
+ if (sawCurrentPost)
427
+ return { ok: false, reason: 'duplicate_callback' };
428
+ sawCurrentPost = true;
429
+ continue;
430
+ }
431
+ if (entry.canonicalKind === 'write')
432
+ return { ok: false, reason: 'mutating_tool_observed' };
433
+ if (entry.canonicalKind === 'other')
434
+ return { ok: false, reason: 'unknown_tool_observed' };
435
+ if (entry.canonicalKind === 'execute' && entry.readOnly !== true) {
436
+ return { ok: false, reason: 'unknown_tool_observed' };
437
+ }
438
+ }
439
+ if (!sawCurrentPost || !opened.has(currentToolCallId) || !closed.has(currentToolCallId)) {
440
+ return { ok: false, reason: 'ordering_unprovable' };
441
+ }
442
+ for (const entry of observations) {
443
+ if (entry.phase !== 'pre')
444
+ continue;
445
+ if (entry.toolCallId === currentToolCallId)
446
+ continue;
447
+ if (!closed.has(entry.toolCallId))
448
+ return { ok: false, reason: 'parallel_order_unprovable' };
449
+ }
450
+ return { ok: true };
451
+ }
452
+ /** Delete every short-lived file of one turn (Stop / terminal drop). */
453
+ export function clearAdaptiveAppendTurn(input) {
454
+ const dir = stateDir(input.workspaceDir);
455
+ const keys = suffix(input.sessionId, input.turnId);
456
+ let entries;
457
+ try {
458
+ entries = fs.readdirSync(dir);
459
+ }
460
+ catch {
461
+ return;
462
+ }
463
+ for (const name of entries) {
464
+ if (!name.startsWith(PREFIX) || !name.includes(keys))
465
+ continue;
466
+ // The ended marker outlives the turn's state: a late selector reads it.
467
+ if (name.startsWith(`${PREFIX}ended_`))
468
+ continue;
469
+ unlinkQuietly(path.join(dir, name));
470
+ }
471
+ }
472
+ /** Opportunistic residue sweep; bounded and age-based, never touches fresh state. */
473
+ export function clearStaleAdaptiveAppendState(workspaceDir, now) {
474
+ const dir = stateDir(workspaceDir);
475
+ let entries;
476
+ try {
477
+ entries = fs.readdirSync(dir).slice(0, 200);
478
+ }
479
+ catch {
480
+ return;
481
+ }
482
+ for (const name of entries) {
483
+ if (!name.startsWith(PREFIX))
484
+ continue;
485
+ const target = path.join(dir, name);
486
+ try {
487
+ if (now - fs.statSync(target).mtimeMs > ADAPTIVE_APPEND_MAX_AGE_MS)
488
+ unlinkQuietly(target);
489
+ }
490
+ catch {
491
+ continue;
492
+ }
493
+ }
494
+ }
495
+ /**
496
+ * One-shot marker for a terminal fact of this turn. Returns true only to the
497
+ * caller that created it, so concurrent hooks emit the fact once.
498
+ */
499
+ export function claimAdaptiveReportMarker(input) {
500
+ const target = reportedPathFor(input.workspaceDir, input.sessionId, input.turnId);
501
+ try {
502
+ fs.mkdirSync(path.dirname(target), { recursive: true });
503
+ fs.writeFileSync(target, JSON.stringify({ reason: input.reason, at: Date.now() }), { flag: 'wx' });
504
+ return true;
505
+ }
506
+ catch {
507
+ return false;
508
+ }
509
+ }
510
+ /**
511
+ * The console reads `runtime_v2_prompt_activations_injected` with an
512
+ * `adaptive` fact. "Background selected" is emitted with empty arrays (no
513
+ * injection claim); "appended" carries exactly the one principle that was
514
+ * added to the later request.
515
+ */
516
+ export function appendAdaptiveAppendFact(input) {
517
+ const { appended } = input;
518
+ const data = {
519
+ eventId: randomUUID(),
520
+ sessionId: input.sessionId,
521
+ runId: input.turnId,
522
+ workspaceDir: input.workspaceDir,
523
+ principleIds: appended ? [appended.principleId] : [],
524
+ activationIds: appended ? [appended.activationId] : [],
525
+ artifactIds: appended ? [appended.artifactId] : [],
526
+ injectedCount: appended ? 1 : 0,
527
+ skippedWarnings: [],
528
+ injectedCharCount: input.injectedCharCount,
529
+ budget: input.budget,
530
+ hostKind: 'codex',
531
+ adaptive: {
532
+ resultCode: input.resultCode.slice(0, 240),
533
+ scored: input.scored,
534
+ ...(appended ? { appendedActivationId: appended.activationId } : {}),
535
+ },
536
+ };
537
+ appendEventLogLine(input.stateDir, {
538
+ ts: new Date().toISOString(),
539
+ type: 'runtime_v2_prompt_activations_injected',
540
+ category: 'injected',
541
+ sessionId: input.sessionId,
542
+ data,
543
+ });
544
+ }