@raidiant/notifai 10.1.0 → 10.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +3 -0
  3. package/dist/cli-bin.d.ts +21 -1
  4. package/dist/cli-bin.js +141 -10
  5. package/dist/cli-bin.js.map +1 -1
  6. package/dist/cli-update-contract.d.ts +7 -0
  7. package/dist/cli-update-contract.js +10 -0
  8. package/dist/cli-update-contract.js.map +1 -0
  9. package/dist/client.d.ts +6 -1
  10. package/dist/client.js +1 -0
  11. package/dist/client.js.map +1 -1
  12. package/dist/codex-wake.d.ts +2 -0
  13. package/dist/codex-wake.js +2 -1
  14. package/dist/codex-wake.js.map +1 -1
  15. package/dist/commands-auth.d.ts +15 -1
  16. package/dist/commands-auth.js +29 -11
  17. package/dist/commands-auth.js.map +1 -1
  18. package/dist/commands-core.d.ts +9 -2
  19. package/dist/commands-core.js +11 -4
  20. package/dist/commands-core.js.map +1 -1
  21. package/dist/commands-devices.d.ts +10 -1
  22. package/dist/commands-devices.js +17 -13
  23. package/dist/commands-devices.js.map +1 -1
  24. package/dist/commands-doctor.js +93 -49
  25. package/dist/commands-doctor.js.map +1 -1
  26. package/dist/commands-hooks.js +47 -10
  27. package/dist/commands-hooks.js.map +1 -1
  28. package/dist/commands-init.d.ts +16 -0
  29. package/dist/commands-init.js +254 -93
  30. package/dist/commands-init.js.map +1 -1
  31. package/dist/commands-send-support.js +3 -0
  32. package/dist/commands-send-support.js.map +1 -1
  33. package/dist/commands-send.d.ts +1 -1
  34. package/dist/commands-send.js +121 -35
  35. package/dist/commands-send.js.map +1 -1
  36. package/dist/commands-skill.js +72 -54
  37. package/dist/commands-skill.js.map +1 -1
  38. package/dist/commands-update.d.ts +10 -0
  39. package/dist/commands-update.js +141 -0
  40. package/dist/commands-update.js.map +1 -0
  41. package/dist/commands.d.ts +2 -1
  42. package/dist/commands.js +2 -1
  43. package/dist/commands.js.map +1 -1
  44. package/dist/hook-adapter.d.ts +2 -0
  45. package/dist/hook-adapter.js +12 -1
  46. package/dist/hook-adapter.js.map +1 -1
  47. package/dist/hooks.d.ts +43 -2
  48. package/dist/hooks.js +163 -21
  49. package/dist/hooks.js.map +1 -1
  50. package/dist/invocation-context.d.ts +1 -0
  51. package/dist/invocation-context.js +9 -1
  52. package/dist/invocation-context.js.map +1 -1
  53. package/dist/main-run.d.ts +1 -0
  54. package/dist/main-run.js +42 -0
  55. package/dist/main-run.js.map +1 -0
  56. package/dist/main.js +10 -31
  57. package/dist/main.js.map +1 -1
  58. package/dist/native-skills.d.ts +13 -3
  59. package/dist/native-skills.js +51 -12
  60. package/dist/native-skills.js.map +1 -1
  61. package/dist/node-floor.d.ts +19 -0
  62. package/dist/node-floor.js +39 -0
  63. package/dist/node-floor.js.map +1 -0
  64. package/dist/orca-session-title.d.ts +5 -4
  65. package/dist/orca-session-title.js +32 -19
  66. package/dist/orca-session-title.js.map +1 -1
  67. package/dist/platform.d.ts +11 -17
  68. package/dist/platform.js +20 -23
  69. package/dist/platform.js.map +1 -1
  70. package/dist/program.d.ts +2 -1
  71. package/dist/program.js +22 -5
  72. package/dist/program.js.map +1 -1
  73. package/dist/question-settlement-process.d.ts +15 -0
  74. package/dist/question-settlement-process.js +35 -0
  75. package/dist/question-settlement-process.js.map +1 -0
  76. package/dist/readiness.d.ts +25 -1
  77. package/dist/readiness.js +32 -2
  78. package/dist/readiness.js.map +1 -1
  79. package/dist/release.d.ts +5 -5
  80. package/dist/release.js +5 -5
  81. package/dist/setup-destinations.d.ts +23 -0
  82. package/dist/setup-destinations.js +44 -0
  83. package/dist/setup-destinations.js.map +1 -0
  84. package/dist/skill-integrity.d.ts +49 -0
  85. package/dist/skill-integrity.js +154 -0
  86. package/dist/skill-integrity.js.map +1 -0
  87. package/dist/skill-source/manifest.json +16 -0
  88. package/dist/skill-source/notifai/SKILL.md +390 -0
  89. package/dist/skill-source/notifai/references/harness-setup.md +220 -0
  90. package/package.json +11 -14
  91. package/src/atomic-file.ts +0 -198
  92. package/src/claude-wake.test.ts +0 -321
  93. package/src/claude-wake.ts +0 -499
  94. package/src/cli-bin.test.ts +0 -38
  95. package/src/cli-bin.ts +0 -67
  96. package/src/cli-release.test.ts +0 -46
  97. package/src/cli-release.ts +0 -78
  98. package/src/client.test.ts +0 -390
  99. package/src/client.ts +0 -345
  100. package/src/codex-wake.test.ts +0 -254
  101. package/src/codex-wake.ts +0 -297
  102. package/src/command-session.ts +0 -38
  103. package/src/commands-agent-sessions.ts +0 -72
  104. package/src/commands-auth.ts +0 -205
  105. package/src/commands-config.ts +0 -336
  106. package/src/commands-core.ts +0 -298
  107. package/src/commands-devices.test.ts +0 -15
  108. package/src/commands-devices.ts +0 -173
  109. package/src/commands-doctor.ts +0 -1440
  110. package/src/commands-guidance.ts +0 -181
  111. package/src/commands-harness-context.ts +0 -207
  112. package/src/commands-hook-shape.ts +0 -69
  113. package/src/commands-hooks.ts +0 -2268
  114. package/src/commands-init.ts +0 -878
  115. package/src/commands-io.ts +0 -108
  116. package/src/commands-logs.ts +0 -243
  117. package/src/commands-project.ts +0 -47
  118. package/src/commands-send-support.test.ts +0 -156
  119. package/src/commands-send-support.ts +0 -311
  120. package/src/commands-send.ts +0 -769
  121. package/src/commands-setup-proof.test.ts +0 -72
  122. package/src/commands-setup-proof.ts +0 -124
  123. package/src/commands-skill.test.ts +0 -44
  124. package/src/commands-skill.ts +0 -204
  125. package/src/commands-sounds.test.ts +0 -106
  126. package/src/commands-sounds.ts +0 -49
  127. package/src/commands.test.ts +0 -7828
  128. package/src/commands.ts +0 -75
  129. package/src/config-schema.test.ts +0 -153
  130. package/src/config-schema.ts +0 -349
  131. package/src/config.test.ts +0 -581
  132. package/src/config.ts +0 -475
  133. package/src/credentials.test.ts +0 -403
  134. package/src/credentials.ts +0 -403
  135. package/src/file-lock-process-worker.test.ts +0 -64
  136. package/src/file-lock.test.ts +0 -320
  137. package/src/file-lock.ts +0 -393
  138. package/src/fixtures/hermes-0.20.6-classic-cli-local.json +0 -50
  139. package/src/fixtures/openclaw-2026.7.1-2-agent-local.json +0 -57
  140. package/src/generated-session-label.ts +0 -155
  141. package/src/guidance-content.ts +0 -278
  142. package/src/guidance-render.ts +0 -56
  143. package/src/guidance.test.ts +0 -327
  144. package/src/guidance.ts +0 -233
  145. package/src/harness-integration.test.ts +0 -294
  146. package/src/harnesses.test.ts +0 -149
  147. package/src/harnesses.ts +0 -164
  148. package/src/hook-adapter.test.ts +0 -496
  149. package/src/hook-adapter.ts +0 -410
  150. package/src/hook-input.test.ts +0 -39
  151. package/src/hook-input.ts +0 -72
  152. package/src/hooks.test.ts +0 -5549
  153. package/src/hooks.ts +0 -3759
  154. package/src/install-hooks.test.ts +0 -1614
  155. package/src/install-hooks.ts +0 -1501
  156. package/src/interactive.test.ts +0 -387
  157. package/src/interactive.ts +0 -858
  158. package/src/invocation-context.test.ts +0 -352
  159. package/src/invocation-context.ts +0 -197
  160. package/src/logging-process-worker.test.ts +0 -45
  161. package/src/logging.test.ts +0 -544
  162. package/src/logging.ts +0 -698
  163. package/src/main.ts +0 -36
  164. package/src/native-skills.test.ts +0 -115
  165. package/src/native-skills.ts +0 -162
  166. package/src/onboarding-docs.test.ts +0 -25
  167. package/src/openclaw-plugin.ts +0 -409
  168. package/src/opencode-plugin.ts +0 -298
  169. package/src/orca-session-title.test.ts +0 -54
  170. package/src/orca-session-title.ts +0 -103
  171. package/src/pack-feedback-slice.test.ts +0 -212
  172. package/src/pack-feedback-slice.ts +0 -187
  173. package/src/platform.test.ts +0 -152
  174. package/src/platform.ts +0 -173
  175. package/src/program.test.ts +0 -282
  176. package/src/program.ts +0 -818
  177. package/src/project-enablement.test.ts +0 -55
  178. package/src/project-enablement.ts +0 -99
  179. package/src/question-caps.test.ts +0 -49
  180. package/src/question-timing.ts +0 -56
  181. package/src/readiness.test.ts +0 -25
  182. package/src/readiness.ts +0 -179
  183. package/src/release.ts +0 -51
  184. package/src/send-attempts.test.ts +0 -143
  185. package/src/send-attempts.ts +0 -188
  186. package/src/send.test.ts +0 -28
  187. package/src/send.ts +0 -436
  188. package/src/session-activation.ts +0 -61
  189. package/src/session-end-log-lock-worker.test.ts +0 -35
  190. package/src/session-labels.test.ts +0 -490
  191. package/src/session-labels.ts +0 -474
  192. package/src/skill.test.ts +0 -415
  193. package/src/sound-ref.test.ts +0 -31
  194. package/src/sound-ref.ts +0 -34
  195. package/src/trust-policy.test.ts +0 -701
  196. package/src/ui/banner.ts +0 -95
  197. package/src/ui/config-view.test.ts +0 -90
  198. package/src/ui/config-view.ts +0 -138
  199. package/src/ui/help.test.ts +0 -16
  200. package/src/ui/help.ts +0 -128
  201. package/src/ui/theme.test.ts +0 -92
  202. package/src/ui/theme.ts +0 -265
  203. package/src/url-policy.ts +0 -399
  204. package/tsconfig.json +0 -10
