@primitive.ai/prim 0.1.0-alpha.12 → 0.1.0-alpha.121

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 (57) hide show
  1. package/README.md +550 -38
  2. package/SKILL.md +320 -75
  3. package/assets/primitive-gameplan/SKILL.md +134 -0
  4. package/assets/primitive-gameplan/claude-hooks.json +28 -0
  5. package/assets/primitive-gameplan/scripts/activate.mjs +37 -0
  6. package/dist/chunk-2DNC2MUN.js +503 -0
  7. package/dist/chunk-2PFJJO2M.js +262 -0
  8. package/dist/chunk-4GLVJLEQ.js +55 -0
  9. package/dist/chunk-4GYJHN26.js +1440 -0
  10. package/dist/chunk-6DEROXLM.js +22695 -0
  11. package/dist/chunk-7LXRFXZG.js +1992 -0
  12. package/dist/chunk-AKGRY7OU.js +1572 -0
  13. package/dist/chunk-BHT6X3T5.js +1450 -0
  14. package/dist/chunk-DQ4I3FLF.js +164 -0
  15. package/dist/chunk-DVHD6LBQ.js +258 -0
  16. package/dist/chunk-EZXEWFDG.js +210 -0
  17. package/dist/chunk-HG7FJK7R.js +253 -0
  18. package/dist/chunk-JSBRDJBE.js +30 -0
  19. package/dist/chunk-JXRJLHE4.js +168 -0
  20. package/dist/chunk-JZC2LHS6.js +209 -0
  21. package/dist/chunk-KZB4ABIB.js +13 -0
  22. package/dist/chunk-LQLP26RL.js +459 -0
  23. package/dist/chunk-M4NZJCPQ.js +135 -0
  24. package/dist/chunk-MRDY7VQP.js +96 -0
  25. package/dist/chunk-NMZSCSMY.js +157 -0
  26. package/dist/chunk-NQZLXYTW.js +36 -0
  27. package/dist/chunk-OXW6PSPT.js +439 -0
  28. package/dist/chunk-OYHYCK4K.js +13 -0
  29. package/dist/chunk-S3ZIMGXV.js +844 -0
  30. package/dist/chunk-WN7OURQ3.js +175 -0
  31. package/dist/daemon/server.js +26506 -0
  32. package/dist/hook-runtime/daemon/server.js +26507 -0
  33. package/dist/hook-runtime/hooks/post-commit.js +23898 -0
  34. package/dist/hook-runtime/hooks/post-rewrite.js +23797 -0
  35. package/dist/hook-runtime/hooks/post-tool-use.js +36213 -0
  36. package/dist/hook-runtime/hooks/pre-commit.js +1741 -0
  37. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +35071 -0
  38. package/dist/hook-runtime/hooks/pre-tool-use.js +96 -0
  39. package/dist/hook-runtime/hooks/prim-hook.js +36273 -0
  40. package/dist/hook-runtime/hooks/session-end.js +1250 -0
  41. package/dist/hook-runtime/hooks/session-start.js +34021 -0
  42. package/dist/hook-runtime/index.js +71700 -0
  43. package/dist/hook-runtime/statusline-main.js +954 -0
  44. package/dist/hooks/post-commit.js +197 -0
  45. package/dist/hooks/post-rewrite.js +206 -0
  46. package/dist/hooks/post-tool-use.js +295 -0
  47. package/dist/hooks/pre-commit.js +16 -108
  48. package/dist/hooks/pre-tool-use-worker.js +238 -0
  49. package/dist/hooks/pre-tool-use.js +87 -0
  50. package/dist/hooks/prim-hook.js +245 -0
  51. package/dist/hooks/session-end.js +67 -0
  52. package/dist/hooks/session-start.js +312 -0
  53. package/dist/index.js +11249 -572
  54. package/dist/statusline-main.js +953 -0
  55. package/package.json +51 -17
  56. package/skills/prim-welcome/SKILL.md +197 -0
  57. package/dist/chunk-3APLWTLB.js +0 -165
