@raidiant/notifai 5.0.0 → 7.0.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 (126) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +2 -2
  3. package/dist/atomic-file.js +13 -0
  4. package/dist/atomic-file.js.map +1 -1
  5. package/dist/client.d.ts +8 -3
  6. package/dist/client.js +24 -3
  7. package/dist/client.js.map +1 -1
  8. package/dist/commands-auth.d.ts +14 -0
  9. package/dist/commands-auth.js +154 -0
  10. package/dist/commands-auth.js.map +1 -0
  11. package/dist/commands-config.d.ts +31 -0
  12. package/dist/commands-config.js +246 -0
  13. package/dist/commands-config.js.map +1 -0
  14. package/dist/commands-core.d.ts +102 -0
  15. package/dist/commands-core.js +135 -0
  16. package/dist/commands-core.js.map +1 -0
  17. package/dist/commands-devices.d.ts +31 -0
  18. package/dist/commands-devices.js +124 -0
  19. package/dist/commands-devices.js.map +1 -0
  20. package/dist/commands-doctor.d.ts +24 -0
  21. package/dist/commands-doctor.js +1011 -0
  22. package/dist/commands-doctor.js.map +1 -0
  23. package/dist/commands-harness-context.d.ts +65 -0
  24. package/dist/commands-harness-context.js +97 -0
  25. package/dist/commands-harness-context.js.map +1 -0
  26. package/dist/commands-hook-shape.d.ts +17 -0
  27. package/dist/commands-hook-shape.js +37 -0
  28. package/dist/commands-hook-shape.js.map +1 -0
  29. package/dist/commands-hooks.d.ts +115 -0
  30. package/dist/commands-hooks.js +1225 -0
  31. package/dist/commands-hooks.js.map +1 -0
  32. package/dist/commands-init.d.ts +35 -0
  33. package/dist/commands-init.js +580 -0
  34. package/dist/commands-init.js.map +1 -0
  35. package/dist/commands-io.d.ts +2 -0
  36. package/dist/commands-io.js +110 -0
  37. package/dist/commands-io.js.map +1 -0
  38. package/dist/commands-logs.d.ts +30 -0
  39. package/dist/commands-logs.js +201 -0
  40. package/dist/commands-logs.js.map +1 -0
  41. package/dist/commands-send-support.d.ts +44 -0
  42. package/dist/commands-send-support.js +183 -0
  43. package/dist/commands-send-support.js.map +1 -0
  44. package/dist/commands-send.d.ts +33 -0
  45. package/dist/commands-send.js +519 -0
  46. package/dist/commands-send.js.map +1 -0
  47. package/dist/commands-setup-proof.d.ts +15 -0
  48. package/dist/commands-setup-proof.js +53 -0
  49. package/dist/commands-setup-proof.js.map +1 -0
  50. package/dist/commands-skill.d.ts +10 -0
  51. package/dist/commands-skill.js +71 -0
  52. package/dist/commands-skill.js.map +1 -0
  53. package/dist/commands.d.ts +12 -387
  54. package/dist/commands.js +12 -4536
  55. package/dist/commands.js.map +1 -1
  56. package/dist/config-schema.js +1 -1
  57. package/dist/config-schema.js.map +1 -1
  58. package/dist/config.d.ts +4 -4
  59. package/dist/config.js +6 -4
  60. package/dist/config.js.map +1 -1
  61. package/dist/credentials.js +13 -3
  62. package/dist/credentials.js.map +1 -1
  63. package/dist/generated-session-label.d.ts +2 -0
  64. package/dist/generated-session-label.js +152 -0
  65. package/dist/generated-session-label.js.map +1 -0
  66. package/dist/hooks.d.ts +2 -2
  67. package/dist/hooks.js +127 -99
  68. package/dist/hooks.js.map +1 -1
  69. package/dist/interactive.js +4 -4
  70. package/dist/interactive.js.map +1 -1
  71. package/dist/invocation-context.d.ts +3 -0
  72. package/dist/invocation-context.js +23 -6
  73. package/dist/invocation-context.js.map +1 -1
  74. package/dist/logging.js +1 -0
  75. package/dist/logging.js.map +1 -1
  76. package/dist/main.js +3 -3
  77. package/dist/main.js.map +1 -1
  78. package/dist/opencode-plugin.js +18 -3
  79. package/dist/opencode-plugin.js.map +1 -1
  80. package/dist/readiness.d.ts +3 -1
  81. package/dist/readiness.js.map +1 -1
  82. package/dist/session-labels.d.ts +30 -0
  83. package/dist/session-labels.js +278 -0
  84. package/dist/session-labels.js.map +1 -0
  85. package/package.json +2 -2
  86. package/src/atomic-file.ts +12 -0
  87. package/src/client.test.ts +90 -1
  88. package/src/client.ts +35 -2
  89. package/src/commands-auth.ts +174 -0
  90. package/src/commands-config.ts +307 -0
  91. package/src/commands-core.ts +240 -0
  92. package/src/commands-devices.ts +150 -0
  93. package/src/commands-doctor.ts +1209 -0
  94. package/src/commands-harness-context.ts +134 -0
  95. package/src/commands-hook-shape.ts +53 -0
  96. package/src/commands-hooks.ts +1586 -0
  97. package/src/commands-init.ts +721 -0
  98. package/src/commands-io.ts +108 -0
  99. package/src/commands-logs.ts +243 -0
  100. package/src/commands-send-support.ts +227 -0
  101. package/src/commands-send.ts +623 -0
  102. package/src/commands-setup-proof.ts +71 -0
  103. package/src/commands-skill.ts +84 -0
  104. package/src/commands.test.ts +567 -42
  105. package/src/commands.ts +58 -5614
  106. package/src/config-schema.ts +1 -1
  107. package/src/config.test.ts +9 -0
  108. package/src/config.ts +10 -5
  109. package/src/credentials.test.ts +25 -1
  110. package/src/credentials.ts +13 -3
  111. package/src/generated-session-label.ts +155 -0
  112. package/src/hooks.test.ts +355 -16
  113. package/src/hooks.ts +145 -97
  114. package/src/install-hooks.test.ts +84 -1
  115. package/src/interactive.test.ts +19 -1
  116. package/src/interactive.ts +4 -4
  117. package/src/invocation-context.test.ts +115 -16
  118. package/src/invocation-context.ts +32 -11
  119. package/src/logging.test.ts +15 -2
  120. package/src/logging.ts +1 -0
  121. package/src/main.ts +9 -3
  122. package/src/opencode-plugin.ts +18 -3
  123. package/src/readiness.ts +3 -1
  124. package/src/session-labels.test.ts +303 -0
  125. package/src/session-labels.ts +360 -0
  126. package/src/skill.test.ts +13 -0