@@ -1,1440 +0,0 @@
1
- import { PLATFORMS, SHIPPED_CLI_CAPABILITIES, type RoutableDevice } 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, type ApiClient } from './client.js'
6
- import { inspectCodexResume } from './codex-wake.js'
7
- import { type CliConfig } from './config.js'
8
- import {
9
- HARNESS_CAPABILITIES,
10
- HARNESS_LABELS,
11
- HERMES_QUESTION_ROUTING_UNAVAILABLE,
12
- isHookInstallableHarness,
13
- } from './harnesses.js'
14
- import { inspectHookAdapter } from './hook-adapter.js'
15
- import {
16
- readLiveProjectSessionPointers,
17
- readProjectSessionPointer,
18
- readSessionState,
19
- } from './hooks.js'
20
- import {
21
- NON_ROUTING_BLOCKING_STOP_TIMEOUT_SECONDS,
22
- QUESTION_STOP_TIMEOUT_SECONDS,
23
- codexCoexistenceNotes,
24
- codexHomeNote,
25
- codexLayerDir,
26
- codexLayerPaths,
27
- codexProjectRoot,
28
- codexRepresentationProblems,
29
- codexTrustProblems,
30
- detectedHarnesses,
31
- findInstallations,
32
- handlerEvent,
33
- inspectCodexLayer,
34
- type Installation,
35
- } from './install-hooks.js'
36
- import { inferInvocationContext } from './invocation-context.js'
37
- import type { SkillScope } from './native-skills.js'
38
- import {
39
- firstBlocker,
40
- readinessJson,
41
- type Readiness,
42
- type ReadinessRefresh,
43
- type ReadinessState,
44
- type StateStatus,
45
- } from './readiness.js'
46
- import { packageVersion } from './release.js'
47
- import type { Tone } from './ui/theme.js'
48
- import type { MachineCredential } from './credentials.js'
49
- import {
50
- EXIT,
51
- SETUP_COMMAND,
52
- UPDATE_CLI_COMMAND,
53
- diagnoseIgnoredOriginOverride,
54
- loadLoggedConfig,
55
- makeClient,
56
- resolvedBaseUrl,
57
- type CommandDeps,
58
- } from './commands-core.js'
59
- import { deviceInstallRemedy, readyCompanionDevices, supportPageUrl } from './commands-devices.js'
60
- import {
61
- claudeSessionPid,
62
- resolveActiveHarness,
63
- type ActiveHarnessSession,
64
- } from './commands-harness-context.js'
65
- import { stopShapeProblems } from './commands-hook-shape.js'
66
- import {
67
- HOOK_EVENTS,
68
- activeQuestionRouteProblems,
69
- hookActivationAdvice,
70
- requiredHookEvents,
71
- } from './commands-hooks.js'
72
- import { cliBinReadiness } from './cli-bin.js'
73
- import {
74
- latestPublishedCliVersion,
75
- newerPublishedCli,
76
- shouldConsultCliRegistry,
77
- thisCliVersion,
78
- } from './cli-release.js'
79
- import {
80
- SETUP_PROOF_STALE_MS,
81
- observedCompanionReceipt,
82
- readSetupProof,
83
- setupProofProject,
84
- setupProofIsStale,
85
- setupProofApplies,
86
- } from './commands-setup-proof.js'
87
- import { skillReadiness } from './commands-skill.js'
88
- import { projectBinding, projectEnabled } from './project-enablement.js'
89
-
90
- // ---------------------------------------------------------------------------
91
- // doctor
92
- // ---------------------------------------------------------------------------
93
-
94
- /**
95
- * Server-owned support policy plus every shipped platform document. Artifact
96
- * versions and document integers are structured inventory, never routing or a
97
- * definition of "up to date".
98
- */
99
- async function compatibilityCheck(client: ApiClient): Promise<ReadinessState> {
100
- try {
101
- const [compatibility, documents] = await Promise.all([
102
- client.compatibility(),
103
- Promise.all(PLATFORMS.map((platform) => client.capabilities(platform))),
104
- ])
105
- const serverCapabilities = new Set(compatibility.server_capabilities)
106
- const cliCapabilityIntersection = {
107
- available: SHIPPED_CLI_CAPABILITIES.filter((capability) => serverCapabilities.has(capability)),
108
- missing_on_server: SHIPPED_CLI_CAPABILITIES.filter(
109
- (capability) => !serverCapabilities.has(capability),
110
- ),
111
- }
112
- const technical = {
113
- local: {
114
- cli_version: packageVersion(),
115
- capabilities: [...SHIPPED_CLI_CAPABILITIES],
116
- },
117
- server: compatibility,
118
- capability_documents: documents.map((document) => ({
119
- platform: document.platform,
120
- schema_version: document.schema_version,
121
- })),
122
- cli_capability_intersection: cliCapabilityIntersection,
123
- }
124
- if (compatibility.cli.state === 'must_update') {
125
- return {
126
- id: 'contract',
127
- title: 'Notifai update',
128
- status: 'gap',
129
- detail: "Notifai can't send notifications until you update.",
130
- technical,
131
- remedy: {
132
- by: 'user-here',
133
- summary: 'update Notifai',
134
- command: UPDATE_CLI_COMMAND,
135
- },
136
- }
137
- }
138
- if (compatibility.cli.state === 'update_available') {
139
- const scheduled = compatibility.cli.reason === 'sunset_scheduled'
140
- return {
141
- id: 'contract',
142
- title: 'Notifai update',
143
- status: 'optional-gap',
144
- detail: scheduled
145
- ? 'Update Notifai soon to keep sending notifications.'
146
- : 'A newer Notifai is available.',
147
- technical,
148
- remedy: {
149
- by: 'user-here',
150
- summary: 'update Notifai',
151
- command: UPDATE_CLI_COMMAND,
152
- },
153
- }
154
- }
155
- if (cliCapabilityIntersection.missing_on_server.length > 0) {
156
- // Named capabilities are feature-scoped. A service that has not learned
157
- // this CLI's optional feature yet does not make baseline Notification
158
- // Requests unavailable, even when every document carries the same schema
159
- // integer. Structured output names the gap; the human path stays on the
160
- // local service-update sentence and never invents a version diagnosis.
161
- return {
162
- id: 'contract',
163
- title: 'Notifai update',
164
- status: 'optional-gap',
165
- detail: 'The service is being updated; try again later.',
166
- technical,
167
- remedy: {
168
- by: 'user-here',
169
- summary: 'try again after the service update',
170
- command: 'notifai doctor',
171
- },
172
- }
173
- }
174
- return {
175
- id: 'contract',
176
- title: 'Notifai update',
177
- status: 'ready',
178
- detail: 'Notifai can send notifications.',
179
- technical,
180
- }
181
- } catch (err) {
182
- return {
183
- id: 'contract',
184
- title: 'Notifai update',
185
- status: 'optional-gap',
186
- detail: 'The service is being updated; try again later.',
187
- technical: {
188
- error: err instanceof ApiCallError
189
- ? { code: err.code, status: err.status }
190
- : String(err),
191
- },
192
- remedy: {
193
- by: 'user-here',
194
- summary: 'try again after the service update',
195
- command: 'notifai doctor',
196
- },
197
- }
198
- }
199
- }
200
-
201
- function projectReadiness(deps: CommandDeps, config: CliConfig): ReadinessState {
202
- const configured = config.project.value
203
- if (configured !== null) {
204
- return {
205
- id: 'project',
206
- title: 'Project identity',
207
- status: 'ready',
208
- detail: `"${configured}" (${config.project.source})`,
209
- }
210
- }
211
- const inferred = inferInvocationContext(deps.cwd).project
212
- if (inferred !== null) {
213
- return {
214
- id: 'project',
215
- title: 'Project identity',
216
- status: 'optional-gap',
217
- detail: `"${inferred}" is inferred for each send; init can stamp it into shared config`,
218
- remedy: {
219
- by: 'cli',
220
- summary: 'make the inferred Project identity explicit for every checkout',
221
- command: 'notifai init',
222
- },
223
- }
224
- }
225
- return {
226
- id: 'project',
227
- title: 'Project identity',
228
- status: 'optional-gap',
229
- detail: 'the directory name has no characters a Project identifier can use',
230
- remedy: {
231
- by: 'cli',
232
- summary: 'choose an explicit Project identifier',
233
- command: 'notifai init --project-id my-project',
234
- },
235
- }
236
- }
237
-
238
- function projectEnablementReadiness(deps: CommandDeps, config: CliConfig): ReadinessState {
239
- const binding = projectBinding(deps.cwd, deps.env, config.project.value)
240
- if (binding === null) {
241
- return {
242
- id: 'project-enablement',
243
- title: 'Project enablement',
244
- status: 'optional-gap',
245
- detail: 'no Project is available here; lifecycle hooks stay silent',
246
- }
247
- }
248
- if (projectEnabled(binding)) {
249
- return {
250
- id: 'project-enablement',
251
- title: 'Project enablement',
252
- status: 'ready',
253
- detail: `enabled by the User for Project "${binding.project}"`,
254
- }
255
- }
256
- return {
257
- id: 'project-enablement',
258
- title: 'Project enablement',
259
- status: 'optional-gap',
260
- detail: `disabled for Project "${binding.project}"; installed lifecycle hooks will emit no model guidance`,
261
- remedy: {
262
- by: 'cli',
263
- summary: 'enable Notifai lifecycle behavior for this Project',
264
- command: 'notifai project enable',
265
- },
266
- }
267
- }
268
-
269
- function remoteStatesFrom(previous: Readiness): {
270
- credential: ReadinessState
271
- server: ReadinessState
272
- contract: ReadinessState
273
- auth: ReadinessState
274
- devices: ReadinessState
275
- proof: ReadinessState
276
- } | null {
277
- const pick = (id: string): ReadinessState | undefined => previous.states.find((state) => state.id === id)
278
- const credential = pick('credential')
279
- const server = pick('server')
280
- const contract = pick('contract')
281
- const auth = pick('auth')
282
- const devices = pick('devices')
283
- const proof = pick('proof')
284
- if (
285
- credential === undefined ||
286
- server === undefined ||
287
- contract === undefined ||
288
- auth === undefined ||
289
- devices === undefined ||
290
- proof === undefined
291
- ) {
292
- return null
293
- }
294
- return { credential, server, contract, auth, devices, proof }
295
- }
296
-
297
- function remoteInvalidatedByConfig(
298
- previous: Readiness,
299
- config: CliConfig,
300
- credential: MachineCredential | null,
301
- ): boolean {
302
- const origin = resolvedBaseUrl(config, credential)
303
- const server = previous.states.find((state) => state.id === 'server')
304
- return server === undefined || !server.detail.includes(origin)
305
- }
306
-
307
- function isNoActivePlanError(err: unknown): err is ApiCallError {
308
- return err instanceof ApiCallError && err.code === 'no_active_plan'
309
- }
310
-
311
- /**
312
- * Device listing is grant-gated; access status is not. A paired Account whose
313
- * plan lapsed must not be diagnosed as a revoked machine.
314
- */
315
- async function probeAccount(
316
- client: ApiClient,
317
- credential: MachineCredential,
318
- baseUrl: string,
319
- ): Promise<{
320
- email: string | null
321
- devices: RoutableDevice[] | null
322
- lookupFailed: boolean
323
- auth: ReadinessState
324
- }> {
325
- const [devicesOutcome, accessOutcome] = await Promise.allSettled([
326
- Promise.resolve().then(() => client.listDevices()),
327
- Promise.resolve().then(() => client.accessStatus()),
328
- ])
329
- const access = accessOutcome.status === 'fulfilled' ? accessOutcome.value : null
330
- const devices = devicesOutcome.status === 'fulfilled' ? devicesOutcome.value.devices : null
331
- const email = access?.email ?? null
332
- const devicesErr = devicesOutcome.status === 'rejected' ? devicesOutcome.reason : null
333
- const noActivePlan =
334
- access?.status === 'no_active_plan' || isNoActivePlanError(devicesErr)
335
-
336
- if (noActivePlan) {
337
- const next =
338
- (isNoActivePlanError(devicesErr) ? devicesErr.nextAction : null) ??
339
- `Open ${supportPageUrl(baseUrl)} to request Alpha access, then retry.`
340
- return {
341
- email,
342
- devices: null,
343
- lookupFailed: true,
344
- auth: {
345
- id: 'auth',
346
- title: 'Account',
347
- status: 'gap',
348
- detail: email
349
- ? `no active plan or temporary Alpha access (${email})`
350
- : 'no active plan or temporary Alpha access',
351
- remedy: {
352
- by: 'user-elsewhere',
353
- summary: next,
354
- },
355
- },
356
- }
357
- }
358
-
359
- if (devices !== null) {
360
- return {
361
- email,
362
- devices,
363
- lookupFailed: false,
364
- auth: {
365
- id: 'auth',
366
- title: 'Account',
367
- status: 'ready',
368
- detail: email
369
- ? `machine ${credential.machineId} accepted (${email})`
370
- : `machine ${credential.machineId} accepted`,
371
- },
372
- }
373
- }
374
-
375
- const err = devicesErr ?? (accessOutcome.status === 'rejected' ? accessOutcome.reason : null)
376
- return {
377
- email: null,
378
- devices: null,
379
- lookupFailed: true,
380
- auth: {
381
- id: 'auth',
382
- title: 'Account',
383
- status: 'gap',
384
- detail: err instanceof ApiCallError ? `${err.code}: ${err.message}` : String(err),
385
- remedy: {
386
- by: 'user-here',
387
- summary: 'this machine is no longer recognised; pair it again',
388
- command: SETUP_COMMAND,
389
- interactive: true,
390
- },
391
- },
392
- }
393
- }
394
-
395
- /**
396
- * Read the whole setup once, in dependency order.
397
- *
398
- * Descent stops where a prerequisite is missing: without a credential there is
399
- * nothing to ask the server with, and without a reachable server a contract
400
- * mismatch is unknowable rather than absent. Those downstream states report
401
- * `unknown`, which is the honest answer and keeps a network outage from
402
- * looking like a broken install.
403
- */
404
- export async function assessReadiness(
405
- deps: CommandDeps,
406
- options: {
407
- skillScope?: SkillScope
408
- previous?: Readiness
409
- refresh?: readonly ReadinessRefresh[]
410
- json?: boolean
411
- } = {},
412
- ): Promise<Readiness> {
413
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env })
414
- const credential = deps.store.load()
415
- if (credential) diagnoseIgnoredOriginOverride(deps.io, config, credential)
416
- const previous = options.previous
417
- const refresh = options.refresh
418
- if (previous !== undefined && refresh !== undefined && refresh.length === 0) return previous
419
-
420
- const reuseRemote =
421
- previous !== undefined &&
422
- refresh !== undefined &&
423
- !refresh.includes('remote') &&
424
- !remoteInvalidatedByConfig(previous, config, credential)
425
- if (reuseRemote) {
426
- const reused = remoteStatesFrom(previous)
427
- if (reused !== null) {
428
- return {
429
- states: [
430
- cliBinReadiness(deps.env, deps.hookPlatform ?? process.platform),
431
- projectEnablementReadiness(deps, config),
432
- projectReadiness(deps, config),
433
- reused.credential,
434
- reused.server,
435
- reused.contract,
436
- reused.auth,
437
- ...hookStates(deps),
438
- await skillReadiness(deps, options.skillScope),
439
- reused.devices,
440
- reused.proof,
441
- ],
442
- }
443
- }
444
- }
445
-
446
- const states: ReadinessState[] = []
447
- let accountClient: ApiClient | null = null
448
- let accountDevices: RoutableDevice[] | null = null
449
-
450
- states.push(cliBinReadiness(deps.env, deps.hookPlatform ?? process.platform))
451
- states.push(projectEnablementReadiness(deps, config))
452
- states.push(projectReadiness(deps, config))
453
-
454
- states.push(
455
- credential
456
- ? {
457
- id: 'credential',
458
- title: 'This machine',
459
- status: 'ready',
460
- detail: `paired as "${credential.machineName}" (${deps.store.describe()})`,
461
- }
462
- : {
463
- id: 'credential',
464
- title: 'This machine',
465
- status: 'gap',
466
- detail: 'not paired with your account',
467
- remedy: {
468
- by: 'user-here',
469
- summary: 'sign in — this opens your browser to approve the machine',
470
- command: SETUP_COMMAND,
471
- interactive: true,
472
- },
473
- },
474
- )
475
-
476
- const baseUrl = resolvedBaseUrl(config, credential)
477
- const anon = makeClient(deps, baseUrl, null)
478
- // A probe that throws is unreachable, not a crash: this runs against a
479
- // half-configured machine by definition, which is where a client that
480
- // cannot even be constructed properly shows up.
481
- let reachable = false
482
- try {
483
- reachable = await anon.health()
484
- } catch {
485
- reachable = false
486
- }
487
- states.push(
488
- reachable
489
- ? { id: 'server', title: 'Service', status: 'ready', detail: `${baseUrl} reachable` }
490
- : {
491
- id: 'server',
492
- title: 'Service',
493
- status: 'gap',
494
- detail: `cannot reach ${baseUrl}`,
495
- remedy: {
496
- by: 'user-here',
497
- summary: 'check your network',
498
- command: 'notifai doctor',
499
- },
500
- },
501
- )
502
-
503
- if (!reachable || !credential) {
504
- states.push({
505
- id: 'contract',
506
- title: 'Notifai update',
507
- status: 'unknown',
508
- detail: !reachable
509
- ? 'Not checked because the service is unreachable.'
510
- : 'Not checked because this machine is not paired.',
511
- })
512
- } else {
513
- const compatibilityClient = makeClient(
514
- deps,
515
- baseUrl,
516
- `Bearer nfm_${credential.machineId}.${credential.secret}`,
517
- )
518
- states.push(await compatibilityCheck(compatibilityClient))
519
- }
520
-
521
- let accountEmail: string | null = null
522
- let accountLookupFailed = false
523
- if (!credential || !reachable) {
524
- const why = !credential ? 'this machine is not paired' : 'the server is unreachable'
525
- states.push({ id: 'auth', title: 'Account', status: 'unknown', detail: `not checked — ${why}` })
526
- } else {
527
- const client = makeClient(deps, baseUrl, `Bearer nfm_${credential.machineId}.${credential.secret}`)
528
- accountClient = client
529
- const probed = await probeAccount(client, credential, baseUrl)
530
- accountDevices = probed.devices
531
- accountEmail = probed.email
532
- accountLookupFailed = probed.lookupFailed
533
- states.push(probed.auth)
534
- }
535
-
536
- // Optional setup that works without a companion device must appear before the
537
- // device gap: init stops at the first user-elsewhere blocker, and hooks/skill
538
- // are reachable without a phone.
539
- states.push(...hookStates(deps))
540
- states.push(await skillReadiness(deps, options.skillScope))
541
-
542
- if (!credential || !reachable) {
543
- const why = !credential ? 'this machine is not paired' : 'the server is unreachable'
544
- states.push({ id: 'devices', title: 'Your devices', status: 'unknown', detail: `not checked — ${why}` })
545
- } else if (accountLookupFailed || accountDevices === null) {
546
- states.push({ id: 'devices', title: 'Your devices', status: 'unknown', detail: 'not checked — sign-in failed' })
547
- } else {
548
- const devices = accountDevices
549
- const companionDevices = devices.filter(
550
- (device) => device.platform === 'ios' || device.platform === 'android',
551
- )
552
- const ready = readyCompanionDevices(companionDevices)
553
- states.push(
554
- ready.length > 0
555
- ? {
556
- id: 'devices',
557
- title: 'Your devices',
558
- status: 'ready',
559
- detail: `${ready.map((d) => `${d.display_name} (${d.platform})`).join(', ')} ready to receive`,
560
- }
561
- : {
562
- id: 'devices',
563
- title: 'Your devices',
564
- status: 'gap',
565
- // The one gap that cannot be closed from this terminal, and the
566
- // likeliest place a first setup is abandoned. Naming which of
567
- // the three sub-states it is matters: "install the app" is
568
- // useless advice to someone who installed it and denied the
569
- // permission prompt. The live bridge is /support on the
570
- // dashboard origin — not a placeholder, and not typed by hand.
571
- detail:
572
- companionDevices.length === 0
573
- ? `no active Companion device registered yet; install Notifai via ${supportPageUrl(baseUrl)}`
574
- : `${companionDevices.map((d) => `${d.display_name} (${d.platform}, ${d.permission_status})`).join(', ')} — registered but not able to receive`,
575
- remedy: {
576
- by: 'user-elsewhere',
577
- summary: deviceInstallRemedy({
578
- baseUrl,
579
- email: accountEmail,
580
- devices: companionDevices,
581
- }),
582
- },
583
- },
584
- )
585
- }
586
-
587
- states.push(await setupProofState(deps, config, accountClient, accountDevices))
588
- await applyRegistryRecommendation(deps, options.json === true, states)
589
-
590
- return { states }
591
- }
592
-
593
- async function applyRegistryRecommendation(
594
- deps: CommandDeps,
595
- json: boolean,
596
- states: ReadinessState[],
597
- ): Promise<void> {
598
- if (
599
- !shouldConsultCliRegistry({
600
- ...(deps.io.interactive === undefined ? {} : { interactive: deps.io.interactive }),
601
- json,
602
- env: deps.env,
603
- })
604
- ) {
605
- return
606
- }
607
- const latest = await latestPublishedCliVersion(deps.fetchImpl)
608
- const newer = newerPublishedCli(thisCliVersion(), latest)
609
- if (newer === null) return
610
- const contract = states.find((state) => state.id === 'contract')
611
- if (contract === undefined || contract.status === 'gap') return
612
- contract.status = 'optional-gap'
613
- contract.detail = 'A newer Notifai is available.'
614
- contract.remedy = {
615
- by: 'user-here',
616
- summary: 'update Notifai',
617
- command: UPDATE_CLI_COMMAND,
618
- }
619
- }
620
-
621
- async function setupProofState(
622
- deps: CommandDeps,
623
- config: CliConfig,
624
- client: ApiClient | null,
625
- devices: RoutableDevice[] | null,
626
- ): Promise<ReadinessState> {
627
- if (client === null || devices === null) {
628
- return {
629
- id: 'proof',
630
- title: 'Delivery proof',
631
- status: 'unknown',
632
- detail: 'not checked — account and device readiness must be established first',
633
- }
634
- }
635
-
636
- const companions = readyCompanionDevices(devices)
637
- if (companions.length === 0) {
638
- return {
639
- id: 'proof',
640
- title: 'Delivery proof',
641
- status: 'unknown',
642
- detail: 'not checked — no iPhone or Android Companion App is ready',
643
- }
644
- }
645
-
646
- const project = setupProofProject(deps, config.project.value)
647
- const proof = readSetupProof(deps, project)
648
- const applies = setupProofApplies(proof, project, companions.map((device) => device.device_id))
649
- if (!applies) {
650
- return {
651
- id: 'proof',
652
- title: 'Delivery proof',
653
- status: 'gap',
654
- detail:
655
- "no Companion Receipt (the app's delivery confirmation) has proven this project on this machine yet",
656
- remedy: {
657
- by: 'cli',
658
- summary:
659
- "send one real verification notification and wait for its Companion Receipt (the app's delivery confirmation)",
660
- command: 'notifai init',
661
- },
662
- }
663
- }
664
-
665
- try {
666
- const snapshot = await client.evidence(proof.request_id)
667
- const observed = observedCompanionReceipt(snapshot, proof.device_id)
668
- if (observed) {
669
- return {
670
- id: 'proof',
671
- title: 'Delivery proof',
672
- status: 'ready',
673
- detail: `Companion Receipt (the app's delivery confirmation) observed from ${observed.delivery.device_name} at ${observed.observedAt} (${proof.request_id})`,
674
- }
675
- }
676
- const now = (deps.now ?? Date.now)()
677
- if (setupProofIsStale(proof, now)) {
678
- return {
679
- id: 'proof',
680
- title: 'Delivery proof',
681
- status: 'gap',
682
- detail: `${proof.request_id} is older than ${SETUP_PROOF_STALE_MS / 36e5}h with no Companion Receipt; init will send a replacement`,
683
- remedy: {
684
- by: 'cli',
685
- summary: 'replace the stale verification notification',
686
- command: 'notifai init',
687
- },
688
- }
689
- }
690
- return {
691
- id: 'proof',
692
- title: 'Delivery proof',
693
- status: 'gap',
694
- detail: `${proof.request_id} was sent, but its Companion Receipt (the app's delivery confirmation) is still unknown`,
695
- remedy: {
696
- by: 'cli',
697
- summary: 'check the same verification notification again',
698
- command: 'notifai init',
699
- },
700
- }
701
- } catch (err) {
702
- return {
703
- id: 'proof',
704
- title: 'Delivery proof',
705
- status: 'gap',
706
- detail: `could not read ${proof.request_id} evidence (${err instanceof ApiCallError ? err.code : String(err)})`,
707
- remedy: {
708
- by: 'cli',
709
- summary: 'retry the existing verification evidence check',
710
- command: 'notifai init',
711
- },
712
- }
713
- }
714
- }
715
-
716
- export async function doctorCommand(
717
- deps: CommandDeps,
718
- flags: { json?: boolean },
719
- options: { readiness?: Readiness } = {},
720
- ): Promise<number> {
721
- const readiness =
722
- options.readiness ?? (await assessReadiness(deps, flags.json === true ? { json: true } : {}))
723
- const blocker = firstBlocker(readiness)
724
- const ok = blocker === null
725
-
726
- // A human fallback exists only at a real terminal. Pipes, harnesses and
727
- // non-TTY callers get the structured agent variant even without --json.
728
- if (flags.json || deps.io.interactive !== true) {
729
- deps.io.out(
730
- JSON.stringify(
731
- { ...readinessJson(readiness), ok, exit_code: ok ? EXIT.ok : EXIT.failed },
732
- null,
733
- 2,
734
- ),
735
- )
736
- return ok ? EXIT.ok : EXIT.failed
737
- }
738
-
739
- const line = (s: ReadinessState) => `${s.title}: ${s.detail}`
740
- await deps.io.intro?.('Notifai doctor')
741
- for (const s of readiness.states) {
742
- // Working software says nothing about versions. Soft/hard update states use
743
- // only the closed sentence and the exact command, never schema/capability
744
- // vocabulary or a server-provided action.
745
- if (s.id === 'contract') {
746
- if (s.status === 'ready' || s.status === 'unknown') continue
747
- deps.io.out(s.detail)
748
- if (s.remedy?.by !== 'user-elsewhere' && s.remedy?.command === UPDATE_CLI_COMMAND) {
749
- deps.io.out(UPDATE_CLI_COMMAND)
750
- }
751
- continue
752
- }
753
- if (deps.io.check) {
754
- await deps.io.check(s.status !== 'gap', line(s), doctorTone(s.status))
755
- } else {
756
- const mark =
757
- s.status === 'gap'
758
- ? 'FAIL'
759
- : s.status === 'unknown'
760
- ? ' ? '
761
- : s.status === 'optional-gap'
762
- ? ' --'
763
- : 'ok '
764
- deps.io.out(`${mark} ${line(s)}`)
765
- }
766
- }
767
- const surfacedUpdate = readiness.states.some(
768
- (state) => state.id === 'contract' && (state.status === 'gap' || state.status === 'optional-gap'),
769
- )
770
- if (blocker !== null && blocker.id !== 'contract') {
771
- await deps.io.outro?.(`Start with: ${remedyLine(blocker)}`)
772
- } else if (!surfacedUpdate) {
773
- await deps.io.outro?.('Everything looks good')
774
- }
775
- return ok ? EXIT.ok : EXIT.failed
776
- }
777
-
778
- /** Readiness status as a report tone. */
779
- function doctorTone(status: StateStatus): Tone {
780
- switch (status) {
781
- case 'ready':
782
- return 'ok'
783
- case 'gap':
784
- return 'bad'
785
- case 'optional-gap':
786
- return 'warn'
787
- case 'unknown':
788
- return 'pending'
789
- }
790
- }
791
-
792
- /** One line telling the reader what to actually do about a state. */
793
- export function remedyLine(state: ReadinessState): string {
794
- const remedy = state.remedy
795
- if (!remedy) return state.detail
796
- if (remedy.by === 'user-elsewhere') return remedy.summary
797
- return remedy.command === undefined
798
- ? remedy.summary
799
- : `${remedy.summary} — run \`${remedy.command}\``
800
- }
801
-
802
- /**
803
- * Whether the hook installation is internally ready, plus evidence that a
804
- * project session has fired it before. This cannot prove future execution or
805
- * end-to-end notification delivery without a live harness and device test.
806
- *
807
- * Every failure mode here was found the expensive way, by spawning a session
808
- * and watching nothing happen: hooks not installed, installed but never fired,
809
- * or left behind by an older build that named events this one does not serve.
810
- */
811
- /**
812
- * Hook diagnostics as readiness states.
813
- *
814
- * A thin adapter over `hookChecks`, whose every branch was found the expensive
815
- * way and is not worth re-deriving. The judgment added here is which failures
816
- * actually stand in the way.
817
- *
818
- * Not everything failed is in the way. A pointer that has never been
819
- * published is the normal condition of an install thirty seconds old — the
820
- * next prompt fixes it and no command can. Treating that as blocking would
821
- * mean `init` could only finish after a session had already run — so it
822
- * reports as something worth knowing rather than something to
823
- * fix, and `init` walks on to the states it can actually close, delivery
824
- * proof included. Which failures are informational, and what the true remedy
825
- * is, is each check's own call (`HookCheck`).
826
- */
827
- function hookStates(deps: CommandDeps): ReadinessState[] {
828
- const installations = findInstallations(deps.cwd, deps.env, deps.hookAdapterHome, deps.hookPlatform)
829
- const { active, contested } = resolveActiveHarness(
830
- deps.env,
831
- deps.cwd,
832
- (deps.now ?? Date.now)(),
833
- )
834
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env })
835
- const settings: ReadinessState = {
836
- id: 'question-routing-settings',
837
- title: 'Question routing settings',
838
- status: config.ask_notifications.value ? 'ready' : 'gap',
839
- detail: [
840
- `ask_notifications=${config.ask_notifications.value} (${config.ask_notifications.source})`,
841
- `ask_grace_seconds=${config.ask_grace_seconds.value} (${config.ask_grace_seconds.source})`,
842
- ].join(', '),
843
- ...(config.ask_notifications.value
844
- ? {}
845
- : {
846
- remedy: {
847
- by: 'cli' as const,
848
- summary: 'enable asynchronous question routing',
849
- command: 'notifai config set ask_notifications true',
850
- },
851
- }),
852
- }
853
- if (installations.length === 0) {
854
- if (contested.length > 1) {
855
- return [
856
- {
857
- id: 'hooks',
858
- title: 'Question routing',
859
- status: 'optional-gap',
860
- detail: `Several harness sessions could own this shell (${contested.map((candidate) => candidate.label).join(', ')}); routing readiness is intentionally not attributed to either one`,
861
- },
862
- settings,
863
- ]
864
- }
865
- if (active !== null && !isHookInstallableHarness(active.harness)) {
866
- return [
867
- {
868
- id: 'hooks',
869
- title: 'Question routing',
870
- status: 'optional-gap',
871
- detail: `${active.label}: ${HERMES_QUESTION_ROUTING_UNAVAILABLE.deliveryContract}`,
872
- },
873
- settings,
874
- ]
875
- }
876
- return [
877
- {
878
- id: 'hooks',
879
- title: 'Question routing',
880
- status: active === null ? 'optional-gap' : 'gap',
881
- detail:
882
- active === null
883
- ? 'hooks not installed, so questions stay in the terminal'
884
- : `active ${active.label} session detected, but ${active.label} hooks are not installed; \`notifai ask\` cannot route this session`,
885
- remedy: {
886
- by: 'cli',
887
- summary: 'install harness hooks so questions reach your devices when you are away',
888
- command:
889
- active === null
890
- ? 'notifai hooks install'
891
- : `notifai hooks install --harness ${active.harness}`,
892
- },
893
- },
894
- settings,
895
- ]
896
- }
897
-
898
- /**
899
- * A human title per check.
900
- *
901
- * Three checks used to collapse onto "Question routing", so a reader could not
902
- * tell which of them had failed, and the rest fell through to their internal
903
- * name — `hooks (stale)` beside `Delivery proof`. The `id` stays the stable
904
- * thing to branch on; this is only what a person reads.
905
- */
906
- const CHECK_TITLES: Readonly<Record<string, string>> = {
907
- hooks: 'Question routing',
908
- 'hooks (detected)': 'Harnesses detected',
909
- 'hooks (active harness)': 'Routing for this harness',
910
- 'hooks (active session)': 'Routing for this session',
911
- 'hooks (stale)': 'Hook definitions current',
912
- 'hooks (adapter)': 'Hook adapter',
913
- 'hooks (trust)': 'Codex hook trust',
914
- 'hooks (stop shape)': 'Turn-end hook shape',
915
- 'hooks (duplicates)': 'Duplicate hook installs',
916
- 'hooks (codex representation)': 'Codex hook representation',
917
- 'hooks (question admission)': 'Question admission',
918
- 'hooks (fired)': 'Hooks have run here',
919
- 'hooks (answer continuation)': 'How an answer returns',
920
- 'hooks (wake route)': 'Direct wake route',
921
- }
922
-
923
- function checkTitle(name: string): string {
924
- return CHECK_TITLES[name] ?? name
925
- }
926
-
927
- /** Real but not in the way; see the note above. */
928
- const informational = new Set<string>()
929
- return [
930
- ...hookChecks(deps).map((check) => ({
931
- id: check.name.replace(/[ ()]+/g, '-').replace(/-$/, ''),
932
- title: checkTitle(check.name),
933
- status: check.ok
934
- ? 'ready' as const
935
- : check.informational === true || informational.has(check.name)
936
- ? 'optional-gap' as const
937
- : 'gap' as const,
938
- detail: check.detail,
939
- ...(check.ok
940
- ? {}
941
- : {
942
- remedy: {
943
- by: 'user-here' as const,
944
- // The check's own remedy when it has one; the generic reinstall
945
- // line was wrong exactly where it mattered (an unfired pointer
946
- // needs a prompt, not `hooks install`).
947
- ...(check.remedy ?? {
948
- summary: 'the detail above names what to change',
949
- command: 'notifai hooks install',
950
- }),
951
- },
952
- }),
953
- })),
954
- settings,
955
- ]
956
- }
957
-
958
-
959
- interface HookCheck {
960
- name: string
961
- ok: boolean
962
- detail: string
963
- /** Real but not in the way: worth a line, never a blocker. */
964
- informational?: boolean
965
- /** A remedy truer than the generic `notifai hooks install`. */
966
- remedy?: {
967
- summary: string
968
- command: string
969
- user_action?: { code: string; harness: string; action: string; message: string }
970
- }
971
- }
972
-
973
- function hookChecks(deps: CommandDeps): HookCheck[] {
974
- const checks: HookCheck[] = []
975
- const installations = findInstallations(deps.cwd, deps.env, deps.hookAdapterHome, deps.hookPlatform)
976
-
977
- // Not having hooks is a setup someone chose, not a fault: `send` works
978
- // without them. A setup that cannot work is what deserves to go red.
979
- if (installations.length === 0) {
980
- checks.push({
981
- name: 'hooks',
982
- ok: true,
983
- detail: 'not installed (optional) — `notifai hooks install` adds question routing',
984
- })
985
- return checks
986
- }
987
- checks.push({
988
- name: 'hooks',
989
- ok: true,
990
- detail: installations
991
- .map((i) => `${i.harness} ${i.global ? 'global' : 'project'} (${i.file})`)
992
- .join(', '),
993
- })
994
-
995
- const wired = new Set(installations.map((installation) => installation.harness))
996
- const unwired = detectedHarnesses(deps.cwd, deps.env).filter((harness) => !wired.has(harness))
997
- if (unwired.length > 0) {
998
- checks.push({
999
- name: 'hooks (detected)',
1000
- ok: false,
1001
- informational: true,
1002
- detail: `${unwired.map((harness) => HARNESS_LABELS[harness]).join(', ')} detected on this machine but not wired`,
1003
- remedy: {
1004
- summary: 'install hooks for every detected harness',
1005
- command: 'notifai hooks install',
1006
- },
1007
- })
1008
- }
1009
-
1010
- const { active, contested } = resolveActiveHarness(
1011
- deps.env,
1012
- deps.cwd,
1013
- (deps.now ?? Date.now)(),
1014
- )
1015
- const activeInstallations =
1016
- active === null
1017
- ? []
1018
- : installations.filter((installation) => installation.harness === active.harness)
1019
- if (contested.length > 1) {
1020
- checks.push({
1021
- name: 'hooks (active harness)',
1022
- ok: false,
1023
- informational: true,
1024
- detail: `Several harness sessions could own this shell (${contested.map((candidate) => candidate.label).join(', ')}); routing readiness is intentionally not attributed to either one`,
1025
- })
1026
- } else if (active !== null && !isHookInstallableHarness(active.harness)) {
1027
- checks.push({
1028
- name: 'hooks (active harness)',
1029
- ok: true,
1030
- informational: true,
1031
- detail: `${active.label}: ${HERMES_QUESTION_ROUTING_UNAVAILABLE.deliveryContract}`,
1032
- })
1033
- } else if (active !== null) {
1034
- checks.push({
1035
- name: 'hooks (active harness)',
1036
- ok: activeInstallations.length > 0,
1037
- detail:
1038
- activeInstallations.length > 0
1039
- ? `active ${active.label} session has a matching hook installation`
1040
- : `active ${active.label} session has no matching hook installation — run \`notifai hooks install --harness ${active.harness}\``,
1041
- ...(activeInstallations.length > 0
1042
- ? {}
1043
- : {
1044
- remedy: {
1045
- summary: `install hooks for the active ${active.label} session`,
1046
- command: `notifai hooks install --harness ${active.harness}`,
1047
- },
1048
- }),
1049
- })
1050
- if (activeInstallations.length > 0) {
1051
- const exactState = active.sessionId === undefined
1052
- ? null
1053
- : readSessionState(active.sessionId, deps.env)
1054
- const activated = exactState?.harness === active.harness && exactState.last_prompt_at !== undefined
1055
- if (!activated) {
1056
- // The normal condition of hooks installed moments ago: the pointer
1057
- // appears when the harness next fires a hook, and no command can
1058
- // force that. Informational, so `init` walks on to the states it can
1059
- // actually prove instead of exiting over evidence only time produces.
1060
- checks.push({
1061
- name: 'hooks (active session)',
1062
- ok: false,
1063
- informational: true,
1064
- detail: `active ${active.label} session has not published exact lifecycle state — send one ${active.label} prompt, then check again`,
1065
- remedy: {
1066
- summary: `send one ${active.label} prompt — its hook publishes the routing pointer`,
1067
- command: 'notifai doctor',
1068
- },
1069
- })
1070
- } else {
1071
- checks.push({
1072
- name: 'hooks (active session)',
1073
- ok: true,
1074
- detail: `the exact active ${active.label} session has published lifecycle state`,
1075
- })
1076
- }
1077
- }
1078
- }
1079
-
1080
- // A handler naming an event this build dropped exits 2 every time the harness
1081
- // fires it, which the harness reports as a hook failure.
1082
- const stale = installations.flatMap((i) =>
1083
- i.handlers
1084
- .filter((h) => {
1085
- const event = handlerEvent(h.command)
1086
- return event !== null && !(HOOK_EVENTS as readonly string[]).includes(event)
1087
- })
1088
- .map((h) => `${h.event} -> ${handlerEvent(h.command)} in ${i.file}`),
1089
- )
1090
- const missing = installations.flatMap((installation) => {
1091
- const required = requiredHookEvents(installation.harness)
1092
- const installed = new Set(
1093
- installation.handlers
1094
- .map((handler) => handlerEvent(handler.command))
1095
- .filter((event): event is string => event !== null),
1096
- )
1097
- const absent = required.filter((event) => !installed.has(event))
1098
- return absent.length === 0
1099
- ? []
1100
- : [`${installation.file} is missing ${absent.join(', ')}`]
1101
- })
1102
- checks.push({
1103
- name: 'hooks (stale)',
1104
- ok: stale.length === 0 && missing.length === 0,
1105
- detail:
1106
- stale.length === 0 && missing.length === 0
1107
- ? 'every installed handler names an event this build serves, and every required lifecycle handler is present'
1108
- : `${[...stale, ...missing].join('; ')} — rerun \`notifai hooks install\` to refresh the complete lifecycle set`,
1109
- })
1110
-
1111
- const adapterProblems = installations.flatMap((installation) =>
1112
- (installation.problems ?? []).map((problem) => `${installation.file}: ${problem}`),
1113
- )
1114
- const sharedAdapter = inspectHookAdapter(deps.hookAdapterHome, deps.hookPlatform)
1115
- adapterProblems.push(...sharedAdapter.problems)
1116
- if (adapterProblems.length > 0) {
1117
- checks.push({
1118
- name: 'hooks (adapter)',
1119
- ok: false,
1120
- // A machine-global install for a harness that is not active in this
1121
- // project is useful diagnosis, but it must not block unrelated init.
1122
- informational: active === null && installations.every((installation) => installation.global),
1123
- detail: adapterProblems.join('; '),
1124
- })
1125
- }
1126
-
1127
- const trustProblems = codexTrustProblems(installations, deps.env)
1128
- checks.push({
1129
- name: 'hooks (trust)',
1130
- ok: trustProblems.length === 0,
1131
- detail:
1132
- trustProblems.length === 0
1133
- ? 'best-effort check matches current persisted Codex approvals; Notifai never writes the trust store, and `/hooks` is authoritative'
1134
- : `best-effort check only; Notifai never writes the trust store and \`/hooks\` is authoritative. ${trustProblems.join('; ')}`,
1135
- ...(trustProblems.length === 0
1136
- ? {}
1137
- : {
1138
- remedy: {
1139
- summary: 'open `/hooks` in Codex and approve the changed Notifai handlers',
1140
- command: '/hooks',
1141
- user_action: {
1142
- code: 'codex_hook_approval_required',
1143
- harness: 'codex',
1144
- action: 'approve_or_enable_notifai_hooks',
1145
- message: 'Open `/hooks` in Codex, approve or enable the Notifai handlers, then tell me when it is done. I will finish setup and verify a fresh session.',
1146
- },
1147
- },
1148
- }),
1149
- })
1150
-
1151
- const shapeProblems = installations.flatMap((installation) =>
1152
- stopShapeProblems(installation, deps.hookPlatform).map(
1153
- (problem) =>
1154
- `${problem} — run \`notifai hooks install --harness ${installation.harness}${installation.global ? ' --global' : ''}\``,
1155
- ),
1156
- )
1157
- checks.push({
1158
- name: 'hooks (stop shape)',
1159
- ok: shapeProblems.length === 0,
1160
- detail:
1161
- shapeProblems.length === 0
1162
- ? `every installed Stop handler declares the shape its harness needs: Claude Code async and Codex blocking with an explicit ${QUESTION_STOP_TIMEOUT_SECONDS}s full-window budget; non-routing blocking hosts ${NON_ROUTING_BLOCKING_STOP_TIMEOUT_SECONDS}s`
1163
- : shapeProblems.join('; '),
1164
- })
1165
-
1166
- // Project and global definitions for one harness both fire. Stable adapter
1167
- // identity deliberately makes their command bytes equal, so comparing
1168
- // command targets would now hide this duplicate rather than diagnose it.
1169
- // Cursor is the exception to harness independence because it may also load
1170
- // Claude's user hook file. The shared adapter detects Cursor's hook-only
1171
- // environment and makes that compatibility copy a no-op; the native Cursor
1172
- // definition remains the single routing owner.
1173
- const duplicated = [...new Set(installations.map((i) => i.harness))]
1174
- .map((harness) => ({
1175
- harness,
1176
- installations: installations.filter((i) => i.harness === harness),
1177
- }))
1178
- .filter(
1179
- (entry) =>
1180
- entry.installations.some((installation) => installation.global) &&
1181
- entry.installations.some((installation) => !installation.global),
1182
- )
1183
- if (duplicated.length > 0) {
1184
- checks.push({
1185
- name: 'hooks (duplicates)',
1186
- ok: false,
1187
- detail: duplicated
1188
- .map(
1189
- (entry) =>
1190
- `${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(', ')}`,
1191
- )
1192
- .join('; '),
1193
- })
1194
- }
1195
-
1196
- const representationProblems = codexRepresentationProblems(
1197
- deps.cwd,
1198
- deps.env,
1199
- deps.hookPlatform,
1200
- )
1201
- if (representationProblems.length > 0) {
1202
- checks.push({
1203
- name: 'hooks (codex representation)',
1204
- ok: false,
1205
- detail: representationProblems.join('; '),
1206
- })
1207
- } else {
1208
- const coexistence = codexCoexistenceNotes(deps.cwd, deps.env, deps.hookPlatform)
1209
- if (coexistence.length > 0) {
1210
- checks.push({
1211
- name: 'hooks (codex representation)',
1212
- ok: true,
1213
- detail: coexistence.join('; '),
1214
- })
1215
- }
1216
- }
1217
-
1218
- const codexHome = codexHomeNote(deps.env, deps.hookPlatform)
1219
- if (codexHome !== null) {
1220
- checks.push({ name: 'hooks (codex home)', ok: true, detail: codexHome })
1221
- }
1222
-
1223
- if (active !== null && activeInstallations.length > 0) {
1224
- const admissionProblems = activeQuestionRouteProblems(deps, active, installations)
1225
- checks.push({
1226
- name: 'hooks (question admission)',
1227
- ok: admissionProblems.length === 0,
1228
- detail:
1229
- admissionProblems.length === 0
1230
- ? `the active ${active.label} route is exact, current, singular, trusted where applicable, and bounded by a live owner`
1231
- : admissionProblems.join('; '),
1232
- })
1233
- }
1234
-
1235
- // Which route this judges, and which remedy it prints, must both belong to
1236
- // the harness that is actually running here. A machine-global installation
1237
- // matches every directory, so picking whichever installation matched — or
1238
- // whichever session last wrote a pointer — reports on a harness the agent
1239
- // cannot influence: it is told to send a prompt in a harness that is not
1240
- // running, follows the fail-closed rule, and can never clear the check.
1241
- const firedPointer =
1242
- active === null
1243
- ? readProjectSessionPointer(deps.cwd, deps.env, (deps.now ?? Date.now)())
1244
- : active.sessionId === undefined
1245
- ? (readLiveProjectSessionPointers(deps.cwd, deps.env, (deps.now ?? Date.now)()).find(
1246
- (pointer) => pointer.harness === active.harness,
1247
- ) ?? null)
1248
- : readSessionState(active.sessionId, deps.env).harness === active.harness
1249
- ? { sessionId: active.sessionId, harness: active.harness }
1250
- : null
1251
- const firedState = firedPointer === null ? null : readSessionState(firedPointer.sessionId, deps.env)
1252
- const promptFired = firedState?.last_prompt_at !== undefined
1253
- const stopFired = firedState?.last_stop_at !== undefined
1254
- const fired = firedPointer !== null && promptFired && stopFired
1255
- // Installations for other harnesses are irrelevant to the active one, and an
1256
- // active harness with none of its own has nothing to activate: say that
1257
- // instead of advising a prompt in some other harness. When the environment
1258
- // is contested and nothing has fired, every candidate is still possible, so
1259
- // the advice covers all of them rather than betting on one.
1260
- const activationHarnesses = new Set(
1261
- contested.length > 1
1262
- ? contested.map((candidate) => candidate.harness)
1263
- : active === null
1264
- ? installations.map((installation) => installation.harness)
1265
- : [active.harness],
1266
- )
1267
- const activationInstallations = installations.filter((installation) =>
1268
- activationHarnesses.has(installation.harness),
1269
- )
1270
- const activationAdvice =
1271
- activationInstallations.length > 0
1272
- ? hookActivationAdvice(activationInstallations)
1273
- : active === null
1274
- ? hookActivationAdvice(installations)
1275
- : `${active.label}: no ${active.label} hook installation matches this project — run \`notifai hooks install --harness ${active.harness}\`.`
1276
- checks.push({
1277
- name: 'hooks (fired)',
1278
- ok: fired,
1279
- // A wholly fresh install is informational. Once UserPromptSubmit has fired,
1280
- // a missing Stop is a broken route, not missing historical evidence.
1281
- informational: firedPointer === null,
1282
- detail: fired
1283
- ? active === null
1284
- ? 'a session in this directory has run UserPromptSubmit and Stop'
1285
- : `the active ${active.label} session has run UserPromptSubmit and Stop`
1286
- : firedPointer === null
1287
- ? `no ${
1288
- contested.length > 1
1289
- ? `session pointer for any harness whose markers are present here (${contested
1290
- .map((candidate) => candidate.label)
1291
- .join(', ')})`
1292
- : active === null
1293
- ? 'session pointer'
1294
- : `${active.label} session pointer`
1295
- } from the last 24 hours — ${activationAdvice}`
1296
- : `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`,
1297
- ...(fired
1298
- ? {}
1299
- : {
1300
- remedy: {
1301
- summary:
1302
- firedPointer === null
1303
- ? `send one ${active === null || contested.length > 1 ? '' : `${active.label} `}prompt in a session here, then re-check`
1304
- : 'end one harmless turn, send a new prompt, then re-check',
1305
- command: 'notifai doctor',
1306
- },
1307
- }),
1308
- })
1309
-
1310
- const continuationInstallations =
1311
- active !== null ? activeInstallations : installations
1312
- const continuationHarnesses = [
1313
- ...new Set(continuationInstallations.map((installation) => installation.harness)),
1314
- ]
1315
- checks.push({
1316
- name: 'hooks (answer continuation)',
1317
- ok:
1318
- continuationHarnesses.length > 0 &&
1319
- continuationHarnesses.every(
1320
- (harness) => HARNESS_CAPABILITIES[harness].stopContinuation !== 'unsupported',
1321
- ),
1322
- informational: active === null,
1323
- detail:
1324
- continuationHarnesses.length === 0
1325
- ? active === null
1326
- ? 'no installed harness route to assess'
1327
- : `the active ${active.label} session has no matching continuation adapter`
1328
- : continuationHarnesses
1329
- .map((harness) => `${harness}: ${HARNESS_CAPABILITIES[harness].deliveryContract}`)
1330
- .join('; '),
1331
- })
1332
-
1333
- const wakeRoute = wakeRouteCheck(deps, active, activeInstallations)
1334
- if (wakeRoute !== null) checks.push(wakeRoute)
1335
-
1336
- const stray = codexStrayWorktreeCheck(deps)
1337
- if (stray !== null) checks.push(stray)
1338
-
1339
- return checks
1340
- }
1341
-
1342
- /**
1343
- * Whether an answer arriving after this turn ends could actually reach this
1344
- * exact session — the question `notifai ask` really turns on, and the one no
1345
- * other check answers.
1346
- *
1347
- * Read-only, and deliberately so: nothing here connects to a socket, takes a
1348
- * lock, or sends a message. A diagnostic that wakes the agent it is diagnosing
1349
- * would be its own bug report.
1350
- *
1351
- * Everything it can report negatively is a degradation rather than a failure —
1352
- * the accepted journal still replays the answer at the session's next turn —
1353
- * so this is never a blocker. What it buys is that the reason has a name
1354
- * before the user notices the silence.
1355
- *
1356
- * It never asks for `crossSessionInbound`. The poster is the session's own
1357
- * hook child and takes the privileged own-child path, verified to be delivered
1358
- * even against a `bypassPermissions` receiver while an unrelated process was
1359
- * held. Widening a user's general inbound policy to suit Notifai would be a
1360
- * real change to their machine's posture in exchange for nothing.
1361
- */
1362
- function wakeRouteCheck(
1363
- deps: CommandDeps,
1364
- active: ActiveHarnessSession | null,
1365
- activeInstallations: Installation[],
1366
- ): HookCheck | null {
1367
- if (active === null || activeInstallations.length === 0) return null
1368
- if (active.harness === 'claude-code') {
1369
- const readiness = inspectClaudeInbox({
1370
- pid: deps.claudeSourcePid ?? claudeSessionPid(deps.env),
1371
- platform: deps.hookPlatform ?? process.platform,
1372
- readDescriptor:
1373
- deps.claudeWake?.readDescriptor ?? systemClaudeWakeAdapters(deps.env).readDescriptor,
1374
- socketExists: (socketPath) => existsSync(socketPath),
1375
- })
1376
- return {
1377
- name: 'hooks (wake route)',
1378
- ok: readiness.state === 'ready',
1379
- informational: true,
1380
- detail:
1381
- readiness.state === 'ready'
1382
- ? `this Claude Code ${readiness.version} session is listening on ${readiness.socketPath}, so an answer can start a turn here without you`
1383
- : `${readiness.reason}. Answers are still delivered, at this session's next turn rather than on their own`,
1384
- }
1385
- }
1386
- if (active.harness === 'codex') {
1387
- const readiness = inspectCodexResume(deps.env, {
1388
- platform: deps.hookPlatform ?? process.platform,
1389
- directoryExists: (directory) => existsSync(directory),
1390
- })
1391
- return {
1392
- name: 'hooks (wake route)',
1393
- ok: readiness.state === 'ready',
1394
- informational: true,
1395
- detail:
1396
- readiness.state === 'ready'
1397
- ? `the held Codex turn continues from its own hook, and after it returns ${readiness.lockDirectory} can prove a stopped thread unowned before resuming it`
1398
- : `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`,
1399
- }
1400
- }
1401
- return null
1402
- }
1403
-
1404
- /**
1405
- * A Codex hooks file sitting in a worktree, which Codex will never read.
1406
- *
1407
- * `settingsFile` now writes to the main repository, so this only fires for a
1408
- * file an older build left behind — but that file is indistinguishable from a
1409
- * working install if you go looking, and it is exactly what made this bug take
1410
- * a day to find. Omitted entirely when there is nothing to say.
1411
- */
1412
- function codexStrayWorktreeCheck(
1413
- deps: CommandDeps,
1414
- ): { name: string; ok: boolean; detail: string } | null {
1415
- const layer = codexLayerDir(deps.cwd)
1416
- if (layer === null) return null
1417
- const root = codexProjectRoot(deps.cwd)
1418
- const project = inspectCodexLayer(codexLayerPaths(false, deps.cwd, deps.env))
1419
- if (project.jsonEvents.length === 0 && project.tomlEvents.length === 0) return null
1420
- const strayJson = path.join(path.dirname(layer), '.codex', 'hooks.json')
1421
- const strayToml = path.join(path.dirname(layer), '.codex', 'config.toml')
1422
- const problems: string[] = []
1423
- if (!existsSync(layer)) {
1424
- problems.push(`${layer} is missing, so Codex never looks for project hooks here`)
1425
- }
1426
- if (existsSync(strayJson) && path.resolve(strayJson) !== path.resolve(project.paths.hooksJson)) {
1427
- problems.push(`${strayJson} is never read — Codex reads ${project.writeTarget} instead`)
1428
- }
1429
- if (existsSync(strayToml) && path.resolve(strayToml) !== path.resolve(project.paths.configToml)) {
1430
- problems.push(`${strayToml} is never read — Codex reads ${project.writeTarget} instead`)
1431
- }
1432
- return {
1433
- name: 'hooks (codex worktree)',
1434
- ok: problems.length === 0,
1435
- detail:
1436
- problems.length === 0
1437
- ? `worktree wired to the main repository at ${root}`
1438
- : `${problems.join('; ')}. Re-run \`notifai hooks install\` to fix.`,
1439
- }
1440
- }