@@ -0,0 +1,503 @@
1
+ import {
2
+ formatStatusline
3
+ } from "./chunk-JXRJLHE4.js";
4
+ import {
5
+ daemonPrincipalsMatch,
6
+ daemonRequest,
7
+ resolveDaemonPrincipal
8
+ } from "./chunk-NMZSCSMY.js";
9
+ import {
10
+ getSiteUrl,
11
+ isSessionEnded,
12
+ terminalSafeText
13
+ } from "./chunk-S3ZIMGXV.js";
14
+ import {
15
+ decisionIngestionStatus,
16
+ gitToplevel,
17
+ packageVersion,
18
+ primConfigDirectory,
19
+ repositoryBindingState,
20
+ withFileLock
21
+ } from "./chunk-4GYJHN26.js";
22
+
23
+ // src/hooks/codex-context.ts
24
+ import { createHash, randomBytes as randomBytes2 } from "crypto";
25
+ import {
26
+ chmodSync,
27
+ existsSync,
28
+ mkdirSync,
29
+ readFileSync,
30
+ readdirSync,
31
+ renameSync,
32
+ rmSync,
33
+ statSync,
34
+ unlinkSync,
35
+ writeFileSync
36
+ } from "fs";
37
+ import { join } from "path";
38
+
39
+ // src/daemon/decision-digest-cache.ts
40
+ import { randomBytes } from "crypto";
41
+ var DECISION_DIGEST_CACHE_LIMIT = 100;
42
+ var DECISION_DIGEST_CACHE_WINDOW = "24h";
43
+ var DECISION_DIGEST_CACHE_PATH = `/api/cli/decisions/recent?limit=${String(DECISION_DIGEST_CACHE_LIMIT)}&since=${DECISION_DIGEST_CACHE_WINDOW}`;
44
+ var DECISION_DRAFT_DIGEST_CACHE_PATH = `${DECISION_DIGEST_CACHE_PATH}&drafts=true`;
45
+ var SAFE_PRIVATE_DRAFT_ID = /^dec_[0-9a-f]{8}$/u;
46
+ function isActionablePrivateDraft(row) {
47
+ if (typeof row !== "object" || row === null || Array.isArray(row)) return false;
48
+ const candidate = row;
49
+ return typeof candidate.id === "string" && SAFE_PRIVATE_DRAFT_ID.test(candidate.id) && typeof candidate.intent === "string" && candidate.authorIsSelf === true && candidate.stage === "draft" && (candidate.intentKind === void 0 || candidate.intentKind === "change");
50
+ }
51
+
52
+ // src/hooks/codex-context.ts
53
+ var CODEX_CONTEXT_TIMEOUT_MS = 250;
54
+ var CODEX_DIGEST_LIMIT = DECISION_DIGEST_CACHE_LIMIT;
55
+ var CODEX_DIGEST_VISIBLE_CAP = 3;
56
+ var CODEX_DIGEST_OVERLAP_MS = 6e4;
57
+ var CODEX_DIGEST_MAX_SEEN_IDS = 128;
58
+ var CODEX_DRAFT_DIGEST_MAX_SEEN_IDS = 4096;
59
+ var CODEX_DIGEST_STATE_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
60
+ var CODEX_DIGEST_STATE_MAX_FILES = 256;
61
+ var STATE_VERSION = 1;
62
+ var DRAFT_STATE_VERSION = 2;
63
+ var NO_CURSOR = -1;
64
+ function appendContext(existing, context) {
65
+ return existing ? `${existing}
66
+
67
+ ${context}` : context;
68
+ }
69
+ function appendCodexContext(output, context) {
70
+ if (!context) return output;
71
+ const candidate = output;
72
+ const next = { ...output };
73
+ if (candidate.systemMessage) {
74
+ next.systemMessage = appendContext(candidate.systemMessage, context);
75
+ } else if (candidate.hookSpecificOutput?.permissionDecisionReason) {
76
+ next.systemMessage = context;
77
+ } else if (candidate.hookSpecificOutput?.additionalContext) {
78
+ next.hookSpecificOutput = {
79
+ ...candidate.hookSpecificOutput,
80
+ additionalContext: appendContext(candidate.hookSpecificOutput.additionalContext, context)
81
+ };
82
+ } else {
83
+ next.systemMessage = context;
84
+ }
85
+ return next;
86
+ }
87
+ function stateRoot(namespace) {
88
+ return join(primConfigDirectory(), namespace, "decision-digests");
89
+ }
90
+ function draftStateRoot(namespace) {
91
+ return join(primConfigDirectory(), namespace, "decision-draft-deliveries");
92
+ }
93
+ function workspaceFor(cwd) {
94
+ try {
95
+ return gitToplevel(cwd) ?? cwd;
96
+ } catch {
97
+ return cwd;
98
+ }
99
+ }
100
+ function statePath(args) {
101
+ const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
102
+ const key = createHash("sha256").update(identity).digest("hex");
103
+ return join(stateRoot(args.namespace), `${key}.json`);
104
+ }
105
+ function draftStatePath(args) {
106
+ const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
107
+ const key = createHash("sha256").update(identity).digest("hex");
108
+ return join(draftStateRoot(args.namespace), `${key}.json`);
109
+ }
110
+ function parseState(value) {
111
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
112
+ const record = value;
113
+ if (record.version !== STATE_VERSION || typeof record.sessionId !== "string" || typeof record.siteUrl !== "string" || typeof record.workspace !== "string" || typeof record.startedAt !== "number" || typeof record.watermarkMs !== "number" || !Array.isArray(record.seenIds) || !record.seenIds.every((id) => typeof id === "string") || typeof record.updatedAt !== "number") {
114
+ return void 0;
115
+ }
116
+ return {
117
+ version: STATE_VERSION,
118
+ sessionId: record.sessionId,
119
+ siteUrl: record.siteUrl,
120
+ workspace: record.workspace,
121
+ startedAt: record.startedAt,
122
+ watermarkMs: record.watermarkMs,
123
+ seenIds: record.seenIds.slice(-CODEX_DIGEST_MAX_SEEN_IDS),
124
+ lastReport: typeof record.lastReport === "string" ? record.lastReport : void 0,
125
+ updatedAt: record.updatedAt
126
+ };
127
+ }
128
+ function parseDraftState(value) {
129
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
130
+ const record = value;
131
+ if (record.version !== DRAFT_STATE_VERSION || typeof record.sessionId !== "string" || typeof record.siteUrl !== "string" || typeof record.workspace !== "string" || typeof record.principalId !== "string" || typeof record.organizationId !== "string" || typeof record.credentialFingerprint !== "string" || !Array.isArray(record.seenDraftIds) || !record.seenDraftIds.every((id) => typeof id === "string") || typeof record.updatedAt !== "number") {
132
+ return void 0;
133
+ }
134
+ return {
135
+ version: DRAFT_STATE_VERSION,
136
+ sessionId: record.sessionId,
137
+ siteUrl: record.siteUrl,
138
+ workspace: record.workspace,
139
+ principalId: record.principalId,
140
+ organizationId: record.organizationId,
141
+ credentialFingerprint: record.credentialFingerprint,
142
+ seenDraftIds: record.seenDraftIds.slice(-CODEX_DRAFT_DIGEST_MAX_SEEN_IDS),
143
+ updatedAt: record.updatedAt
144
+ };
145
+ }
146
+ function readState(path) {
147
+ if (!existsSync(path)) return void 0;
148
+ try {
149
+ return parseState(JSON.parse(readFileSync(path, "utf8")));
150
+ } catch {
151
+ return void 0;
152
+ }
153
+ }
154
+ function readDraftState(path) {
155
+ if (!existsSync(path)) return void 0;
156
+ try {
157
+ return parseDraftState(JSON.parse(readFileSync(path, "utf8")));
158
+ } catch {
159
+ return void 0;
160
+ }
161
+ }
162
+ function writeStateFile(path, directory, state) {
163
+ mkdirSync(directory, { recursive: true, mode: 448 });
164
+ chmodSync(directory, 448);
165
+ const temporary = join(
166
+ directory,
167
+ `.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes2(8).toString("hex")}`
168
+ );
169
+ try {
170
+ writeFileSync(temporary, `${JSON.stringify(state)}
171
+ `, {
172
+ encoding: "utf8",
173
+ mode: 384,
174
+ flag: "wx"
175
+ });
176
+ chmodSync(temporary, 384);
177
+ renameSync(temporary, path);
178
+ } finally {
179
+ try {
180
+ unlinkSync(temporary);
181
+ } catch {
182
+ }
183
+ }
184
+ }
185
+ function cleanupStateFiles(directory, now) {
186
+ if (!existsSync(directory)) return;
187
+ let names;
188
+ try {
189
+ names = readdirSync(directory);
190
+ } catch {
191
+ return;
192
+ }
193
+ const files = [];
194
+ const residue = [];
195
+ for (const name of names) {
196
+ const path = join(directory, name);
197
+ try {
198
+ const mtimeMs = statSync(path).mtimeMs;
199
+ if (name.endsWith(".json")) {
200
+ files.push({ path, mtimeMs });
201
+ } else if ((name.includes(".json.tmp-") || name.endsWith(".json.lock")) && now - mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
202
+ residue.push(path);
203
+ }
204
+ } catch {
205
+ }
206
+ }
207
+ const stale = files.filter((file) => now - file.mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS);
208
+ const excess = files.filter((file) => !stale.some((candidate) => candidate.path === file.path)).sort((a, b) => a.mtimeMs - b.mtimeMs).slice(0, Math.max(0, files.length - CODEX_DIGEST_STATE_MAX_FILES));
209
+ for (const file of [...stale, ...excess]) {
210
+ try {
211
+ unlinkSync(file.path);
212
+ } catch {
213
+ }
214
+ }
215
+ for (const path of residue) {
216
+ try {
217
+ if (now - statSync(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
218
+ rmSync(path, { recursive: true, force: true });
219
+ }
220
+ } catch {
221
+ }
222
+ }
223
+ }
224
+ function isChangeDecision(row) {
225
+ return row.intentKind === void 0 || row.intentKind === "change";
226
+ }
227
+ function safeInline(value, fallback) {
228
+ const clean = terminalSafeText(value ?? "").replace(/\s+/gu, " ").trim();
229
+ if (!clean) return fallback;
230
+ return clean.length <= 240 ? clean : `${clean.slice(0, 239)}\u2026`;
231
+ }
232
+ function renderDecisionDigest(rows, options = {}) {
233
+ if (rows.length === 0) return void 0;
234
+ const visible = rows.slice(0, CODEX_DIGEST_VISIBLE_CAP).map((row) => {
235
+ const author = safeInline(row.authorName, "(unknown)").replace(/[;;;‒-―−]/gu, "-");
236
+ const intent = safeInline(row.intent, "(untitled Decision)").replace(/[`“-‟″‶〝〞]/gu, "'");
237
+ return `${author} \u2014 \u201C${intent}\u201D`;
238
+ });
239
+ const overflow = rows.length > CODEX_DIGEST_VISIBLE_CAP ? ` +${String(rows.length - CODEX_DIGEST_VISIBLE_CAP)}${options.pageTruncated === true ? "+" : ""}` : "";
240
+ return `[prim] Decisions captured since last message: ${visible.join("; ")}${overflow}`;
241
+ }
242
+ function actionablePrivateDrafts(rows) {
243
+ const seen = /* @__PURE__ */ new Set();
244
+ const actionable = [];
245
+ for (const row of rows) {
246
+ if (!isActionablePrivateDraft(row) || seen.has(row.id)) continue;
247
+ seen.add(row.id);
248
+ actionable.push(row);
249
+ }
250
+ return actionable;
251
+ }
252
+ function renderDecisionDraftDigest(rows, options = {}) {
253
+ const eligible = actionablePrivateDrafts(rows);
254
+ if (eligible.length === 0) return void 0;
255
+ const visible = eligible.slice(0, CODEX_DIGEST_VISIBLE_CAP);
256
+ const lines = visible.flatMap((row) => {
257
+ const intent = safeInline(row.intent, "(untitled Decision)").replace(/[“-‟″‶〝〞]/gu, "'");
258
+ return [
259
+ `[prim] private Decision ${row.id} \xB7 stage: draft \xB7 \u201C${intent}\u201D`,
260
+ `[prim] Run \`prim decisions publish ${row.id}\` to share it with your team.`
261
+ ];
262
+ });
263
+ if (eligible.length > visible.length) {
264
+ const suffix = options.pageTruncated === true ? "+" : "";
265
+ lines.push(
266
+ `[prim] +${String(eligible.length - visible.length)}${suffix} private Decision drafts remain for later messages.`
267
+ );
268
+ }
269
+ return { message: lines.join("\n"), deliveredIds: visible.map((row) => row.id) };
270
+ }
271
+ function reauthSnapshot(sessionId) {
272
+ return {
273
+ pid: 0,
274
+ uptimeMs: 0,
275
+ sessionId,
276
+ healthy: false,
277
+ needsReauth: true
278
+ };
279
+ }
280
+ function mergeState(latest, args) {
281
+ const seen = new Set(latest?.seenIds ?? []);
282
+ for (const id of args.seenIds) seen.add(id);
283
+ return {
284
+ version: STATE_VERSION,
285
+ sessionId: args.sessionId,
286
+ siteUrl: args.siteUrl,
287
+ workspace: args.workspace,
288
+ startedAt: latest?.startedAt ?? args.startedAt,
289
+ // Advance only on an observed page (server classifiedAt time), never the
290
+ // client clock; an unavailable feed keeps the previous cursor — or the
291
+ // NO_CURSOR sentinel, so the startup backlog survives until the first
292
+ // successful fetch.
293
+ watermarkMs: args.feedAvailable ? Math.max(latest?.watermarkMs ?? NO_CURSOR, args.watermarkMs) : latest?.watermarkMs ?? NO_CURSOR,
294
+ seenIds: [...seen].slice(-CODEX_DIGEST_MAX_SEEN_IDS),
295
+ lastReport: args.report,
296
+ updatedAt: args.now
297
+ };
298
+ }
299
+ async function commitState(path, args, namespace) {
300
+ try {
301
+ await withFileLock(
302
+ `${path}.lock`,
303
+ () => {
304
+ const latest = readState(path);
305
+ writeStateFile(path, stateRoot(namespace), mergeState(latest, args));
306
+ cleanupStateFiles(stateRoot(namespace), args.now);
307
+ },
308
+ { timeoutMs: 50, pollMs: 10 }
309
+ );
310
+ } catch {
311
+ }
312
+ }
313
+ function mergeDraftState(latest, args) {
314
+ const seen = new Set(latest?.seenDraftIds ?? []);
315
+ for (const id of args.deliveredIds) seen.add(id);
316
+ return {
317
+ version: DRAFT_STATE_VERSION,
318
+ sessionId: args.sessionId,
319
+ siteUrl: args.siteUrl,
320
+ workspace: args.workspace,
321
+ principalId: args.principalId,
322
+ organizationId: args.organizationId,
323
+ credentialFingerprint: args.credentialFingerprint,
324
+ seenDraftIds: [...seen].slice(-CODEX_DRAFT_DIGEST_MAX_SEEN_IDS),
325
+ updatedAt: args.now
326
+ };
327
+ }
328
+ async function commitDraftState(path, args, namespace) {
329
+ try {
330
+ let next;
331
+ await withFileLock(
332
+ `${path}.lock`,
333
+ () => {
334
+ const latest = readDraftState(path);
335
+ next = mergeDraftState(latest, args);
336
+ writeStateFile(path, draftStateRoot(namespace), next);
337
+ cleanupStateFiles(draftStateRoot(namespace), args.now);
338
+ },
339
+ { timeoutMs: 50, pollMs: 10 }
340
+ );
341
+ return next;
342
+ } catch {
343
+ return void 0;
344
+ }
345
+ }
346
+ async function prepareCodexContext(options) {
347
+ const namespace = options.namespace ?? "codex";
348
+ const siteUrl = getSiteUrl();
349
+ const workspace = workspaceFor(options.cwd);
350
+ const path = statePath({ cwd: options.cwd, sessionId: options.sessionId, siteUrl, namespace });
351
+ const previous = readState(path);
352
+ const principal = resolveDaemonPrincipal();
353
+ const privatePath = principal ? draftStatePath({
354
+ cwd: options.cwd,
355
+ sessionId: options.sessionId,
356
+ siteUrl,
357
+ principalId: principal.principalId,
358
+ organizationId: principal.organizationId,
359
+ credentialFingerprint: principal.credentialFingerprint,
360
+ namespace
361
+ }) : void 0;
362
+ const previousDraft = privatePath ? readDraftState(privatePath) : void 0;
363
+ const startup = options.startup === true;
364
+ const includeDigest = options.includeDigest !== false;
365
+ const startedAt = previous?.startedAt ?? Date.now();
366
+ const terminalAuth = isSessionEnded();
367
+ let snapshot = null;
368
+ let recent = null;
369
+ let recentDrafts = null;
370
+ if (terminalAuth) {
371
+ snapshot = reauthSnapshot(options.sessionId);
372
+ } else {
373
+ [snapshot, recent, recentDrafts] = await Promise.all([
374
+ daemonRequest(
375
+ "status_snapshot",
376
+ { callerEnv: siteUrl },
377
+ { timeoutMs: CODEX_CONTEXT_TIMEOUT_MS }
378
+ ),
379
+ includeDigest ? daemonRequest(
380
+ "decision_digest_snapshot",
381
+ { callerEnv: siteUrl },
382
+ { timeoutMs: CODEX_CONTEXT_TIMEOUT_MS }
383
+ ) : Promise.resolve(null),
384
+ includeDigest && principal !== void 0 ? daemonRequest(
385
+ "decision_draft_digest_snapshot",
386
+ { callerEnv: siteUrl },
387
+ { timeoutMs: CODEX_CONTEXT_TIMEOUT_MS }
388
+ ) : Promise.resolve(null)
389
+ ]);
390
+ if (principal !== void 0 && !daemonPrincipalsMatch(principal, resolveDaemonPrincipal())) {
391
+ snapshot = null;
392
+ recent = null;
393
+ recentDrafts = null;
394
+ }
395
+ }
396
+ let ingestionStatus;
397
+ const resolveIngestionStatus = () => {
398
+ ingestionStatus ??= decisionIngestionStatus(options.cwd);
399
+ return ingestionStatus;
400
+ };
401
+ const report = formatStatusline(packageVersion() ?? "0.0.0", snapshot, resolveIngestionStatus, {
402
+ includeIngestionWhenUnavailable: true,
403
+ plainLinks: true,
404
+ resolveRepositoryBindingState: () => resolveIngestionStatus() === "enabled" ? repositoryBindingState(options.cwd) : void 0
405
+ });
406
+ const reportChanged = startup || previous?.lastReport !== report;
407
+ let feedAvailable = false;
408
+ let freshRows = [];
409
+ let pageTruncated = false;
410
+ let pageWatermark = NO_CURSOR;
411
+ if (!terminalAuth && includeDigest && recent !== null) {
412
+ feedAvailable = recent.unavailable === void 0 && Array.isArray(recent.decisions);
413
+ if (feedAvailable) {
414
+ const seen = new Set(previous?.seenIds ?? []);
415
+ const lowerBound = previous !== void 0 && previous.watermarkMs >= 0 ? Math.max(0, previous.watermarkMs - CODEX_DIGEST_OVERLAP_MS) : 0;
416
+ freshRows = recent.decisions.filter(
417
+ (row) => isChangeDecision(row) && !seen.has(row.id) && typeof row.classifiedAt === "number" && row.classifiedAt >= lowerBound
418
+ );
419
+ pageTruncated = recent.decisions.length >= CODEX_DIGEST_LIMIT;
420
+ pageWatermark = recent.decisions.reduce(
421
+ (max, row) => typeof row.classifiedAt === "number" && row.classifiedAt > max ? row.classifiedAt : max,
422
+ NO_CURSOR
423
+ );
424
+ }
425
+ }
426
+ const digest = renderDecisionDigest(freshRows, { pageTruncated });
427
+ let draftDigest;
428
+ let draftPageToken;
429
+ let draftPageActionableIds = [];
430
+ if (!terminalAuth && includeDigest && privatePath !== void 0 && recentDrafts !== null && recentDrafts.unavailable === void 0 && Array.isArray(recentDrafts.decisions)) {
431
+ const allActionableDrafts = actionablePrivateDrafts(recentDrafts.decisions);
432
+ const seenDrafts = new Set(previousDraft?.seenDraftIds ?? []);
433
+ const freshDrafts = allActionableDrafts.filter((row) => !seenDrafts.has(row.id));
434
+ draftDigest = renderDecisionDraftDigest(freshDrafts, {
435
+ pageTruncated: recentDrafts.pageDone === false
436
+ });
437
+ draftPageToken = typeof recentDrafts.pageToken === "string" ? recentDrafts.pageToken : void 0;
438
+ draftPageActionableIds = allActionableDrafts.map((row) => row.id);
439
+ }
440
+ const combinedDigest = [digest, draftDigest?.message].filter((value) => value !== void 0).join("\n\n");
441
+ const context = [reportChanged ? report : void 0, combinedDigest || void 0].filter((value) => value !== void 0).join("\n\n") || void 0;
442
+ let acknowledged = false;
443
+ return {
444
+ context,
445
+ decisionDigest: combinedDigest || void 0,
446
+ feedAvailable,
447
+ acknowledge: async (handedOff) => {
448
+ if (!handedOff || acknowledged) return;
449
+ acknowledged = true;
450
+ await commitState(
451
+ path,
452
+ {
453
+ sessionId: options.sessionId,
454
+ siteUrl,
455
+ workspace,
456
+ startedAt,
457
+ watermarkMs: pageWatermark,
458
+ seenIds: freshRows.map((row) => row.id),
459
+ report,
460
+ feedAvailable,
461
+ now: Date.now()
462
+ },
463
+ namespace
464
+ );
465
+ if (privatePath === void 0 || principal === void 0 || draftPageToken === void 0) {
466
+ return;
467
+ }
468
+ let persistedDraft = previousDraft;
469
+ if (draftDigest?.deliveredIds.length) {
470
+ persistedDraft = await commitDraftState(
471
+ privatePath,
472
+ {
473
+ sessionId: options.sessionId,
474
+ siteUrl,
475
+ workspace,
476
+ principalId: principal.principalId,
477
+ organizationId: principal.organizationId,
478
+ credentialFingerprint: principal.credentialFingerprint,
479
+ deliveredIds: draftDigest.deliveredIds,
480
+ now: Date.now()
481
+ },
482
+ namespace
483
+ );
484
+ }
485
+ const seenDrafts = new Set(persistedDraft?.seenDraftIds ?? []);
486
+ const deliveredOnThisPage = draftPageActionableIds.filter((id) => seenDrafts.has(id));
487
+ await daemonRequest(
488
+ "decision_draft_digest_acknowledge",
489
+ {
490
+ callerEnv: siteUrl,
491
+ pageToken: draftPageToken,
492
+ deliveredIds: deliveredOnThisPage
493
+ },
494
+ { timeoutMs: CODEX_CONTEXT_TIMEOUT_MS }
495
+ );
496
+ }
497
+ };
498
+ }
499
+
500
+ export {
501
+ appendCodexContext,
502
+ prepareCodexContext
503
+ };