@@ -0,0 +1,1011 @@
1
+ import { PLATFORMS, SHIPPED_CLI_CAPABILITIES } from '@raidiant/notifai-protocol';
2
+ import { existsSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { inspectClaudeInbox, systemClaudeWakeAdapters } from './claude-wake.js';
5
+ import { ApiCallError } from './client.js';
6
+ import { inspectCodexResume } from './codex-wake.js';
7
+ import {} from './config.js';
8
+ import { HARNESS_CAPABILITIES, HARNESS_LABELS } from './harnesses.js';
9
+ import { inspectHookAdapter } from './hook-adapter.js';
10
+ import { readLiveProjectSessionPointers, readMatchingProjectSessionPointer, readProjectSessionPointer, readSessionState, } from './hooks.js';
11
+ import { BLOCKING_STOP_TIMEOUT_SECONDS, CLAUDE_ASYNC_STOP_TIMEOUT_SECONDS, codexCoexistenceNotes, codexHomeNote, codexLayerDir, codexLayerPaths, codexProjectRoot, codexRepresentationProblems, codexTrustProblems, detectedHarnesses, findInstallations, handlerEvent, inspectCodexLayer, } from './install-hooks.js';
12
+ import { inferInvocationContext } from './invocation-context.js';
13
+ import { firstBlocker, } from './readiness.js';
14
+ import { packageVersion } from './release.js';
15
+ import { EXIT, UPDATE_CLI_COMMAND, loadLoggedConfig, makeClient, resolvedBaseUrl, } from './commands-core.js';
16
+ import { deviceInstallRemedy, readyIosDevices, supportPageUrl } from './commands-devices.js';
17
+ import { activeHarnessSession, claudeSessionPid, resolveActiveHarness, } from './commands-harness-context.js';
18
+ import { stopShapeProblems } from './commands-hook-shape.js';
19
+ import { HOOK_EVENTS, activeQuestionRouteProblems, hookActivationAdvice } from './commands-hooks.js';
20
+ import { observedCompanionReceipt, readSetupProof } from './commands-setup-proof.js';
21
+ import { skillReadiness } from './commands-skill.js';
22
+ // ---------------------------------------------------------------------------
23
+ // doctor
24
+ // ---------------------------------------------------------------------------
25
+ /**
26
+ * Server-owned support policy plus every shipped platform document. Artifact
27
+ * versions and document integers are structured inventory, never routing or a
28
+ * definition of "up to date".
29
+ */
30
+ async function compatibilityCheck(client) {
31
+ try {
32
+ const [compatibility, documents] = await Promise.all([
33
+ client.compatibility(),
34
+ Promise.all(PLATFORMS.map((platform) => client.capabilities(platform))),
35
+ ]);
36
+ const serverCapabilities = new Set(compatibility.server_capabilities);
37
+ const cliCapabilityIntersection = {
38
+ available: SHIPPED_CLI_CAPABILITIES.filter((capability) => serverCapabilities.has(capability)),
39
+ missing_on_server: SHIPPED_CLI_CAPABILITIES.filter((capability) => !serverCapabilities.has(capability)),
40
+ };
41
+ const technical = {
42
+ local: {
43
+ cli_version: packageVersion(),
44
+ capabilities: [...SHIPPED_CLI_CAPABILITIES],
45
+ },
46
+ server: compatibility,
47
+ capability_documents: documents.map((document) => ({
48
+ platform: document.platform,
49
+ schema_version: document.schema_version,
50
+ })),
51
+ cli_capability_intersection: cliCapabilityIntersection,
52
+ };
53
+ if (compatibility.cli.state === 'must_update') {
54
+ return {
55
+ id: 'contract',
56
+ title: 'Notifai update',
57
+ status: 'gap',
58
+ detail: "Notifai can't send notifications until you update.",
59
+ technical,
60
+ remedy: {
61
+ by: 'user-here',
62
+ summary: 'update Notifai',
63
+ command: UPDATE_CLI_COMMAND,
64
+ },
65
+ };
66
+ }
67
+ if (compatibility.cli.state === 'update_available') {
68
+ const scheduled = compatibility.cli.reason === 'sunset_scheduled';
69
+ return {
70
+ id: 'contract',
71
+ title: 'Notifai update',
72
+ status: 'optional-gap',
73
+ detail: scheduled
74
+ ? 'Update Notifai soon to keep sending notifications.'
75
+ : 'A newer Notifai is available.',
76
+ technical,
77
+ remedy: {
78
+ by: 'user-here',
79
+ summary: 'update Notifai',
80
+ command: UPDATE_CLI_COMMAND,
81
+ },
82
+ };
83
+ }
84
+ if (cliCapabilityIntersection.missing_on_server.length > 0) {
85
+ // Named capabilities are feature-scoped. A service that has not learned
86
+ // this CLI's optional feature yet does not make baseline Notification
87
+ // Requests unavailable, even when every document carries the same schema
88
+ // integer. Structured output names the gap; the human path stays on the
89
+ // local service-update sentence and never invents a version diagnosis.
90
+ return {
91
+ id: 'contract',
92
+ title: 'Notifai update',
93
+ status: 'optional-gap',
94
+ detail: 'The service is being updated; try again later.',
95
+ technical,
96
+ remedy: {
97
+ by: 'user-here',
98
+ summary: 'try again after the service update',
99
+ command: 'notifai doctor',
100
+ },
101
+ };
102
+ }
103
+ return {
104
+ id: 'contract',
105
+ title: 'Notifai update',
106
+ status: 'ready',
107
+ detail: 'Notifai can send notifications.',
108
+ technical,
109
+ };
110
+ }
111
+ catch (err) {
112
+ return {
113
+ id: 'contract',
114
+ title: 'Notifai update',
115
+ status: 'optional-gap',
116
+ detail: 'The service is being updated; try again later.',
117
+ technical: {
118
+ error: err instanceof ApiCallError
119
+ ? { code: err.code, status: err.status }
120
+ : String(err),
121
+ },
122
+ remedy: {
123
+ by: 'user-here',
124
+ summary: 'try again after the service update',
125
+ command: 'notifai doctor',
126
+ },
127
+ };
128
+ }
129
+ }
130
+ function projectReadiness(deps, config) {
131
+ const configured = config.project.value;
132
+ if (configured !== null) {
133
+ return {
134
+ id: 'project',
135
+ title: 'Project identity',
136
+ status: 'ready',
137
+ detail: `"${configured}" (${config.project.source})`,
138
+ };
139
+ }
140
+ const inferred = inferInvocationContext(deps.cwd).project;
141
+ if (inferred !== null) {
142
+ return {
143
+ id: 'project',
144
+ title: 'Project identity',
145
+ status: 'optional-gap',
146
+ detail: `"${inferred}" is inferred for each send; init can stamp it into shared config`,
147
+ remedy: {
148
+ by: 'cli',
149
+ summary: 'make the inferred Project identity explicit for every checkout',
150
+ command: 'notifai init',
151
+ },
152
+ };
153
+ }
154
+ return {
155
+ id: 'project',
156
+ title: 'Project identity',
157
+ status: 'optional-gap',
158
+ detail: 'the directory name has no characters a Project identifier can use',
159
+ remedy: {
160
+ by: 'cli',
161
+ summary: 'choose an explicit Project identifier',
162
+ command: 'notifai init --project-id my-project',
163
+ },
164
+ };
165
+ }
166
+ function remoteStatesFrom(previous) {
167
+ const pick = (id) => previous.states.find((state) => state.id === id);
168
+ const credential = pick('credential');
169
+ const server = pick('server');
170
+ const contract = pick('contract');
171
+ const auth = pick('auth');
172
+ const devices = pick('devices');
173
+ const proof = pick('proof');
174
+ if (credential === undefined ||
175
+ server === undefined ||
176
+ contract === undefined ||
177
+ auth === undefined ||
178
+ devices === undefined ||
179
+ proof === undefined) {
180
+ return null;
181
+ }
182
+ return { credential, server, contract, auth, devices, proof };
183
+ }
184
+ function remoteInvalidatedByConfig(previous, config) {
185
+ if (config.base_url.source === 'default')
186
+ return false;
187
+ const server = previous.states.find((state) => state.id === 'server');
188
+ return server === undefined || !server.detail.includes(config.base_url.value);
189
+ }
190
+ /**
191
+ * Read the whole setup once, in dependency order.
192
+ *
193
+ * Descent stops where a prerequisite is missing: without a credential there is
194
+ * nothing to ask the server with, and without a reachable server a contract
195
+ * mismatch is unknowable rather than absent. Those downstream states report
196
+ * `unknown`, which is the honest answer and keeps a network outage from
197
+ * looking like a broken install.
198
+ */
199
+ export async function assessReadiness(deps, options = {}) {
200
+ const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env });
201
+ const previous = options.previous;
202
+ const refresh = options.refresh;
203
+ if (previous !== undefined && refresh !== undefined && refresh.length === 0)
204
+ return previous;
205
+ const reuseRemote = previous !== undefined &&
206
+ refresh !== undefined &&
207
+ !refresh.includes('remote') &&
208
+ !remoteInvalidatedByConfig(previous, config);
209
+ if (reuseRemote) {
210
+ const reused = remoteStatesFrom(previous);
211
+ if (reused !== null) {
212
+ return {
213
+ states: [
214
+ projectReadiness(deps, config),
215
+ reused.credential,
216
+ reused.server,
217
+ reused.contract,
218
+ reused.auth,
219
+ ...hookStates(deps),
220
+ await skillReadiness(deps, options.skillScope),
221
+ reused.devices,
222
+ reused.proof,
223
+ ],
224
+ };
225
+ }
226
+ }
227
+ const states = [];
228
+ let accountClient = null;
229
+ let accountDevices = null;
230
+ states.push(projectReadiness(deps, config));
231
+ const credential = deps.store.load();
232
+ states.push(credential
233
+ ? {
234
+ id: 'credential',
235
+ title: 'This machine',
236
+ status: 'ready',
237
+ detail: `paired as "${credential.machineName}" (${deps.store.describe()})`,
238
+ }
239
+ : {
240
+ id: 'credential',
241
+ title: 'This machine',
242
+ status: 'gap',
243
+ detail: 'not paired with your account',
244
+ remedy: {
245
+ by: 'user-here',
246
+ summary: 'sign in — this opens your browser to approve the machine',
247
+ command: 'notifai login',
248
+ interactive: true,
249
+ },
250
+ });
251
+ const baseUrl = resolvedBaseUrl(config, credential);
252
+ const anon = makeClient(deps, baseUrl, null);
253
+ // A probe that throws is unreachable, not a crash: this runs against a
254
+ // half-configured machine by definition, which is where a client that
255
+ // cannot even be constructed properly shows up.
256
+ let reachable = false;
257
+ try {
258
+ reachable = await anon.health();
259
+ }
260
+ catch {
261
+ reachable = false;
262
+ }
263
+ states.push(reachable
264
+ ? { id: 'server', title: 'Service', status: 'ready', detail: `${baseUrl} reachable` }
265
+ : {
266
+ id: 'server',
267
+ title: 'Service',
268
+ status: 'gap',
269
+ detail: `cannot reach ${baseUrl}`,
270
+ remedy: {
271
+ by: 'user-here',
272
+ summary: 'check your network',
273
+ command: 'notifai doctor',
274
+ },
275
+ });
276
+ if (!reachable || !credential) {
277
+ states.push({
278
+ id: 'contract',
279
+ title: 'Notifai update',
280
+ status: 'unknown',
281
+ detail: !reachable
282
+ ? 'Not checked because the service is unreachable.'
283
+ : 'Not checked because this machine is not paired.',
284
+ });
285
+ }
286
+ else {
287
+ const compatibilityClient = makeClient(deps, baseUrl, `Bearer nfm_${credential.machineId}.${credential.secret}`);
288
+ states.push(await compatibilityCheck(compatibilityClient));
289
+ }
290
+ let accountEmail = null;
291
+ let accountLookupFailed = false;
292
+ if (!credential || !reachable) {
293
+ const why = !credential ? 'this machine is not paired' : 'the server is unreachable';
294
+ states.push({ id: 'auth', title: 'Account', status: 'unknown', detail: `not checked — ${why}` });
295
+ }
296
+ else {
297
+ const client = makeClient(deps, baseUrl, `Bearer nfm_${credential.machineId}.${credential.secret}`);
298
+ accountClient = client;
299
+ try {
300
+ const [{ devices }, email] = await Promise.all([
301
+ client.listDevices(),
302
+ Promise.resolve()
303
+ .then(async () => (await client.accessStatus()).email)
304
+ .catch(() => null),
305
+ ]);
306
+ accountDevices = devices;
307
+ accountEmail = email;
308
+ states.push({
309
+ id: 'auth',
310
+ title: 'Account',
311
+ status: 'ready',
312
+ detail: accountEmail
313
+ ? `machine ${credential.machineId} accepted (${accountEmail})`
314
+ : `machine ${credential.machineId} accepted`,
315
+ });
316
+ }
317
+ catch (err) {
318
+ // A credential the server rejects is revocation, not absence, and the
319
+ // remedy is the same sign-in either way.
320
+ accountLookupFailed = true;
321
+ states.push({
322
+ id: 'auth',
323
+ title: 'Account',
324
+ status: 'gap',
325
+ detail: err instanceof ApiCallError ? `${err.code}: ${err.message}` : String(err),
326
+ remedy: {
327
+ by: 'user-here',
328
+ summary: 'this machine is no longer recognised; pair it again',
329
+ command: 'notifai login',
330
+ },
331
+ });
332
+ }
333
+ }
334
+ // Optional setup that works without a companion device must appear before the
335
+ // device gap: init stops at the first user-elsewhere blocker, and hooks/skill
336
+ // are reachable without a phone.
337
+ states.push(...hookStates(deps));
338
+ states.push(await skillReadiness(deps, options.skillScope));
339
+ if (!credential || !reachable) {
340
+ const why = !credential ? 'this machine is not paired' : 'the server is unreachable';
341
+ states.push({ id: 'devices', title: 'Your devices', status: 'unknown', detail: `not checked — ${why}` });
342
+ }
343
+ else if (accountLookupFailed || accountDevices === null) {
344
+ states.push({ id: 'devices', title: 'Your devices', status: 'unknown', detail: 'not checked — sign-in failed' });
345
+ }
346
+ else {
347
+ const devices = accountDevices;
348
+ const iphoneDevices = devices.filter((device) => device.platform === 'ios');
349
+ const ready = readyIosDevices(iphoneDevices);
350
+ states.push(ready.length > 0
351
+ ? {
352
+ id: 'devices',
353
+ title: 'Your devices',
354
+ status: 'ready',
355
+ detail: `${ready.map((d) => d.display_name).join(', ')} ready to receive`,
356
+ }
357
+ : {
358
+ id: 'devices',
359
+ title: 'Your devices',
360
+ status: 'gap',
361
+ // The one gap that cannot be closed from this terminal, and the
362
+ // likeliest place a first setup is abandoned. Naming which of
363
+ // the three sub-states it is matters: "install the app" is
364
+ // useless advice to someone who installed it and denied the
365
+ // permission prompt. The live bridge is /support on the
366
+ // dashboard origin — not a placeholder, and not typed by hand.
367
+ detail: iphoneDevices.length === 0
368
+ ? `no iPhone registered yet; install Notifai on iPhone via ${supportPageUrl(baseUrl)}`
369
+ : `${iphoneDevices.map((d) => `${d.display_name} (${d.permission_status})`).join(', ')} — registered but not able to receive`,
370
+ remedy: {
371
+ by: 'user-elsewhere',
372
+ summary: deviceInstallRemedy({
373
+ baseUrl,
374
+ email: accountEmail,
375
+ devices: iphoneDevices,
376
+ }),
377
+ },
378
+ });
379
+ }
380
+ states.push(await setupProofState(deps, config, accountClient, accountDevices));
381
+ return { states };
382
+ }
383
+ async function setupProofState(deps, config, client, devices) {
384
+ if (client === null || devices === null) {
385
+ return {
386
+ id: 'proof',
387
+ title: 'Delivery proof',
388
+ status: 'unknown',
389
+ detail: 'not checked — account and device readiness must be established first',
390
+ };
391
+ }
392
+ const ios = readyIosDevices(devices);
393
+ if (ios.length === 0) {
394
+ return {
395
+ id: 'proof',
396
+ title: 'Delivery proof',
397
+ status: 'unknown',
398
+ detail: 'not checked — no iPhone is ready',
399
+ };
400
+ }
401
+ const proof = readSetupProof(deps);
402
+ const target = proof === null ? null : ios.find((device) => device.device_id === proof.device_id);
403
+ if (proof === null || proof.project !== config.project.value || target === undefined) {
404
+ return {
405
+ id: 'proof',
406
+ title: 'Delivery proof',
407
+ status: 'gap',
408
+ detail: "no Companion Receipt (the app's delivery confirmation) has proven this project on this machine yet",
409
+ remedy: {
410
+ by: 'cli',
411
+ summary: "send one real verification notification and wait for its Companion Receipt (the app's delivery confirmation)",
412
+ command: 'notifai init',
413
+ },
414
+ };
415
+ }
416
+ try {
417
+ const snapshot = await client.evidence(proof.request_id);
418
+ const observed = observedCompanionReceipt(snapshot, proof.device_id);
419
+ if (observed) {
420
+ return {
421
+ id: 'proof',
422
+ title: 'Delivery proof',
423
+ status: 'ready',
424
+ detail: `Companion Receipt (the app's delivery confirmation) observed from ${observed.delivery.device_name} at ${observed.observedAt} (${proof.request_id})`,
425
+ };
426
+ }
427
+ return {
428
+ id: 'proof',
429
+ title: 'Delivery proof',
430
+ status: 'gap',
431
+ detail: `${proof.request_id} was sent, but its Companion Receipt (the app's delivery confirmation) is still unknown`,
432
+ remedy: {
433
+ by: 'cli',
434
+ summary: 'check the same verification notification again',
435
+ command: 'notifai init',
436
+ },
437
+ };
438
+ }
439
+ catch (err) {
440
+ return {
441
+ id: 'proof',
442
+ title: 'Delivery proof',
443
+ status: 'gap',
444
+ detail: `could not read ${proof.request_id} evidence (${err instanceof ApiCallError ? err.code : String(err)})`,
445
+ remedy: {
446
+ by: 'cli',
447
+ summary: 'retry the existing verification evidence check',
448
+ command: 'notifai init',
449
+ },
450
+ };
451
+ }
452
+ }
453
+ export async function doctorCommand(deps, flags, options = {}) {
454
+ const readiness = options.readiness ?? (await assessReadiness(deps));
455
+ const blocker = firstBlocker(readiness);
456
+ const ok = blocker === null;
457
+ // A human fallback exists only at a real terminal. Pipes, harnesses and
458
+ // non-TTY callers get the structured agent variant even without --json.
459
+ if (flags.json || deps.io.interactive !== true) {
460
+ deps.io.out(JSON.stringify({ ok, exit_code: ok ? EXIT.ok : EXIT.failed, states: readiness.states }, null, 2));
461
+ return ok ? EXIT.ok : EXIT.failed;
462
+ }
463
+ const line = (s) => `${s.title}: ${s.detail}`;
464
+ await deps.io.intro?.('Notifai doctor');
465
+ for (const s of readiness.states) {
466
+ // Working software says nothing about versions. Soft/hard update states use
467
+ // only the closed sentence and the exact command, never schema/capability
468
+ // vocabulary or a server-provided action.
469
+ if (s.id === 'contract') {
470
+ if (s.status === 'ready' || s.status === 'unknown')
471
+ continue;
472
+ deps.io.out(s.detail);
473
+ if (s.remedy?.by !== 'user-elsewhere' && s.remedy?.command === UPDATE_CLI_COMMAND) {
474
+ deps.io.out(UPDATE_CLI_COMMAND);
475
+ }
476
+ continue;
477
+ }
478
+ if (deps.io.check) {
479
+ await deps.io.check(s.status !== 'gap', line(s), doctorTone(s.status));
480
+ }
481
+ else {
482
+ const mark = s.status === 'gap'
483
+ ? 'FAIL'
484
+ : s.status === 'unknown'
485
+ ? ' ? '
486
+ : s.status === 'optional-gap'
487
+ ? ' --'
488
+ : 'ok ';
489
+ deps.io.out(`${mark} ${line(s)}`);
490
+ }
491
+ }
492
+ await deps.io.outro?.(ok
493
+ ? 'Everything looks good'
494
+ : blocker?.id === 'contract'
495
+ ? 'Update Notifai, then run doctor again'
496
+ : `Start with: ${remedyLine(blocker)}`);
497
+ return ok ? EXIT.ok : EXIT.failed;
498
+ }
499
+ /** Readiness status as a report tone. */
500
+ function doctorTone(status) {
501
+ switch (status) {
502
+ case 'ready':
503
+ return 'ok';
504
+ case 'gap':
505
+ return 'bad';
506
+ case 'optional-gap':
507
+ return 'warn';
508
+ case 'unknown':
509
+ return 'pending';
510
+ }
511
+ }
512
+ /** One line telling the reader what to actually do about a state. */
513
+ export function remedyLine(state) {
514
+ const remedy = state.remedy;
515
+ if (!remedy)
516
+ return state.detail;
517
+ if (remedy.by === 'user-elsewhere')
518
+ return remedy.summary;
519
+ return remedy.command === undefined
520
+ ? remedy.summary
521
+ : `${remedy.summary} — run \`${remedy.command}\``;
522
+ }
523
+ /**
524
+ * Whether the hook installation is internally ready, plus evidence that a
525
+ * project session has fired it before. This cannot prove future execution or
526
+ * end-to-end notification delivery without a live harness and device test.
527
+ *
528
+ * Every failure mode here was found the expensive way, by spawning a session
529
+ * and watching nothing happen: hooks not installed, installed but never fired,
530
+ * or left behind by an older build that named events this one does not serve.
531
+ */
532
+ /**
533
+ * Hook diagnostics as readiness states.
534
+ *
535
+ * A thin adapter over `hookChecks`, whose every branch was found the expensive
536
+ * way and is not worth re-deriving. The judgment added here is which failures
537
+ * actually stand in the way.
538
+ *
539
+ * Not everything failed is in the way. A pointer that has never been
540
+ * published is the normal condition of an install thirty seconds old — the
541
+ * next prompt fixes it and no command can. Treating that as blocking would
542
+ * mean `init` could only finish after a session had already run — so it
543
+ * reports as something worth knowing rather than something to
544
+ * fix, and `init` walks on to the states it can actually close, delivery
545
+ * proof included. Which failures are informational, and what the true remedy
546
+ * is, is each check's own call (`HookCheck`).
547
+ */
548
+ function hookStates(deps) {
549
+ const installations = findInstallations(deps.cwd, deps.env, deps.hookAdapterHome, deps.hookPlatform);
550
+ const active = activeHarnessSession(deps.env, deps.cwd, (deps.now ?? Date.now)());
551
+ const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env });
552
+ const settings = {
553
+ id: 'question-routing-settings',
554
+ title: 'Question routing settings',
555
+ status: config.ask_notifications.value ? 'ready' : 'gap',
556
+ detail: [
557
+ `ask_notifications=${config.ask_notifications.value} (${config.ask_notifications.source})`,
558
+ `ask_grace_seconds=${config.ask_grace_seconds.value} (${config.ask_grace_seconds.source})`,
559
+ ].join(', '),
560
+ ...(config.ask_notifications.value
561
+ ? {}
562
+ : {
563
+ remedy: {
564
+ by: 'cli',
565
+ summary: 'enable asynchronous question routing',
566
+ command: 'notifai config set ask_notifications true',
567
+ },
568
+ }),
569
+ };
570
+ if (installations.length === 0) {
571
+ return [
572
+ {
573
+ id: 'hooks',
574
+ title: 'Question routing',
575
+ status: active === null ? 'optional-gap' : 'gap',
576
+ detail: active === null
577
+ ? 'hooks not installed, so questions stay in the terminal'
578
+ : `active ${active.label} session detected, but ${active.label} hooks are not installed; \`notifai ask\` cannot route this session`,
579
+ remedy: {
580
+ by: 'cli',
581
+ summary: 'install harness hooks so questions reach your devices when you are away',
582
+ command: active === null
583
+ ? 'notifai hooks install'
584
+ : `notifai hooks install --harness ${active.harness}`,
585
+ },
586
+ },
587
+ settings,
588
+ ];
589
+ }
590
+ /**
591
+ * A human title per check.
592
+ *
593
+ * Three checks used to collapse onto "Question routing", so a reader could not
594
+ * tell which of them had failed, and the rest fell through to their internal
595
+ * name — `hooks (stale)` beside `Delivery proof`. The `id` stays the stable
596
+ * thing to branch on; this is only what a person reads.
597
+ */
598
+ const CHECK_TITLES = {
599
+ hooks: 'Question routing',
600
+ 'hooks (detected)': 'Harnesses detected',
601
+ 'hooks (active harness)': 'Routing for this harness',
602
+ 'hooks (active session)': 'Routing for this session',
603
+ 'hooks (stale)': 'Hook definitions current',
604
+ 'hooks (adapter)': 'Hook adapter',
605
+ 'hooks (trust)': 'Codex hook trust',
606
+ 'hooks (stop shape)': 'Turn-end hook shape',
607
+ 'hooks (duplicates)': 'Duplicate hook installs',
608
+ 'hooks (codex representation)': 'Codex hook representation',
609
+ 'hooks (question admission)': 'Question admission',
610
+ 'hooks (fired)': 'Hooks have run here',
611
+ 'hooks (answer continuation)': 'How an answer returns',
612
+ 'hooks (wake route)': 'Direct wake route',
613
+ };
614
+ function checkTitle(name) {
615
+ return CHECK_TITLES[name] ?? name;
616
+ }
617
+ /** Real but not in the way; see the note above. */
618
+ const informational = new Set();
619
+ return [
620
+ ...hookChecks(deps).map((check) => ({
621
+ id: check.name.replace(/[ ()]+/g, '-').replace(/-$/, ''),
622
+ title: checkTitle(check.name),
623
+ status: check.ok
624
+ ? 'ready'
625
+ : check.informational === true || informational.has(check.name)
626
+ ? 'optional-gap'
627
+ : 'gap',
628
+ detail: check.detail,
629
+ ...(check.ok
630
+ ? {}
631
+ : {
632
+ remedy: {
633
+ by: 'user-here',
634
+ // The check's own remedy when it has one; the generic reinstall
635
+ // line was wrong exactly where it mattered (an unfired pointer
636
+ // needs a prompt, not `hooks install`).
637
+ ...(check.remedy ?? {
638
+ summary: 'the detail above names what to change',
639
+ command: 'notifai hooks install',
640
+ }),
641
+ },
642
+ }),
643
+ })),
644
+ settings,
645
+ ];
646
+ }
647
+ function hookChecks(deps) {
648
+ const checks = [];
649
+ const installations = findInstallations(deps.cwd, deps.env, deps.hookAdapterHome, deps.hookPlatform);
650
+ // Not having hooks is a setup someone chose, not a fault: `send` works
651
+ // without them. A setup that cannot work is what deserves to go red.
652
+ if (installations.length === 0) {
653
+ checks.push({
654
+ name: 'hooks',
655
+ ok: true,
656
+ detail: 'not installed (optional) — `notifai hooks install` adds question routing',
657
+ });
658
+ return checks;
659
+ }
660
+ checks.push({
661
+ name: 'hooks',
662
+ ok: true,
663
+ detail: installations
664
+ .map((i) => `${i.harness} ${i.global ? 'global' : 'project'} (${i.file})`)
665
+ .join(', '),
666
+ });
667
+ const wired = new Set(installations.map((installation) => installation.harness));
668
+ const unwired = detectedHarnesses(deps.cwd, deps.env).filter((harness) => !wired.has(harness));
669
+ if (unwired.length > 0) {
670
+ checks.push({
671
+ name: 'hooks (detected)',
672
+ ok: false,
673
+ informational: true,
674
+ detail: `${unwired.map((harness) => HARNESS_LABELS[harness]).join(', ')} detected on this machine but not wired`,
675
+ remedy: {
676
+ summary: 'install hooks for every detected harness',
677
+ command: 'notifai hooks install',
678
+ },
679
+ });
680
+ }
681
+ const { active, contested } = resolveActiveHarness(deps.env, deps.cwd, (deps.now ?? Date.now)());
682
+ const activeInstallations = active === null
683
+ ? []
684
+ : installations.filter((installation) => installation.harness === active.harness);
685
+ if (active !== null) {
686
+ checks.push({
687
+ name: 'hooks (active harness)',
688
+ ok: activeInstallations.length > 0,
689
+ detail: activeInstallations.length > 0
690
+ ? `active ${active.label} session has a matching hook installation`
691
+ : `active ${active.label} session has no matching hook installation — run \`notifai hooks install --harness ${active.harness}\``,
692
+ ...(activeInstallations.length > 0
693
+ ? {}
694
+ : {
695
+ remedy: {
696
+ summary: `install hooks for the active ${active.label} session`,
697
+ command: `notifai hooks install --harness ${active.harness}`,
698
+ },
699
+ }),
700
+ });
701
+ if (activeInstallations.length > 0) {
702
+ const pointer = active.sessionId === undefined
703
+ ? null
704
+ : readMatchingProjectSessionPointer(deps.cwd, deps.env, (deps.now ?? Date.now)(), active.sessionId, active.harness);
705
+ if (pointer === null) {
706
+ // The normal condition of hooks installed moments ago: the pointer
707
+ // appears when the harness next fires a hook, and no command can
708
+ // force that. Informational, so `init` walks on to the states it can
709
+ // actually prove instead of exiting over evidence only time produces.
710
+ checks.push({
711
+ name: 'hooks (active session)',
712
+ ok: false,
713
+ informational: true,
714
+ detail: `active ${active.label} session has not published a live pointer — send one ${active.label} prompt, then check again`,
715
+ remedy: {
716
+ summary: `send one ${active.label} prompt — its hook publishes the routing pointer`,
717
+ command: 'notifai doctor',
718
+ },
719
+ });
720
+ }
721
+ else {
722
+ checks.push({
723
+ name: 'hooks (active session)',
724
+ ok: true,
725
+ detail: `the concurrent project index contains the active ${active.label} session`,
726
+ });
727
+ }
728
+ }
729
+ }
730
+ // A handler naming an event this build dropped exits 2 every time the harness
731
+ // fires it, which the harness reports as a hook failure.
732
+ const stale = installations.flatMap((i) => i.handlers
733
+ .filter((h) => {
734
+ const event = handlerEvent(h.command);
735
+ return event !== null && !HOOK_EVENTS.includes(event);
736
+ })
737
+ .map((h) => `${h.event} -> ${handlerEvent(h.command)} in ${i.file}`));
738
+ checks.push({
739
+ name: 'hooks (stale)',
740
+ ok: stale.length === 0,
741
+ detail: stale.length === 0
742
+ ? 'every installed handler names an event this build serves'
743
+ : `${stale.join('; ')} — rerun \`notifai hooks install\` to drop ${stale.length === 1 ? 'it' : 'them'}`,
744
+ });
745
+ const adapterProblems = installations.flatMap((installation) => (installation.problems ?? []).map((problem) => `${installation.file}: ${problem}`));
746
+ const sharedAdapter = inspectHookAdapter(deps.hookAdapterHome, deps.hookPlatform);
747
+ adapterProblems.push(...sharedAdapter.problems);
748
+ if (adapterProblems.length > 0) {
749
+ checks.push({
750
+ name: 'hooks (adapter)',
751
+ ok: false,
752
+ // A machine-global install for a harness that is not active in this
753
+ // project is useful diagnosis, but it must not block unrelated init.
754
+ informational: active === null && installations.every((installation) => installation.global),
755
+ detail: adapterProblems.join('; '),
756
+ });
757
+ }
758
+ const trustProblems = codexTrustProblems(installations, deps.env);
759
+ checks.push({
760
+ name: 'hooks (trust)',
761
+ ok: trustProblems.length === 0,
762
+ detail: trustProblems.length === 0
763
+ ? 'best-effort check matches current persisted Codex approvals; Notifai never writes the trust store, and `/hooks` is authoritative'
764
+ : `best-effort check only; Notifai never writes the trust store and \`/hooks\` is authoritative. ${trustProblems.join('; ')}`,
765
+ ...(trustProblems.length === 0
766
+ ? {}
767
+ : {
768
+ remedy: {
769
+ summary: 'open `/hooks` in Codex and approve the changed Notifai handlers',
770
+ command: '/hooks',
771
+ },
772
+ }),
773
+ });
774
+ const shapeProblems = installations.flatMap((installation) => stopShapeProblems(installation, deps.hookPlatform).map((problem) => `${problem} — run \`notifai hooks install --harness ${installation.harness}${installation.global ? ' --global' : ''}\``));
775
+ checks.push({
776
+ name: 'hooks (stop shape)',
777
+ ok: shapeProblems.length === 0,
778
+ detail: shapeProblems.length === 0
779
+ ? `every installed Stop handler declares the shape its harness needs: Claude Code async with an explicit ${CLAUDE_ASYNC_STOP_TIMEOUT_SECONDS}s waiter budget, blocking hosts ${BLOCKING_STOP_TIMEOUT_SECONDS}s, Codex host-owned`
780
+ : shapeProblems.join('; '),
781
+ });
782
+ // Project and global definitions for one harness both fire. Stable adapter
783
+ // identity deliberately makes their command bytes equal, so comparing
784
+ // command targets would now hide this duplicate rather than diagnose it.
785
+ // Different harnesses remain independent: only the active one runs.
786
+ const duplicated = [...new Set(installations.map((i) => i.harness))]
787
+ .map((harness) => ({
788
+ harness,
789
+ installations: installations.filter((i) => i.harness === harness),
790
+ }))
791
+ .filter((entry) => entry.installations.some((installation) => installation.global) &&
792
+ entry.installations.some((installation) => !installation.global));
793
+ if (duplicated.length > 0) {
794
+ checks.push({
795
+ name: 'hooks (duplicates)',
796
+ ok: false,
797
+ detail: duplicated
798
+ .map((entry) => `${entry.harness}: ${entry.installations.length} hook definitions are active, so each event will fire all of them. Keep either project or global routing and uninstall the other: ${entry.installations.map((installation) => installation.file).join(', ')}`)
799
+ .join('; '),
800
+ });
801
+ }
802
+ const representationProblems = codexRepresentationProblems(deps.cwd, deps.env, deps.hookPlatform);
803
+ if (representationProblems.length > 0) {
804
+ checks.push({
805
+ name: 'hooks (codex representation)',
806
+ ok: false,
807
+ detail: representationProblems.join('; '),
808
+ });
809
+ }
810
+ else {
811
+ const coexistence = codexCoexistenceNotes(deps.cwd, deps.env, deps.hookPlatform);
812
+ if (coexistence.length > 0) {
813
+ checks.push({
814
+ name: 'hooks (codex representation)',
815
+ ok: true,
816
+ detail: coexistence.join('; '),
817
+ });
818
+ }
819
+ }
820
+ const codexHome = codexHomeNote(deps.env, deps.hookPlatform);
821
+ if (codexHome !== null) {
822
+ checks.push({ name: 'hooks (codex home)', ok: true, detail: codexHome });
823
+ }
824
+ if (active !== null && activeInstallations.length > 0) {
825
+ const admissionProblems = activeQuestionRouteProblems(deps, active, installations);
826
+ checks.push({
827
+ name: 'hooks (question admission)',
828
+ ok: admissionProblems.length === 0,
829
+ detail: admissionProblems.length === 0
830
+ ? `the active ${active.label} route is exact, current, singular, trusted where applicable, and bounded by a live owner`
831
+ : admissionProblems.join('; '),
832
+ });
833
+ }
834
+ // Which route this judges, and which remedy it prints, must both belong to
835
+ // the harness that is actually running here. A machine-global installation
836
+ // matches every directory, so picking whichever installation matched — or
837
+ // whichever session last wrote a pointer — reports on a harness the agent
838
+ // cannot influence: it is told to send a prompt in a harness that is not
839
+ // running, follows the fail-closed rule, and can never clear the check.
840
+ const firedPointer = active === null
841
+ ? readProjectSessionPointer(deps.cwd, deps.env, (deps.now ?? Date.now)())
842
+ : active.sessionId === undefined
843
+ ? (readLiveProjectSessionPointers(deps.cwd, deps.env, (deps.now ?? Date.now)()).find((pointer) => pointer.harness === active.harness) ?? null)
844
+ : readMatchingProjectSessionPointer(deps.cwd, deps.env, (deps.now ?? Date.now)(), active.sessionId, active.harness);
845
+ const firedState = firedPointer === null ? null : readSessionState(firedPointer.sessionId, deps.env);
846
+ const promptFired = firedState?.last_prompt_at !== undefined;
847
+ const stopFired = firedState?.last_stop_at !== undefined;
848
+ const fired = firedPointer !== null && promptFired && stopFired;
849
+ // Installations for other harnesses are irrelevant to the active one, and an
850
+ // active harness with none of its own has nothing to activate: say that
851
+ // instead of advising a prompt in some other harness. When the environment
852
+ // is contested and nothing has fired, every candidate is still possible, so
853
+ // the advice covers all of them rather than betting on one.
854
+ const activationHarnesses = new Set(contested.length > 1
855
+ ? contested.map((candidate) => candidate.harness)
856
+ : active === null
857
+ ? installations.map((installation) => installation.harness)
858
+ : [active.harness]);
859
+ const activationInstallations = installations.filter((installation) => activationHarnesses.has(installation.harness));
860
+ const activationAdvice = activationInstallations.length > 0
861
+ ? hookActivationAdvice(activationInstallations)
862
+ : active === null
863
+ ? hookActivationAdvice(installations)
864
+ : `${active.label}: no ${active.label} hook installation matches this project — run \`notifai hooks install --harness ${active.harness}\`.`;
865
+ checks.push({
866
+ name: 'hooks (fired)',
867
+ ok: fired,
868
+ // A wholly fresh install is informational. Once UserPromptSubmit has fired,
869
+ // a missing Stop is a broken route, not missing historical evidence.
870
+ informational: firedPointer === null,
871
+ detail: fired
872
+ ? active === null
873
+ ? 'a session in this directory has run UserPromptSubmit and Stop'
874
+ : `the active ${active.label} session has run UserPromptSubmit and Stop`
875
+ : firedPointer === null
876
+ ? `no ${contested.length > 1
877
+ ? `session pointer for any harness whose markers are present here (${contested
878
+ .map((candidate) => candidate.label)
879
+ .join(', ')})`
880
+ : active === null
881
+ ? 'session pointer'
882
+ : `${active.label} session pointer`} from the last 24 hours — ${activationAdvice}`
883
+ : `the routed session has fired ${promptFired ? 'UserPromptSubmit' : 'neither required event'}, but Stop has not been observed — end one harmless turn, send a new prompt, then check again`,
884
+ ...(fired
885
+ ? {}
886
+ : {
887
+ remedy: {
888
+ summary: firedPointer === null
889
+ ? `send one ${active === null || contested.length > 1 ? '' : `${active.label} `}prompt in a session here, then re-check`
890
+ : 'end one harmless turn, send a new prompt, then re-check',
891
+ command: 'notifai doctor',
892
+ },
893
+ }),
894
+ });
895
+ const continuationInstallations = active !== null ? activeInstallations : installations;
896
+ const continuationHarnesses = [
897
+ ...new Set(continuationInstallations.map((installation) => installation.harness)),
898
+ ];
899
+ checks.push({
900
+ name: 'hooks (answer continuation)',
901
+ ok: continuationHarnesses.length > 0 &&
902
+ continuationHarnesses.every((harness) => HARNESS_CAPABILITIES[harness].stopContinuation !== 'unsupported'),
903
+ informational: active === null,
904
+ detail: continuationHarnesses.length === 0
905
+ ? active === null
906
+ ? 'no installed harness route to assess'
907
+ : `the active ${active.label} session has no matching continuation adapter`
908
+ : continuationHarnesses
909
+ .map((harness) => `${harness}: ${HARNESS_CAPABILITIES[harness].deliveryContract}`)
910
+ .join('; '),
911
+ });
912
+ const wakeRoute = wakeRouteCheck(deps, active, activeInstallations);
913
+ if (wakeRoute !== null)
914
+ checks.push(wakeRoute);
915
+ const stray = codexStrayWorktreeCheck(deps);
916
+ if (stray !== null)
917
+ checks.push(stray);
918
+ return checks;
919
+ }
920
+ /**
921
+ * Whether an answer arriving after this turn ends could actually reach this
922
+ * exact session — the question `notifai ask` really turns on, and the one no
923
+ * other check answers.
924
+ *
925
+ * Read-only, and deliberately so: nothing here connects to a socket, takes a
926
+ * lock, or sends a message. A diagnostic that wakes the agent it is diagnosing
927
+ * would be its own bug report.
928
+ *
929
+ * Everything it can report negatively is a degradation rather than a failure —
930
+ * the accepted journal still replays the answer at the session's next turn —
931
+ * so this is never a blocker. What it buys is that the reason has a name
932
+ * before the user notices the silence.
933
+ *
934
+ * It never asks for `crossSessionInbound`. The poster is the session's own
935
+ * hook child and takes the privileged own-child path, verified to be delivered
936
+ * even against a `bypassPermissions` receiver while an unrelated process was
937
+ * held. Widening a user's general inbound policy to suit Notifai would be a
938
+ * real change to their machine's posture in exchange for nothing.
939
+ */
940
+ function wakeRouteCheck(deps, active, activeInstallations) {
941
+ if (active === null || activeInstallations.length === 0)
942
+ return null;
943
+ if (active.harness === 'claude-code') {
944
+ const readiness = inspectClaudeInbox({
945
+ pid: deps.claudeSourcePid ?? claudeSessionPid(deps.env),
946
+ platform: deps.hookPlatform ?? process.platform,
947
+ readDescriptor: deps.claudeWake?.readDescriptor ?? systemClaudeWakeAdapters(deps.env).readDescriptor,
948
+ socketExists: (socketPath) => existsSync(socketPath),
949
+ });
950
+ return {
951
+ name: 'hooks (wake route)',
952
+ ok: readiness.state === 'ready',
953
+ informational: true,
954
+ detail: readiness.state === 'ready'
955
+ ? `this Claude Code ${readiness.version} session is listening on ${readiness.socketPath}, so an answer can start a turn here without you`
956
+ : `${readiness.reason}. Answers are still delivered, at this session's next turn rather than on their own`,
957
+ };
958
+ }
959
+ if (active.harness === 'codex') {
960
+ const readiness = inspectCodexResume(deps.env, {
961
+ platform: deps.hookPlatform ?? process.platform,
962
+ directoryExists: (directory) => existsSync(directory),
963
+ });
964
+ return {
965
+ name: 'hooks (wake route)',
966
+ ok: readiness.state === 'ready',
967
+ informational: true,
968
+ detail: readiness.state === 'ready'
969
+ ? `the held Codex turn continues from its own hook, and after it returns ${readiness.lockDirectory} can prove a stopped thread unowned before resuming it`
970
+ : `the held Codex turn still continues from its own hook, but after it returns nothing can be resumed: ${readiness.reason}. Answers wait for the next turn`,
971
+ };
972
+ }
973
+ return null;
974
+ }
975
+ /**
976
+ * A Codex hooks file sitting in a worktree, which Codex will never read.
977
+ *
978
+ * `settingsFile` now writes to the main repository, so this only fires for a
979
+ * file an older build left behind — but that file is indistinguishable from a
980
+ * working install if you go looking, and it is exactly what made this bug take
981
+ * a day to find. Omitted entirely when there is nothing to say.
982
+ */
983
+ function codexStrayWorktreeCheck(deps) {
984
+ const layer = codexLayerDir(deps.cwd);
985
+ if (layer === null)
986
+ return null;
987
+ const root = codexProjectRoot(deps.cwd);
988
+ const project = inspectCodexLayer(codexLayerPaths(false, deps.cwd, deps.env));
989
+ if (project.jsonEvents.length === 0 && project.tomlEvents.length === 0)
990
+ return null;
991
+ const strayJson = path.join(path.dirname(layer), '.codex', 'hooks.json');
992
+ const strayToml = path.join(path.dirname(layer), '.codex', 'config.toml');
993
+ const problems = [];
994
+ if (!existsSync(layer)) {
995
+ problems.push(`${layer} is missing, so Codex never looks for project hooks here`);
996
+ }
997
+ if (existsSync(strayJson) && path.resolve(strayJson) !== path.resolve(project.paths.hooksJson)) {
998
+ problems.push(`${strayJson} is never read — Codex reads ${project.writeTarget} instead`);
999
+ }
1000
+ if (existsSync(strayToml) && path.resolve(strayToml) !== path.resolve(project.paths.configToml)) {
1001
+ problems.push(`${strayToml} is never read — Codex reads ${project.writeTarget} instead`);
1002
+ }
1003
+ return {
1004
+ name: 'hooks (codex worktree)',
1005
+ ok: problems.length === 0,
1006
+ detail: problems.length === 0
1007
+ ? `worktree wired to the main repository at ${root}`
1008
+ : `${problems.join('; ')}. Re-run \`notifai hooks install\` to fix.`,
1009
+ };
1010
+ }
1011
+ //# sourceMappingURL=commands-doctor.js.map