failproofai 1.0.15 → 1.0.16-beta.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 (159) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +13 -13
  3. package/.next/standalone/.next/prerender-manifest.json +4 -4
  4. package/.next/standalone/.next/required-server-files.json +1 -1
  5. package/.next/standalone/.next/server/app/_global-error/page/build-manifest.json +2 -2
  6. package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
  7. package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
  8. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.rsc +2 -2
  11. package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +2 -2
  12. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +2 -2
  13. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/.next/standalone/.next/server/app/_not-found/page/build-manifest.json +2 -2
  15. package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
  16. package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
  17. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  18. package/.next/standalone/.next/server/app/_not-found.html +1 -1
  19. package/.next/standalone/.next/server/app/_not-found.rsc +4 -4
  20. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +4 -4
  21. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +3 -3
  22. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  23. package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
  24. package/.next/standalone/.next/server/app/api/audit/run/route.js +22 -21
  25. package/.next/standalone/.next/server/app/api/audit/run/route.js.nft.json +1 -1
  26. package/.next/standalone/.next/server/app/api/audit/status/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/auth/login-request/route.js.nft.json +1 -1
  28. package/.next/standalone/.next/server/app/api/auth/login-verify/route.js.nft.json +1 -1
  29. package/.next/standalone/.next/server/app/api/auth/logout/route.js.nft.json +1 -1
  30. package/.next/standalone/.next/server/app/api/auth/status/route.js.nft.json +1 -1
  31. package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
  32. package/.next/standalone/.next/server/app/audit/page/build-manifest.json +2 -2
  33. package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
  34. package/.next/standalone/.next/server/app/audit/page.js +4 -3
  35. package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
  36. package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
  37. package/.next/standalone/.next/server/app/index.html +1 -1
  38. package/.next/standalone/.next/server/app/index.rsc +4 -4
  39. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  40. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +4 -4
  41. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  42. package/.next/standalone/.next/server/app/page/build-manifest.json +2 -2
  43. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  44. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  45. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  46. package/.next/standalone/.next/server/app/policies/page/build-manifest.json +2 -2
  47. package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +14 -14
  48. package/.next/standalone/.next/server/app/policies/page.js +8 -7
  49. package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
  50. package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
  51. package/.next/standalone/.next/server/app/project/[name]/page/build-manifest.json +2 -2
  52. package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
  53. package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
  54. package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
  55. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/build-manifest.json +2 -2
  56. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
  57. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
  58. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
  59. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
  60. package/.next/standalone/.next/server/app/projects/page/build-manifest.json +2 -2
  61. package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
  62. package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
  63. package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  64. package/.next/standalone/.next/server/app/settings/page/build-manifest.json +2 -2
  65. package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +8 -8
  66. package/.next/standalone/.next/server/app/settings/page.js +8 -7
  67. package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
  68. package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  69. package/.next/standalone/.next/server/chunks/[root-of-the-server]__048f1wnr8pysf._.js +4 -4
  70. package/.next/standalone/.next/server/chunks/_0tovk6q0miud6._.js +1 -1
  71. package/.next/standalone/.next/server/chunks/_0trp3ycqv17cl._.js +1 -1
  72. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4vkpxxu7._.js +1 -1
  73. package/.next/standalone/.next/server/chunks/src_hooks_0fmclqlaj83-2._.js +5 -0
  74. package/.next/standalone/.next/server/chunks/src_hooks_15j31lnj-km9r._.js +3 -0
  75. package/.next/standalone/.next/server/chunks/src_hooks_daemon-client_ts_0il_yu1zc0291._.js +1 -1
  76. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__08ch3staq3ejw._.js +1 -1
  77. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0bigvy9xmv2ka._.js +1 -1
  78. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0h86bl2qf0k_o._.js +1 -1
  79. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0pia5h3p8re4c._.js +1 -1
  80. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0t76rmc_vci18._.js +3 -0
  81. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1vofkb2oq7p7e._.js → [root-of-the-server]__0tayeyopslkf1._.js} +1 -1
  82. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1-ey9fgesfbc0._.js +1 -1
  83. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__15usvs-ms-0hf._.js +1 -1
  84. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__16gb3_92zvk5x._.js +1 -1
  85. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1avi2kypusyb_._.js +1 -1
  86. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1r7drlqli-ado._.js +1 -1
  87. package/.next/standalone/.next/server/chunks/ssr/_0eoura3_9gjb-._.js +1 -1
  88. package/.next/standalone/.next/server/chunks/ssr/_0f-kswpk5hx7v._.js +3 -0
  89. package/.next/standalone/.next/server/chunks/ssr/_0pedwblqdoh58._.js +1 -1
  90. package/.next/standalone/.next/server/chunks/ssr/_1djqs9i27e4kg._.js +1 -1
  91. package/.next/standalone/.next/server/chunks/ssr/_next-internal_server_app_policies_page_actions_1sp2-yo5_vm5f.js +5 -5
  92. package/.next/standalone/.next/server/chunks/ssr/app_actions_get-scheduled-audit_ts_0ei9snixb5fd-._.js +1 -1
  93. package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47q0xq5w._.js +1 -1
  94. package/.next/standalone/.next/server/chunks/ssr/app_components_project-list_tsx_1ke6anr0vt64h._.js +1 -1
  95. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x33jqb6._.js +1 -1
  96. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpcz0uxur._.js +1 -1
  97. package/.next/standalone/.next/server/chunks/ssr/app_settings_02tf1h47jmhhd._.js +1 -1
  98. package/.next/standalone/.next/server/chunks/ssr/{node_modules_html-to-image_es_index_0e3yg5gbcfsai.js → node_modules_html-to-image_es_index_0wgfci23_yqs_.js} +1 -1
  99. package/.next/standalone/.next/server/chunks/ssr/package_json_[json]_cjs_013tntikdft59._.js +1 -1
  100. package/.next/standalone/.next/server/chunks/ssr/src_hooks_1-ytegsicaf2d._.js +5 -0
  101. package/.next/standalone/.next/server/chunks/ssr/src_hooks_1euxn1va7c5gq._.js +5 -0
  102. package/.next/standalone/.next/server/chunks/ssr/src_hooks_daemon-client_ts_0k41_i7jg6ndv._.js +1 -1
  103. package/.next/standalone/.next/server/chunks/ssr/src_hooks_daemon-service_ts_0ibufora3s_bw._.js +1 -1
  104. package/.next/standalone/.next/server/chunks/ssr/src_hooks_effective-reviewers_ts_1h4wtvo55j16x._.js +3 -0
  105. package/.next/standalone/.next/server/middleware-build-manifest.js +13 -13
  106. package/.next/standalone/.next/server/pages/404.html +1 -1
  107. package/.next/standalone/.next/server/pages/500.html +1 -1
  108. package/.next/standalone/.next/server/preview-props.json +3 -3
  109. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  110. package/.next/standalone/.next/server/server-reference-manifest.json +23 -23
  111. package/.next/standalone/.next/static/chunks/{0oxlfb02aqo3e.js → 0fqjv13piwa6z.js} +1 -1
  112. package/.next/standalone/.next/static/chunks/{1osrmi14e2jub.js → 0y9qczsccrmmf.js} +1 -1
  113. package/.next/standalone/.next/static/chunks/{0p14j2e6dnj1x.js → 0z70k3nof30ws.js} +1 -1
  114. package/.next/standalone/.next/static/chunks/{05g1pu2r8o5q3.js → 167exo9u6npy3.js} +1 -1
  115. package/.next/standalone/.next/static/chunks/{098vx6twrn-vk.js → 1xwh61k4505md.js} +1 -1
  116. package/.next/standalone/.next/static/chunks/{3d6_vjbvr0c2n.js → 24nikgpkr0qas.js} +1 -1
  117. package/.next/standalone/.next/static/chunks/{38lnk75xvqiug.js → 2ayu58wi805x4.js} +1 -1
  118. package/.next/standalone/.next/static/chunks/{0tiuj32d-qcy3.js → 2swcvie6i54dn.js} +1 -1
  119. package/.next/standalone/.next/static/chunks/2xx-2wehe-kwl.js +1 -0
  120. package/.next/standalone/.next/static/chunks/{1i9zuw01f0ogt.js → 3r-j6pmqrq4l1.js} +2 -2
  121. package/.next/standalone/.next/static/chunks/{2zwsbp8xyfv__.js → 3tfcj166ki-08.js} +1 -1
  122. package/.next/standalone/.next/static/chunks/{12ys9uaq6i1h2.js → 3uj5quosl7j_x.js} +1 -1
  123. package/.next/standalone/hermes-plugin/client.py +97 -37
  124. package/.next/standalone/hermes-plugin/plugin.yaml +1 -1
  125. package/.next/standalone/package.json +9 -9
  126. package/.next/standalone/server.js +1 -1
  127. package/bin/failproofai.mjs +66 -90
  128. package/dist/cli.mjs +1421 -1489
  129. package/dist/worker.mjs +19 -4
  130. package/hermes-plugin/client.py +97 -37
  131. package/hermes-plugin/plugin.yaml +1 -1
  132. package/openclaw-plugin/daemon-client.js +72 -16
  133. package/openclaw-plugin/hooks.js +12 -0
  134. package/package.json +9 -9
  135. package/pi-extension/index.ts +2 -0
  136. package/src/hooks/cloud-managed-policies.ts +22 -0
  137. package/src/hooks/config-status.ts +34 -21
  138. package/src/hooks/configure-wizard.ts +16 -3
  139. package/src/hooks/daemon-client.ts +59 -16
  140. package/src/hooks/daemon-service.ts +167 -19
  141. package/src/hooks/delivery-health.ts +10 -0
  142. package/src/hooks/fp-home.ts +8 -0
  143. package/src/hooks/fp-reset.ts +8 -2
  144. package/src/hooks/gateway-restart.ts +248 -0
  145. package/src/hooks/handler.ts +39 -2
  146. package/src/hooks/hermes-update.ts +18 -2
  147. package/src/hooks/hook-activity-store.ts +5 -0
  148. package/src/hooks/manager.ts +43 -9
  149. package/src/hooks/shell-quote.ts +19 -0
  150. package/src/hooks/update-run.ts +276 -0
  151. package/.next/standalone/.next/server/chunks/src_hooks_0_em82s16zfym._.js +0 -5
  152. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__05-glpesefmmi._.js +0 -3
  153. package/.next/standalone/.next/server/chunks/ssr/_0ge1hz9485xpp._.js +0 -3
  154. package/.next/standalone/.next/server/chunks/ssr/src_hooks_0agdmptetetdt._.js +0 -5
  155. package/.next/standalone/.next/server/chunks/ssr/src_hooks_0mdwgjisv4fub._.js +0 -5
  156. package/.next/standalone/.next/static/chunks/2o8j51ujh1ox4.js +0 -1
  157. /package/.next/standalone/.next/static/{-AugwIGiiIYcahO4J7mdM → _rnWxsoAWV0JPMURamq78}/_buildManifest.js +0 -0
  158. /package/.next/standalone/.next/static/{-AugwIGiiIYcahO4J7mdM → _rnWxsoAWV0JPMURamq78}/_clientMiddlewareManifest.js +0 -0
  159. /package/.next/standalone/.next/static/{-AugwIGiiIYcahO4J7mdM → _rnWxsoAWV0JPMURamq78}/_ssgManifest.js +0 -0
package/dist/cli.mjs CHANGED
@@ -29,7 +29,7 @@ var __esm = (fn, res, err) => () => {
29
29
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
30
30
 
31
31
  // package.json
32
- var version2 = "1.0.15", package_default;
32
+ var version2 = "1.0.16-beta.0", package_default;
33
33
  var init_package = __esm(() => {
34
34
  package_default = {
35
35
  name: "failproofai",
@@ -160,16 +160,16 @@ var init_package = __esm(() => {
160
160
  minimatch: "11.0.3"
161
161
  },
162
162
  optionalDependencies: {
163
- "@failproofai/failproofaid-linux-x64": "1.0.15",
164
- "@failproofai/failproofaid-linux-arm64": "1.0.15",
165
- "@failproofai/failproofaid-darwin-x64": "1.0.15",
166
- "@failproofai/failproofaid-darwin-arm64": "1.0.15"
163
+ "@failproofai/failproofaid-linux-x64": "1.0.16-beta.0",
164
+ "@failproofai/failproofaid-linux-arm64": "1.0.16-beta.0",
165
+ "@failproofai/failproofaid-darwin-x64": "1.0.16-beta.0",
166
+ "@failproofai/failproofaid-darwin-arm64": "1.0.16-beta.0"
167
167
  },
168
168
  failproofaidBinaries: {
169
- "linux-x64": "e5c7543ab9aeb5366e804d4cf5aef8ee35ef340f145c1c15f683b76761426fe6",
170
- "linux-arm64": "06d27497490f7a1cec34f03808a3bf6a5644830fdf7db9133642b464f5affcde",
171
- "darwin-x64": "763e6a6790d8c247765a83c92f9de65875807c96fee098c15748ac098ff99513",
172
- "darwin-arm64": "a422303761f70023ad9a8d3a9b0b0e8689adc4669bddd90f72722b3df6b33ab4"
169
+ "linux-x64": "201c0518311a351fafb7ba856a8a6f441d3100497c8ce68f2954575c57bd90a9",
170
+ "linux-arm64": "9dfbd061d38024e3680060fb753129b63e032404948f40db825517584a1b9fb4",
171
+ "darwin-x64": "9b4f2b8476cddbaca32f1afe1f5c37b542d08308f58cb23277cf885dc497c157",
172
+ "darwin-arm64": "3b7de91ac706baa744fc7c2c059ae5ebfd5b4600a6a3c726561d685cfb13c0e8"
173
173
  }
174
174
  };
175
175
  });
@@ -255,7 +255,7 @@ var LAYOUT_VERSION = 4, at = (...parts) => resolve(failproofaiHome(), ...parts),
255
255
  if (!["claude", "codex", "copilot"].includes(agent))
256
256
  throw new Error("Unknown OTEL agent.");
257
257
  return resolve(otelAgentStateDir(), `${agent}.json`);
258
- }, otlpSpoolDir = (home) => atHome(home, "state", "spool-otlp"), otlpHealthFile = (home) => atHome(home, "state", "otlp-health.json"), credentialsFile = (home) => atHome(home, "credentials.json"), jevConfigFile = (home) => atHome(home, "jev.json"), agentRosterFile = (home) => atHome(home, "agents", "roster.json"), binDir = (home) => atHome(home, "bin"), policiesDir = (home) => atHome(home, "policies"), customPoliciesDir, globalPolicyConfigFile = (home) => atHome(home, "policies-config.json"), cloudPoliciesDir = (home) => resolve(policiesDir(home), "cloud-policies"), packsDir = (home) => resolve(policiesDir(home), "packs"), packsInstalledFile = (home) => resolve(packsDir(home), "installed.json"), cursorsDir = (source, home) => source ? resolve(atHome(home, "cursors"), source) : atHome(home, "cursors"), customAgentsDir = (home) => atHome(home, "custom-agents"), customAgentsEventsDir = (home) => resolve(customAgentsDir(home), "events"), auditDir = (home) => atHome(home, "audit"), auditDashboardFile = (home) => resolve(auditDir(home), "dashboard.json"), auditCacheDir = (home) => resolve(auditDir(home), "cache"), auditSessionFile = (home) => resolve(auditDir(home), "session.json"), auditMachineFile = (home) => resolve(auditDir(home), "machine.json"), fpcliDir = (home) => atHome(home, "fpcli"), fpcliAuthFile = (home) => resolve(fpcliDir(home), "cli-auth.json"), hookActivityDir = (home) => atHome(home, "hook-activity"), runDir = (home) => atHome(home, "run"), daemonSocket = () => process.env.FAILPROOFAI_DAEMON_SOCKET || resolve(runDir(), "failproofaid.sock"), auditLockFile = (home) => resolve(runDir(home), "audit.lock"), stateDir = (home) => atHome(home, "state"), shimsDir = (home) => resolve(stateDir(home), "shims"), spoolDir = (home) => resolve(stateDir(home), "spool"), failedDir = (home) => resolve(stateDir(home), "failed"), collectorHealthFile = (home) => resolve(stateDir(home), "collector-health.json"), sessionPauseDir = () => resolve(stateDir(), "sessions"), semanticDir = () => resolve(stateDir(), "semantic"), auditScheduleFile = (home) => resolve(auditDir(home), "schedule.json"), telemetryIdFile = (home) => resolve(stateDir(home), "telemetry-id"), launcherMarker = (home) => resolve(stateDir(home), "launcher-configured"), onboardingAttemptFile = (home) => resolve(stateDir(home), "onboarding-attempt.json"), lastVersionFile = (home) => resolve(stateDir(home), "last-version"), onboardingLockFile = (home) => resolve(stateDir(home), "onboarding.lock"), codexSessionPathsFile = (home) => resolve(stateDir(home), "codex-session-paths.json"), logsDir = (home) => atHome(home, "logs"), migrationsDir = (home) => atHome(home, "migrations"), migrationLedgerFile = (home) => resolve(migrationsDir(home), "applied.json"), migrationBackupDir = (layout, home) => resolve(migrationsDir(home), `backup-layout${layout}`), HOME_CLASSES, legacy;
258
+ }, otlpSpoolDir = (home) => atHome(home, "state", "spool-otlp"), otlpHealthFile = (home) => atHome(home, "state", "otlp-health.json"), credentialsFile = (home) => atHome(home, "credentials.json"), jevConfigFile = (home) => atHome(home, "jev.json"), agentRosterFile = (home) => atHome(home, "agents", "roster.json"), binDir = (home) => atHome(home, "bin"), policiesDir = (home) => atHome(home, "policies"), customPoliciesDir, globalPolicyConfigFile = (home) => atHome(home, "policies-config.json"), cloudPoliciesDir = (home) => resolve(policiesDir(home), "cloud-policies"), packsDir = (home) => resolve(policiesDir(home), "packs"), packsInstalledFile = (home) => resolve(packsDir(home), "installed.json"), cursorsDir = (source, home) => source ? resolve(atHome(home, "cursors"), source) : atHome(home, "cursors"), customAgentsDir = (home) => atHome(home, "custom-agents"), customAgentsEventsDir = (home) => resolve(customAgentsDir(home), "events"), auditDir = (home) => atHome(home, "audit"), auditDashboardFile = (home) => resolve(auditDir(home), "dashboard.json"), auditCacheDir = (home) => resolve(auditDir(home), "cache"), auditSessionFile = (home) => resolve(auditDir(home), "session.json"), auditMachineFile = (home) => resolve(auditDir(home), "machine.json"), fpcliDir = (home) => atHome(home, "fpcli"), fpcliAuthFile = (home) => resolve(fpcliDir(home), "cli-auth.json"), hookActivityDir = (home) => atHome(home, "hook-activity"), runDir = (home) => atHome(home, "run"), daemonSocket = () => process.env.FAILPROOFAI_DAEMON_SOCKET || resolve(runDir(), "failproofaid.sock"), auditLockFile = (home) => resolve(runDir(home), "audit.lock"), stateDir = (home) => atHome(home, "state"), shimsDir = (home) => resolve(stateDir(home), "shims"), spoolDir = (home) => resolve(stateDir(home), "spool"), failedDir = (home) => resolve(stateDir(home), "failed"), collectorHealthFile = (home) => resolve(stateDir(home), "collector-health.json"), sessionPauseDir = () => resolve(stateDir(), "sessions"), semanticDir = () => resolve(stateDir(), "semantic"), auditScheduleFile = (home) => resolve(auditDir(home), "schedule.json"), telemetryIdFile = (home) => resolve(stateDir(home), "telemetry-id"), launcherMarker = (home) => resolve(stateDir(home), "launcher-configured"), onboardingAttemptFile = (home) => resolve(stateDir(home), "onboarding-attempt.json"), lastVersionFile = (home) => resolve(stateDir(home), "last-version"), updatedVersionFile = (home) => resolve(stateDir(home), "updated-version"), onboardingLockFile = (home) => resolve(stateDir(home), "onboarding.lock"), codexSessionPathsFile = (home) => resolve(stateDir(home), "codex-session-paths.json"), logsDir = (home) => atHome(home, "logs"), migrationsDir = (home) => atHome(home, "migrations"), migrationLedgerFile = (home) => resolve(migrationsDir(home), "applied.json"), migrationBackupDir = (layout, home) => resolve(migrationsDir(home), `backup-layout${layout}`), HOME_CLASSES, legacy;
259
259
  var init_fp_home = __esm(() => {
260
260
  customPoliciesDir = policiesDir;
261
261
  HOME_CLASSES = [
@@ -292,6 +292,7 @@ var init_fp_home = __esm(() => {
292
292
  { path: semanticDir, class: "derived" },
293
293
  { path: logsDir, class: "derived" },
294
294
  { path: lastVersionFile, class: "derived" },
295
+ { path: updatedVersionFile, class: "derived" },
295
296
  { path: launcherMarker, class: "derived" },
296
297
  { path: onboardingLockFile, class: "derived" },
297
298
  { path: onboardingAttemptFile, class: "derived" },
@@ -1779,6 +1780,546 @@ var init_agent_roster = __esm(() => {
1779
1780
  };
1780
1781
  });
1781
1782
 
1783
+ // src/hooks/hook-logger.ts
1784
+ import {
1785
+ appendFileSync,
1786
+ renameSync as renameSync2,
1787
+ mkdirSync as mkdirSync3,
1788
+ existsSync as existsSync3,
1789
+ statSync as statSync4
1790
+ } from "node:fs";
1791
+ import { join } from "node:path";
1792
+ function ensureResolved() {
1793
+ if (resolved)
1794
+ return;
1795
+ resolved = true;
1796
+ const rawLevel = (process.env.FAILPROOFAI_LOG_LEVEL ?? "").toLowerCase();
1797
+ if (rawLevel === "info" || rawLevel === "warn" || rawLevel === "error") {
1798
+ currentLevel = rawLevel;
1799
+ }
1800
+ const rawFile = (process.env.FAILPROOFAI_HOOK_LOG_FILE ?? "").trim();
1801
+ if (rawFile) {
1802
+ fileLoggingEnabled = true;
1803
+ if (rawFile !== "1" && rawFile !== "true") {
1804
+ logDir = rawFile;
1805
+ }
1806
+ }
1807
+ }
1808
+ function shouldEmit(level) {
1809
+ ensureResolved();
1810
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[currentLevel];
1811
+ }
1812
+ function emitStderr(label, msg) {
1813
+ process.stderr.write(`[failproofai:hook] ${label} ${msg}
1814
+ `);
1815
+ }
1816
+ function ensureLogDir() {
1817
+ if (!existsSync3(logDir)) {
1818
+ mkdirSync3(logDir, { recursive: true });
1819
+ }
1820
+ }
1821
+ function rotateIfNeeded(filePath) {
1822
+ try {
1823
+ const stats = statSync4(filePath);
1824
+ if (stats.size >= MAX_FILE_SIZE) {
1825
+ const archiveName = `hooks-${Date.now()}.log`;
1826
+ renameSync2(filePath, join(logDir, archiveName));
1827
+ }
1828
+ } catch {}
1829
+ }
1830
+ function appendToFile(label, msg) {
1831
+ if (!fileLoggingEnabled)
1832
+ return;
1833
+ try {
1834
+ ensureLogDir();
1835
+ const filePath = join(logDir, LOG_FILENAME);
1836
+ rotateIfNeeded(filePath);
1837
+ const timestamp = new Date().toISOString();
1838
+ const line = `[${timestamp}] ${label} ${msg}
1839
+ `;
1840
+ appendFileSync(filePath, line, "utf-8");
1841
+ } catch {}
1842
+ }
1843
+ function hookLogInfo(msg) {
1844
+ if (!shouldEmit("info"))
1845
+ return;
1846
+ emitStderr("INFO", msg);
1847
+ appendToFile("INFO", msg);
1848
+ }
1849
+ function hookLogWarn(msg) {
1850
+ if (!shouldEmit("warn"))
1851
+ return;
1852
+ emitStderr("WARN", msg);
1853
+ appendToFile("WARN", msg);
1854
+ }
1855
+ function hookLogError(msg) {
1856
+ if (!shouldEmit("error"))
1857
+ return;
1858
+ emitStderr("ERROR", msg);
1859
+ appendToFile("ERROR", msg);
1860
+ }
1861
+ var LEVEL_ORDER, MAX_FILE_SIZE, LOG_FILENAME = "hooks.log", DEFAULT_LOG_DIR, resolved = false, currentLevel = "warn", fileLoggingEnabled = false, logDir;
1862
+ var init_hook_logger = __esm(() => {
1863
+ init_fp_home();
1864
+ LEVEL_ORDER = { info: 0, warn: 1, error: 2 };
1865
+ MAX_FILE_SIZE = 512 * 1024;
1866
+ DEFAULT_LOG_DIR = logsDir();
1867
+ logDir = DEFAULT_LOG_DIR;
1868
+ });
1869
+
1870
+ // src/hooks/policy-types.ts
1871
+ function effectiveAuthority(p) {
1872
+ if (p.alwaysOn === true)
1873
+ return "hard";
1874
+ if (p.authority !== "reviewable")
1875
+ return "hard";
1876
+ if (!Array.isArray(p.reviewedBy))
1877
+ return "hard";
1878
+ const named = p.reviewedBy.filter((n) => typeof n === "string" && n.length > 0);
1879
+ return named.length > 0 ? "reviewable" : "hard";
1880
+ }
1881
+
1882
+ // src/hooks/policy-authority.ts
1883
+ import { existsSync as existsSync4 } from "node:fs";
1884
+ function resolvePolicyAuthority(decl, knownReviewers = NO_REVIEWERS, contested) {
1885
+ const declaredReviewable = decl?.authority === "reviewable";
1886
+ if (!decl || effectiveAuthority(decl) === "hard") {
1887
+ if (!declaredReviewable)
1888
+ return { authority: "hard" };
1889
+ return { authority: "hard", downgraded: whyHard(decl) };
1890
+ }
1891
+ const names = decl.reviewedBy;
1892
+ if (!names.every(isName)) {
1893
+ return { authority: "hard", downgraded: "reviewedBy is not a list of semantic policy names" };
1894
+ }
1895
+ const unknown = names.filter((n) => !knownReviewers.has(n));
1896
+ if (knownReviewers.size === 0 && !unknown.some((n) => contested?.has(n)))
1897
+ return { authority: "hard" };
1898
+ if (unknown.length > 0) {
1899
+ return { authority: "hard", downgraded: `reviewedBy names ${unknown.map((n) => whyUnknown(n, knownReviewers, contested)).join("; ")}` };
1900
+ }
1901
+ return { authority: "reviewable", reviewedBy: [...new Set(names)] };
1902
+ }
1903
+ function whyUnknown(name, known, contested) {
1904
+ const quoted = JSON.stringify(name);
1905
+ const claimants = contested?.get(name);
1906
+ if (claimants)
1907
+ return `${quoted}, which packs ${claimants.join(" and ")} declare differently, so it is asked for neither`;
1908
+ if (known === SEMANTIC_REVIEWER_NAMES)
1909
+ return `${quoted}, which is not a semantic policy in this build`;
1910
+ const sorted = [...known].sort();
1911
+ const listed = sorted.length > 6 ? `${sorted.slice(0, 6).join(", ")} and ${sorted.length - 6} more` : sorted.join(", ");
1912
+ return `${quoted}, which is not among the Jev checks it is judged against (${listed})`;
1913
+ }
1914
+ function whyHard(decl) {
1915
+ if (decl.alwaysOn === true)
1916
+ return "it is alwaysOn, and the self-protection guard is never reviewable";
1917
+ if (!Array.isArray(decl.reviewedBy) || decl.reviewedBy.length === 0) {
1918
+ return "reviewedBy does not name any semantic policy";
1919
+ }
1920
+ return "reviewedBy is not a list of semantic policy names";
1921
+ }
1922
+ function authorityFieldsOf(raw) {
1923
+ const out = {};
1924
+ if (raw.authority === "hard" || raw.authority === "reviewable")
1925
+ out.authority = raw.authority;
1926
+ const list = raw.reviewedBy;
1927
+ if (Array.isArray(list) && list.length > 0 && list.every(isName)) {
1928
+ out.reviewedBy = [...list];
1929
+ }
1930
+ return out;
1931
+ }
1932
+ function authorityProblem(decl, knownReviewers = SEMANTIC_REVIEWER_NAMES) {
1933
+ if (decl.authority !== undefined && decl.authority !== "hard" && decl.authority !== "reviewable") {
1934
+ const t = typeof decl.authority;
1935
+ return `authority must be "hard" or "reviewable", and is ${t === "string" ? JSON.stringify(decl.authority) : `${/^[aeiou]/.test(t) ? "an" : "a"} ${t}`}`;
1936
+ }
1937
+ if (decl.reviewedBy !== undefined && !(Array.isArray(decl.reviewedBy) && decl.reviewedBy.every(isName))) {
1938
+ return "reviewedBy must be a list of semantic policy names";
1939
+ }
1940
+ const { downgraded } = resolvePolicyAuthority(decl, knownReviewers);
1941
+ return downgraded ? `authority "reviewable" was refused — ${downgraded}` : undefined;
1942
+ }
1943
+ function withMergedAuthority(record, declarations, knownReviewers = NO_REVIEWERS) {
1944
+ const resolved = declarations.map((d) => resolvePolicyAuthority(d, knownReviewers));
1945
+ const allReviewable = resolved.length > 0 && resolved.every((r) => r.authority === "reviewable");
1946
+ const decided = declarations[resolved.findIndex((r) => r.authority !== "reviewable")] ?? {};
1947
+ const fields = allReviewable ? { authority: "reviewable", reviewedBy: [...new Set(resolved.flatMap((r) => r.reviewedBy ?? []))] } : decided.authority === undefined ? {} : { authority: "hard" };
1948
+ const overruled = !allReviewable && resolved.some((r) => r.authority === "reviewable");
1949
+ const refused = resolved.find((r) => r.downgraded !== undefined)?.downgraded;
1950
+ const extra = refused === undefined ? {} : { refused };
1951
+ const same = record.authority === fields.authority && JSON.stringify(record.reviewedBy) === JSON.stringify(fields.reviewedBy);
1952
+ if (same)
1953
+ return { merged: record, overruled, ...extra };
1954
+ const { authority: _a, reviewedBy: _r, ...rest } = record;
1955
+ return { merged: { ...rest, ...fields }, overruled, ...extra };
1956
+ }
1957
+ function refusedAuthorityWarning(subject, reason) {
1958
+ return `${subject} asks to be reviewable, but ${reason} — it stays hard`;
1959
+ }
1960
+ function warnAuthority(message) {
1961
+ try {
1962
+ if (!existsSync4(jevConfigFile()))
1963
+ return;
1964
+ } catch {
1965
+ return;
1966
+ }
1967
+ if (warnedAuthority.has(message))
1968
+ return;
1969
+ warnedAuthority.add(message);
1970
+ hookLogWarn(message);
1971
+ }
1972
+ function authorityDeclarationFor(hook, source) {
1973
+ if (source.cloudManaged) {
1974
+ return { authority: source.cloudManaged.authority, reviewedBy: source.cloudManaged.reviewedBy };
1975
+ }
1976
+ if (source.pack) {
1977
+ const entry = source.pack.policies.find((p) => p.name === hook.name);
1978
+ return { authority: entry?.authority, reviewedBy: entry?.reviewedBy };
1979
+ }
1980
+ return { authority: hook.authority, reviewedBy: hook.reviewedBy };
1981
+ }
1982
+ var SEMANTIC_POLICY_NAMES, SEMANTIC_REVIEWER_NAMES, NO_REVIEWERS, isName = (n) => typeof n === "string" && n.length > 0, warnedAuthority;
1983
+ var init_policy_authority = __esm(() => {
1984
+ init_fp_home();
1985
+ init_hook_logger();
1986
+ SEMANTIC_POLICY_NAMES = [
1987
+ "destructive-deletion",
1988
+ "production-infra-change",
1989
+ "git-history-rewrite",
1990
+ "push-to-protected-branch",
1991
+ "commit-on-protected-branch",
1992
+ "secret-exposure",
1993
+ "credential-exfiltration",
1994
+ "remote-code-execution",
1995
+ "privilege-escalation",
1996
+ "database-destruction",
1997
+ "read-outside-workspace",
1998
+ "agent-config-tampering",
1999
+ "system-modification",
2000
+ "env-secrets-dump",
2001
+ "external-destructive-action",
2002
+ "external-data-egress"
2003
+ ];
2004
+ SEMANTIC_REVIEWER_NAMES = new Set(SEMANTIC_POLICY_NAMES);
2005
+ NO_REVIEWERS = new Set;
2006
+ warnedAuthority = new Set;
2007
+ });
2008
+
2009
+ // src/hooks/cloud-managed-policies.ts
2010
+ import { createHash } from "node:crypto";
2011
+ import { existsSync as existsSync5, readFileSync as readFileSync3, realpathSync, rmSync as rmSync2, statSync as statSync5 } from "node:fs";
2012
+ import { isAbsolute, relative, resolve as resolve3 } from "node:path";
2013
+ function cloudManagedPolicyRoot() {
2014
+ return process.env.FAILPROOFAI_CLOUD_POLICY_DIR ?? cloudPoliciesDir();
2015
+ }
2016
+ function disconnectedByConfig() {
2017
+ try {
2018
+ const raw = JSON.parse(readFileSync3(configFile(), "utf8"));
2019
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
2020
+ return false;
2021
+ const mode = raw.mode;
2022
+ return !!mode && typeof mode === "object" && !Array.isArray(mode) && mode.kind === "oss";
2023
+ } catch {
2024
+ return false;
2025
+ }
2026
+ }
2027
+ function parseManifest(value) {
2028
+ if (!value || typeof value !== "object")
2029
+ throw new Error("active manifest is not an object");
2030
+ const raw = value;
2031
+ if (!ACCEPTED_ACTIVE_SCHEMA_VERSIONS.includes(raw.schemaVersion)) {
2032
+ throw new Error(`unsupported active manifest schema ${String(raw.schemaVersion)} ` + `(supported: ${ACCEPTED_ACTIVE_SCHEMA_VERSIONS.join(", ")})`);
2033
+ }
2034
+ const deployment = raw.deployment ?? raw.generation;
2035
+ if (!Number.isSafeInteger(deployment) || (deployment ?? -1) < 0) {
2036
+ throw new Error("active manifest deployment is invalid");
2037
+ }
2038
+ if (!Array.isArray(raw.policies))
2039
+ throw new Error("active manifest policies is not an array");
2040
+ const policies = raw.policies.map((p) => {
2041
+ const entry = p;
2042
+ return { ...entry, version: entry.version ?? entry.revision };
2043
+ });
2044
+ return { schemaVersion: raw.schemaVersion, deployment, policies };
2045
+ }
2046
+ function resolveManagedPath(root, candidate) {
2047
+ if (!candidate || isAbsolute(candidate))
2048
+ throw new Error(`unsafe managed policy path ${JSON.stringify(candidate)}`);
2049
+ const absolute = resolve3(root, candidate);
2050
+ const lexicalRelative = relative(root, absolute);
2051
+ if (lexicalRelative.startsWith("..") || isAbsolute(lexicalRelative)) {
2052
+ throw new Error(`managed policy path escapes its root: ${JSON.stringify(candidate)}`);
2053
+ }
2054
+ const realRoot = realpathSync(root);
2055
+ const realFile = realpathSync(absolute);
2056
+ const physicalRelative = relative(realRoot, realFile);
2057
+ if (physicalRelative.startsWith("..") || isAbsolute(physicalRelative)) {
2058
+ throw new Error(`managed policy symlink escapes its root: ${JSON.stringify(candidate)}`);
2059
+ }
2060
+ return realFile;
2061
+ }
2062
+ function clearActiveCloudManagedPolicies() {
2063
+ if (process.env.FAILPROOFAI_CLOUD_POLICY_DIR !== undefined)
2064
+ return false;
2065
+ const root = cloudManagedPolicyRoot();
2066
+ let removed = false;
2067
+ for (const name of [DESIRED_STATE_FILE, CLOUD_POLICY_ERRORS_FILE, DAEMON_POLICY_ERRORS_FILE, JEV_BUDGET_FILE, "load-checked.json", "active.json"]) {
2068
+ const path = resolve3(root, name);
2069
+ if (!existsSync5(path))
2070
+ continue;
2071
+ try {
2072
+ rmSync2(path, { force: true });
2073
+ if (name === DESIRED_STATE_FILE || name === "active.json")
2074
+ removed = true;
2075
+ } catch {}
2076
+ }
2077
+ try {
2078
+ rmSync2(resolve3(root, "artifacts"), { recursive: true, force: true });
2079
+ } catch {}
2080
+ return removed;
2081
+ }
2082
+ function parseCloudJevMode(raw) {
2083
+ return raw === "off" || raw === "observe" || raw === "enforce" ? raw : null;
2084
+ }
2085
+ function cloudJevAsks(mode) {
2086
+ return mode === "observe" || mode === "enforce";
2087
+ }
2088
+ function fileVersion(path) {
2089
+ try {
2090
+ const s = statSync5(path, { bigint: true });
2091
+ return `${s.dev}:${s.ino}:${s.mode}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`;
2092
+ } catch (err) {
2093
+ const code = err.code;
2094
+ if (code === "ENOENT" || code === "ENOTDIR")
2095
+ return null;
2096
+ throw err;
2097
+ }
2098
+ }
2099
+ function readActiveJson() {
2100
+ if (disconnectedByConfig()) {
2101
+ activeJsonCache = null;
2102
+ return;
2103
+ }
2104
+ const path = resolve3(cloudManagedPolicyRoot(), "active.json");
2105
+ const version = fileVersion(path);
2106
+ if (version === null) {
2107
+ activeJsonCache = null;
2108
+ return;
2109
+ }
2110
+ if (activeJsonCache && activeJsonCache.path === path && activeJsonCache.version === version)
2111
+ return activeJsonCache.value;
2112
+ const value = JSON.parse(readFileSync3(path, "utf8"));
2113
+ activeJsonCache = { path, version, value };
2114
+ return value;
2115
+ }
2116
+ function readActiveRaw() {
2117
+ const raw = readActiveJson();
2118
+ if (raw === undefined)
2119
+ return null;
2120
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
2121
+ throw new Error("active manifest is not an object");
2122
+ const record = raw;
2123
+ if (!ACCEPTED_ACTIVE_SCHEMA_VERSIONS.includes(record.schemaVersion)) {
2124
+ throw new Error(`unsupported active manifest schema ${String(record.schemaVersion)}`);
2125
+ }
2126
+ return record;
2127
+ }
2128
+ function readCloudAgentScopeRequired() {
2129
+ try {
2130
+ return readActiveRaw()?.schemaVersion === 3;
2131
+ } catch {
2132
+ return false;
2133
+ }
2134
+ }
2135
+ function cloudDeploymentMayTargetAgents() {
2136
+ if (disconnectedByConfig())
2137
+ return false;
2138
+ let text;
2139
+ try {
2140
+ text = readFileSync3(resolve3(cloudManagedPolicyRoot(), "active.json"), "utf8");
2141
+ } catch (err) {
2142
+ return err.code !== "ENOENT";
2143
+ }
2144
+ try {
2145
+ const version = JSON.parse(text)?.schemaVersion;
2146
+ return !(typeof version === "number" && Number.isInteger(version) && version < 3);
2147
+ } catch {
2148
+ return true;
2149
+ }
2150
+ }
2151
+ function readCloudJevMode() {
2152
+ try {
2153
+ return parseCloudJevMode(readActiveRaw()?.jevMode);
2154
+ } catch {
2155
+ return null;
2156
+ }
2157
+ }
2158
+ function readCloudJevState() {
2159
+ let active;
2160
+ try {
2161
+ active = readActiveRaw();
2162
+ } catch {
2163
+ return noCloudJev();
2164
+ }
2165
+ if (!active)
2166
+ return noCloudJev();
2167
+ const rawMode = active.jevMode;
2168
+ const jevMode = parseCloudJevMode(rawMode);
2169
+ const errors = [];
2170
+ if (rawMode !== undefined && rawMode !== null && jevMode === null) {
2171
+ errors.push({ id: "jevMode", version: null, kind: "daemon", message: `unknown Jev mode ${JSON.stringify(rawMode)} ignored` });
2172
+ }
2173
+ const deployment = Number.isSafeInteger(active.deployment) ? active.deployment : null;
2174
+ return { jevMode, deployment, errors };
2175
+ }
2176
+ function readCloudJevAssignments() {
2177
+ try {
2178
+ const active = readActiveRaw();
2179
+ if (!active || !Array.isArray(active.jevPolicies))
2180
+ return null;
2181
+ const schema = active.schemaVersion;
2182
+ const out = [];
2183
+ for (const raw of active.jevPolicies) {
2184
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
2185
+ return null;
2186
+ const entry = raw;
2187
+ if (typeof entry.id !== "string" || !POLICY_ID_RE.test(entry.id))
2188
+ return null;
2189
+ if (!Number.isSafeInteger(entry.version) || entry.version < 0)
2190
+ return null;
2191
+ if (entry.effect !== undefined && entry.effect !== "enforce" && entry.effect !== "observe")
2192
+ return null;
2193
+ const targets = parseAgentTargets(entry.agentTargets, schema);
2194
+ out.push({
2195
+ id: entry.id,
2196
+ version: entry.version,
2197
+ effect: entry.effect === "observe" ? "observe" : "enforce",
2198
+ ...targets ? { agentTargets: targets } : {}
2199
+ });
2200
+ }
2201
+ return out;
2202
+ } catch {
2203
+ return null;
2204
+ }
2205
+ }
2206
+ function cloudJevAssignmentsFor(agent) {
2207
+ const all = readCloudJevAssignments();
2208
+ return all === null ? null : all.filter((a) => agentTargetsMatch(a.agentTargets, agent));
2209
+ }
2210
+ function cloudReviewerName(policyId, name) {
2211
+ return `cloud:${policyId}/${name}`;
2212
+ }
2213
+ function cloudAuthorityDeclaration(policy, mode) {
2214
+ if (policy.authority !== "reviewable")
2215
+ return policy.authority ? { authority: policy.authority } : {};
2216
+ if (policy.effect === "observe" || !cloudJevAsks(mode))
2217
+ return { authority: "hard" };
2218
+ return {
2219
+ authority: "reviewable",
2220
+ reviewedBy: (policy.reviewedBy ?? []).map((n) => CLOUD_REVIEWER_RE.test(n) ? n : cloudReviewerName(policy.id, n))
2221
+ };
2222
+ }
2223
+ function withCloudAuthority(policy, mode) {
2224
+ const { authority: _authority, reviewedBy: _reviewedBy, ...rest } = policy;
2225
+ return { ...rest, ...cloudAuthorityDeclaration(policy, mode) };
2226
+ }
2227
+ function cloudReviewerNames(policies, mode) {
2228
+ const out = [];
2229
+ for (const policy of policies) {
2230
+ const declared = cloudAuthorityDeclaration(policy, mode);
2231
+ if (declared.authority === "reviewable")
2232
+ out.push(...declared.reviewedBy ?? []);
2233
+ }
2234
+ return out;
2235
+ }
2236
+ function readCloudAuthorityInputs(agent = null) {
2237
+ try {
2238
+ const raw = readActiveJson();
2239
+ if (raw === undefined)
2240
+ return [];
2241
+ const manifest = parseManifest(raw);
2242
+ return manifest.policies.flatMap((policy) => {
2243
+ if (typeof policy.id !== "string")
2244
+ return [];
2245
+ const targets = parseAgentTargets(policy.agentTargets, manifest.schemaVersion);
2246
+ if (!agentTargetsMatch(targets, agent))
2247
+ return [];
2248
+ return [{
2249
+ id: policy.id,
2250
+ effect: policy.effect === "observe" ? "observe" : "enforce",
2251
+ ...targets ? { agentTargets: targets } : {},
2252
+ ...authorityFieldsOf(policy)
2253
+ }];
2254
+ });
2255
+ } catch {
2256
+ return [];
2257
+ }
2258
+ }
2259
+ function listActiveCloudManagedPolicies() {
2260
+ return readActiveCloudManagedPoliciesFor(() => true);
2261
+ }
2262
+ function readActiveCloudManagedPolicies(agent = null) {
2263
+ return readActiveCloudManagedPoliciesFor((targets) => agentTargetsMatch(targets, agent));
2264
+ }
2265
+ function readActiveCloudManagedPoliciesFor(applies) {
2266
+ const root = cloudManagedPolicyRoot();
2267
+ let raw;
2268
+ try {
2269
+ raw = readActiveJson();
2270
+ } catch (err) {
2271
+ throw new Error(`failed to read cloud-managed active manifest: ${err instanceof Error ? err.message : String(err)}`);
2272
+ }
2273
+ if (raw === undefined)
2274
+ return [];
2275
+ const manifest = parseManifest(raw);
2276
+ const applicable = manifest.policies.filter((policy) => applies(parseAgentTargets(policy.agentTargets, manifest.schemaVersion)));
2277
+ const seen = new Set;
2278
+ return applicable.map((policy) => {
2279
+ if (!POLICY_ID_RE.test(policy.id) || policy.id === "." || policy.id === "..") {
2280
+ throw new Error(`unsafe cloud-managed policy id ${JSON.stringify(policy.id)}`);
2281
+ }
2282
+ if (!Number.isSafeInteger(policy.version) || policy.version < 0) {
2283
+ throw new Error(`invalid version for cloud-managed policy ${policy.id}`);
2284
+ }
2285
+ if (!SHA256_RE.test(policy.sha256)) {
2286
+ throw new Error(`invalid SHA-256 for cloud-managed policy ${policy.id}`);
2287
+ }
2288
+ if (seen.has(policy.id))
2289
+ throw new Error(`duplicate cloud-managed policy id ${policy.id}`);
2290
+ seen.add(policy.id);
2291
+ const path = resolveManagedPath(root, policy.path);
2292
+ const bytes = readFileSync3(path);
2293
+ const actual = createHash("sha256").update(bytes).digest("hex");
2294
+ if (actual !== policy.sha256) {
2295
+ throw new Error(`cloud-managed policy ${policy.id} failed integrity verification: expected ${policy.sha256}, got ${actual}`);
2296
+ }
2297
+ if (policy.effect !== undefined && policy.effect !== "enforce" && policy.effect !== "observe") {
2298
+ throw new Error(`unknown effect ${JSON.stringify(policy.effect)} for cloud-managed policy ${policy.id}`);
2299
+ }
2300
+ return {
2301
+ id: policy.id,
2302
+ version: policy.version,
2303
+ effect: policy.effect ?? "enforce",
2304
+ sha256: policy.sha256,
2305
+ path,
2306
+ deployment: manifest.deployment,
2307
+ ...parseAgentTargets(policy.agentTargets, manifest.schemaVersion) ? { agentTargets: parseAgentTargets(policy.agentTargets, manifest.schemaVersion) } : {},
2308
+ ...authorityFieldsOf(policy)
2309
+ };
2310
+ });
2311
+ }
2312
+ var ACCEPTED_ACTIVE_SCHEMA_VERSIONS, SHA256_RE, POLICY_ID_RE, DESIRED_STATE_FILE = "desired-state.json", CLOUD_POLICY_ERRORS_FILE = "errors.json", DAEMON_POLICY_ERRORS_FILE = "daemon-errors.json", JEV_BUDGET_FILE = "jev-budget.json", noCloudJev = () => ({ jevMode: null, deployment: null, errors: [] }), activeJsonCache = null, CLOUD_REVIEWER_RE;
2313
+ var init_cloud_managed_policies = __esm(() => {
2314
+ init_fp_home();
2315
+ init_agent_targets();
2316
+ init_policy_authority();
2317
+ ACCEPTED_ACTIVE_SCHEMA_VERSIONS = [1, 2, 3];
2318
+ SHA256_RE = /^[a-f0-9]{64}$/;
2319
+ POLICY_ID_RE = /^[A-Za-z0-9._-]{1,128}$/;
2320
+ CLOUD_REVIEWER_RE = /^cloud:[^/]+\/./;
2321
+ });
2322
+
1782
2323
  // src/hooks/daemon-client.ts
1783
2324
  import { createConnection } from "node:net";
1784
2325
  function socketPath() {
@@ -1799,7 +2340,22 @@ function encodeFrame(value) {
1799
2340
  header.writeUInt32BE(body.length, 0);
1800
2341
  return Buffer.concat([header, body]);
1801
2342
  }
1802
- async function attemptDaemonRequest(request, opts) {
2343
+ async function attemptDaemonRequest(build, opts) {
2344
+ const first = await attemptDaemonRequestAt(PROTOCOL_VERSION, build, opts);
2345
+ const older = !first.ok ? first.daemonVersion : undefined;
2346
+ if (older === undefined || !Number.isInteger(older) || older < MIN_PROTOCOL_VERSION || older >= PROTOCOL_VERSION || cloudDeploymentMayTargetAgents()) {
2347
+ return withoutDaemonVersion(first);
2348
+ }
2349
+ const retried = await attemptDaemonRequestAt(older, build, opts);
2350
+ if (cloudDeploymentMayTargetAgents())
2351
+ return withoutDaemonVersion(first);
2352
+ return withoutDaemonVersion(retried);
2353
+ }
2354
+ function withoutDaemonVersion(attempt) {
2355
+ return attempt.ok ? attempt : { ok: false, failure: attempt.failure };
2356
+ }
2357
+ async function attemptDaemonRequestAt(protocolVersion, build, opts) {
2358
+ const request = build(protocolVersion);
1803
2359
  if (process.platform === "win32")
1804
2360
  return { ok: false, failure: "unreachable" };
1805
2361
  const responseBudget = opts?.responseTimeoutMs ?? DAEMON_RESPONSE_TIMEOUT_MS;
@@ -1856,8 +2412,9 @@ async function attemptDaemonRequest(request, opts) {
1856
2412
  return;
1857
2413
  }
1858
2414
  const message = parsed;
1859
- if (message.protocolVersion !== PROTOCOL_VERSION) {
1860
- fail("protocol-mismatch");
2415
+ if (message.protocolVersion !== protocolVersion) {
2416
+ const daemonVersion = typeof message.protocolVersion === "number" ? message.protocolVersion : undefined;
2417
+ finish({ ok: false, failure: "protocol-mismatch", daemonVersion });
1861
2418
  return;
1862
2419
  }
1863
2420
  finish({ ok: true, message });
@@ -1866,16 +2423,19 @@ async function attemptDaemonRequest(request, opts) {
1866
2423
  socket.on("close", () => fail("unreachable"));
1867
2424
  });
1868
2425
  }
2426
+ function settingsPathFor(protocolVersion, agentSettingsPath) {
2427
+ return protocolVersion >= AGENT_SETTINGS_PATH_SINCE ? { agentSettingsPath } : {};
2428
+ }
1869
2429
  async function attemptDaemonHook(req, opts) {
1870
- const attempt = await attemptDaemonRequest({
2430
+ const attempt = await attemptDaemonRequest((protocolVersion) => ({
1871
2431
  type: "hook",
1872
- protocolVersion: PROTOCOL_VERSION,
2432
+ protocolVersion,
1873
2433
  hookEvent: req.hookEvent,
1874
2434
  cli: req.cli,
1875
2435
  stdin: req.stdin,
1876
2436
  cwd: req.cwd,
1877
- agentSettingsPath: req.agentSettingsPath
1878
- }, opts);
2437
+ ...settingsPathFor(protocolVersion, req.agentSettingsPath)
2438
+ }), opts);
1879
2439
  if (!attempt.ok)
1880
2440
  return attempt;
1881
2441
  const message = attempt.message;
@@ -1891,10 +2451,11 @@ async function attemptDaemonHook(req, opts) {
1891
2451
  }
1892
2452
  return { ok: false, failure: "unreachable" };
1893
2453
  }
1894
- var PROTOCOL_VERSION = 2, DAEMON_CONNECT_TIMEOUT_MS = 150, DAEMON_RESPONSE_TIMEOUT_MS = 30000, MAX_FRAME_LEN;
2454
+ var PROTOCOL_VERSION = 2, MIN_PROTOCOL_VERSION = 1, AGENT_SETTINGS_PATH_SINCE = 2, DAEMON_CONNECT_TIMEOUT_MS = 150, DAEMON_RESPONSE_TIMEOUT_MS = 30000, MAX_FRAME_LEN;
1895
2455
  var init_daemon_client = __esm(() => {
1896
2456
  init_fp_home();
1897
2457
  init_fp_config();
2458
+ init_cloud_managed_policies();
1898
2459
  MAX_FRAME_LEN = 16 * 1024 * 1024;
1899
2460
  });
1900
2461
 
@@ -2041,105 +2602,18 @@ function normalizeCliPayload(cli, parsed) {
2041
2602
  }
2042
2603
  }
2043
2604
 
2044
- // src/hooks/hook-logger.ts
2045
- import {
2046
- appendFileSync,
2047
- renameSync as renameSync2,
2048
- mkdirSync as mkdirSync3,
2049
- existsSync as existsSync3,
2050
- statSync as statSync4
2051
- } from "node:fs";
2052
- import { join } from "node:path";
2053
- function ensureResolved() {
2054
- if (resolved)
2055
- return;
2056
- resolved = true;
2057
- const rawLevel = (process.env.FAILPROOFAI_LOG_LEVEL ?? "").toLowerCase();
2058
- if (rawLevel === "info" || rawLevel === "warn" || rawLevel === "error") {
2059
- currentLevel = rawLevel;
2060
- }
2061
- const rawFile = (process.env.FAILPROOFAI_HOOK_LOG_FILE ?? "").trim();
2062
- if (rawFile) {
2063
- fileLoggingEnabled = true;
2064
- if (rawFile !== "1" && rawFile !== "true") {
2065
- logDir = rawFile;
2066
- }
2067
- }
2068
- }
2069
- function shouldEmit(level) {
2070
- ensureResolved();
2071
- return LEVEL_ORDER[level] >= LEVEL_ORDER[currentLevel];
2072
- }
2073
- function emitStderr(label, msg) {
2074
- process.stderr.write(`[failproofai:hook] ${label} ${msg}
2075
- `);
2076
- }
2077
- function ensureLogDir() {
2078
- if (!existsSync3(logDir)) {
2079
- mkdirSync3(logDir, { recursive: true });
2080
- }
2081
- }
2082
- function rotateIfNeeded(filePath) {
2083
- try {
2084
- const stats = statSync4(filePath);
2085
- if (stats.size >= MAX_FILE_SIZE) {
2086
- const archiveName = `hooks-${Date.now()}.log`;
2087
- renameSync2(filePath, join(logDir, archiveName));
2088
- }
2089
- } catch {}
2090
- }
2091
- function appendToFile(label, msg) {
2092
- if (!fileLoggingEnabled)
2093
- return;
2094
- try {
2095
- ensureLogDir();
2096
- const filePath = join(logDir, LOG_FILENAME);
2097
- rotateIfNeeded(filePath);
2098
- const timestamp = new Date().toISOString();
2099
- const line = `[${timestamp}] ${label} ${msg}
2100
- `;
2101
- appendFileSync(filePath, line, "utf-8");
2102
- } catch {}
2103
- }
2104
- function hookLogInfo(msg) {
2105
- if (!shouldEmit("info"))
2106
- return;
2107
- emitStderr("INFO", msg);
2108
- appendToFile("INFO", msg);
2109
- }
2110
- function hookLogWarn(msg) {
2111
- if (!shouldEmit("warn"))
2112
- return;
2113
- emitStderr("WARN", msg);
2114
- appendToFile("WARN", msg);
2115
- }
2116
- function hookLogError(msg) {
2117
- if (!shouldEmit("error"))
2118
- return;
2119
- emitStderr("ERROR", msg);
2120
- appendToFile("ERROR", msg);
2121
- }
2122
- var LEVEL_ORDER, MAX_FILE_SIZE, LOG_FILENAME = "hooks.log", DEFAULT_LOG_DIR, resolved = false, currentLevel = "warn", fileLoggingEnabled = false, logDir;
2123
- var init_hook_logger = __esm(() => {
2124
- init_fp_home();
2125
- LEVEL_ORDER = { info: 0, warn: 1, error: 2 };
2126
- MAX_FILE_SIZE = 512 * 1024;
2127
- DEFAULT_LOG_DIR = logsDir();
2128
- logDir = DEFAULT_LOG_DIR;
2129
- });
2130
-
2131
2605
  // src/hooks/hooks-config.ts
2132
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, statSync as statSync5 } from "node:fs";
2133
- import { resolve as resolve3, dirname as dirname4 } from "node:path";
2606
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, existsSync as existsSync6, mkdirSync as mkdirSync4, statSync as statSync6 } from "node:fs";
2607
+ import { resolve as resolve4, dirname as dirname4 } from "node:path";
2134
2608
  import { homedir as homedir3 } from "node:os";
2135
2609
  function configuredCustomPolicyPaths(config) {
2136
2610
  return config.customPoliciesPaths ?? (config.customPoliciesPath ? [config.customPoliciesPath] : []);
2137
2611
  }
2138
2612
  function readConfigAt(path) {
2139
- if (!existsSync4(path))
2613
+ if (!existsSync6(path))
2140
2614
  return {};
2141
2615
  try {
2142
- const raw = readFileSync3(path, "utf8");
2616
+ const raw = readFileSync4(path, "utf8");
2143
2617
  return JSON.parse(raw);
2144
2618
  } catch (err) {
2145
2619
  hookLogWarn(`failed to parse config at ${path}: ${err instanceof Error ? err.message : String(err)}`);
@@ -2148,11 +2622,11 @@ function readConfigAt(path) {
2148
2622
  }
2149
2623
  function findProjectConfigDir(start) {
2150
2624
  const home = homedir3();
2151
- let dir = resolve3(start);
2625
+ let dir = resolve4(start);
2152
2626
  while (dir !== home) {
2153
- const marker = resolve3(dir, ".failproofai");
2627
+ const marker = resolve4(dir, ".failproofai");
2154
2628
  try {
2155
- if (statSync5(marker).isDirectory())
2629
+ if (statSync6(marker).isDirectory())
2156
2630
  return dir;
2157
2631
  } catch {}
2158
2632
  const parent = dirname4(dir);
@@ -2160,12 +2634,12 @@ function findProjectConfigDir(start) {
2160
2634
  break;
2161
2635
  dir = parent;
2162
2636
  }
2163
- return resolve3(start);
2637
+ return resolve4(start);
2164
2638
  }
2165
2639
  function readMergedHooksConfig(cwd) {
2166
2640
  const base = findProjectConfigDir(cwd ?? process.cwd());
2167
- const projectPath = resolve3(base, ".failproofai", "policies-config.json");
2168
- const localPath = resolve3(base, ".failproofai", "policies-config.local.json");
2641
+ const projectPath = resolve4(base, ".failproofai", "policies-config.json");
2642
+ const localPath = resolve4(base, ".failproofai", "policies-config.local.json");
2169
2643
  const globalPath = globalPolicyConfigFile();
2170
2644
  const project = readConfigAt(projectPath);
2171
2645
  const local = readConfigAt(localPath);
@@ -2207,18 +2681,18 @@ function getConfigPathForScope(scope, cwd) {
2207
2681
  case "user":
2208
2682
  return globalPolicyConfigFile();
2209
2683
  case "project":
2210
- return resolve3(findProjectConfigDir(cwd ?? process.cwd()), ".failproofai", "policies-config.json");
2684
+ return resolve4(findProjectConfigDir(cwd ?? process.cwd()), ".failproofai", "policies-config.json");
2211
2685
  case "local":
2212
- return resolve3(findProjectConfigDir(cwd ?? process.cwd()), ".failproofai", "policies-config.local.json");
2686
+ return resolve4(findProjectConfigDir(cwd ?? process.cwd()), ".failproofai", "policies-config.local.json");
2213
2687
  }
2214
2688
  }
2215
2689
  function readScopedHooksConfig(scope, cwd) {
2216
2690
  const configPath = getConfigPathForScope(scope, cwd);
2217
- if (!existsSync4(configPath)) {
2691
+ if (!existsSync6(configPath)) {
2218
2692
  return { enabledPolicies: [] };
2219
2693
  }
2220
2694
  try {
2221
- const raw = readFileSync3(configPath, "utf8");
2695
+ const raw = readFileSync4(configPath, "utf8");
2222
2696
  return JSON.parse(raw);
2223
2697
  } catch (err) {
2224
2698
  hookLogWarn(`failed to parse config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
@@ -2228,7 +2702,7 @@ function readScopedHooksConfig(scope, cwd) {
2228
2702
  function writeScopedHooksConfig(config, scope, cwd) {
2229
2703
  const configPath = getConfigPathForScope(scope, cwd);
2230
2704
  const dir = dirname4(configPath);
2231
- if (!existsSync4(dir)) {
2705
+ if (!existsSync6(dir)) {
2232
2706
  mkdirSync4(dir, { recursive: true });
2233
2707
  }
2234
2708
  writeFileSync3(configPath, JSON.stringify(config, null, 2) + `
@@ -2236,11 +2710,11 @@ function writeScopedHooksConfig(config, scope, cwd) {
2236
2710
  }
2237
2711
  function syncConventionPolicies(entries, scope, cwd) {
2238
2712
  const configPath = getConfigPathForScope(scope, cwd);
2239
- if (!existsSync4(configPath) && entries.length === 0)
2713
+ if (!existsSync6(configPath) && entries.length === 0)
2240
2714
  return false;
2241
- if (existsSync4(configPath)) {
2715
+ if (existsSync6(configPath)) {
2242
2716
  try {
2243
- JSON.parse(readFileSync3(configPath, "utf8"));
2717
+ JSON.parse(readFileSync4(configPath, "utf8"));
2244
2718
  } catch {
2245
2719
  hookLogWarn(`not recording convention policies: ${configPath} is not valid JSON — ` + `fix the syntax error and re-run. Nothing was written.`);
2246
2720
  return false;
@@ -2851,443 +3325,6 @@ function instruct(reason) {
2851
3325
  return { decision: "instruct", reason };
2852
3326
  }
2853
3327
 
2854
- // src/hooks/policy-types.ts
2855
- function effectiveAuthority(p) {
2856
- if (p.alwaysOn === true)
2857
- return "hard";
2858
- if (p.authority !== "reviewable")
2859
- return "hard";
2860
- if (!Array.isArray(p.reviewedBy))
2861
- return "hard";
2862
- const named = p.reviewedBy.filter((n) => typeof n === "string" && n.length > 0);
2863
- return named.length > 0 ? "reviewable" : "hard";
2864
- }
2865
-
2866
- // src/hooks/policy-authority.ts
2867
- import { existsSync as existsSync5 } from "node:fs";
2868
- function resolvePolicyAuthority(decl, knownReviewers = NO_REVIEWERS, contested) {
2869
- const declaredReviewable = decl?.authority === "reviewable";
2870
- if (!decl || effectiveAuthority(decl) === "hard") {
2871
- if (!declaredReviewable)
2872
- return { authority: "hard" };
2873
- return { authority: "hard", downgraded: whyHard(decl) };
2874
- }
2875
- const names = decl.reviewedBy;
2876
- if (!names.every(isName)) {
2877
- return { authority: "hard", downgraded: "reviewedBy is not a list of semantic policy names" };
2878
- }
2879
- const unknown = names.filter((n) => !knownReviewers.has(n));
2880
- if (knownReviewers.size === 0 && !unknown.some((n) => contested?.has(n)))
2881
- return { authority: "hard" };
2882
- if (unknown.length > 0) {
2883
- return { authority: "hard", downgraded: `reviewedBy names ${unknown.map((n) => whyUnknown(n, knownReviewers, contested)).join("; ")}` };
2884
- }
2885
- return { authority: "reviewable", reviewedBy: [...new Set(names)] };
2886
- }
2887
- function whyUnknown(name, known, contested) {
2888
- const quoted = JSON.stringify(name);
2889
- const claimants = contested?.get(name);
2890
- if (claimants)
2891
- return `${quoted}, which packs ${claimants.join(" and ")} declare differently, so it is asked for neither`;
2892
- if (known === SEMANTIC_REVIEWER_NAMES)
2893
- return `${quoted}, which is not a semantic policy in this build`;
2894
- const sorted = [...known].sort();
2895
- const listed = sorted.length > 6 ? `${sorted.slice(0, 6).join(", ")} and ${sorted.length - 6} more` : sorted.join(", ");
2896
- return `${quoted}, which is not among the Jev checks it is judged against (${listed})`;
2897
- }
2898
- function whyHard(decl) {
2899
- if (decl.alwaysOn === true)
2900
- return "it is alwaysOn, and the self-protection guard is never reviewable";
2901
- if (!Array.isArray(decl.reviewedBy) || decl.reviewedBy.length === 0) {
2902
- return "reviewedBy does not name any semantic policy";
2903
- }
2904
- return "reviewedBy is not a list of semantic policy names";
2905
- }
2906
- function authorityFieldsOf(raw) {
2907
- const out = {};
2908
- if (raw.authority === "hard" || raw.authority === "reviewable")
2909
- out.authority = raw.authority;
2910
- const list = raw.reviewedBy;
2911
- if (Array.isArray(list) && list.length > 0 && list.every(isName)) {
2912
- out.reviewedBy = [...list];
2913
- }
2914
- return out;
2915
- }
2916
- function authorityProblem(decl, knownReviewers = SEMANTIC_REVIEWER_NAMES) {
2917
- if (decl.authority !== undefined && decl.authority !== "hard" && decl.authority !== "reviewable") {
2918
- const t = typeof decl.authority;
2919
- return `authority must be "hard" or "reviewable", and is ${t === "string" ? JSON.stringify(decl.authority) : `${/^[aeiou]/.test(t) ? "an" : "a"} ${t}`}`;
2920
- }
2921
- if (decl.reviewedBy !== undefined && !(Array.isArray(decl.reviewedBy) && decl.reviewedBy.every(isName))) {
2922
- return "reviewedBy must be a list of semantic policy names";
2923
- }
2924
- const { downgraded } = resolvePolicyAuthority(decl, knownReviewers);
2925
- return downgraded ? `authority "reviewable" was refused — ${downgraded}` : undefined;
2926
- }
2927
- function withMergedAuthority(record, declarations, knownReviewers = NO_REVIEWERS) {
2928
- const resolved = declarations.map((d) => resolvePolicyAuthority(d, knownReviewers));
2929
- const allReviewable = resolved.length > 0 && resolved.every((r) => r.authority === "reviewable");
2930
- const decided = declarations[resolved.findIndex((r) => r.authority !== "reviewable")] ?? {};
2931
- const fields = allReviewable ? { authority: "reviewable", reviewedBy: [...new Set(resolved.flatMap((r) => r.reviewedBy ?? []))] } : decided.authority === undefined ? {} : { authority: "hard" };
2932
- const overruled = !allReviewable && resolved.some((r) => r.authority === "reviewable");
2933
- const refused = resolved.find((r) => r.downgraded !== undefined)?.downgraded;
2934
- const extra = refused === undefined ? {} : { refused };
2935
- const same = record.authority === fields.authority && JSON.stringify(record.reviewedBy) === JSON.stringify(fields.reviewedBy);
2936
- if (same)
2937
- return { merged: record, overruled, ...extra };
2938
- const { authority: _a, reviewedBy: _r, ...rest } = record;
2939
- return { merged: { ...rest, ...fields }, overruled, ...extra };
2940
- }
2941
- function refusedAuthorityWarning(subject, reason) {
2942
- return `${subject} asks to be reviewable, but ${reason} — it stays hard`;
2943
- }
2944
- function warnAuthority(message) {
2945
- try {
2946
- if (!existsSync5(jevConfigFile()))
2947
- return;
2948
- } catch {
2949
- return;
2950
- }
2951
- if (warnedAuthority.has(message))
2952
- return;
2953
- warnedAuthority.add(message);
2954
- hookLogWarn(message);
2955
- }
2956
- function authorityDeclarationFor(hook, source) {
2957
- if (source.cloudManaged) {
2958
- return { authority: source.cloudManaged.authority, reviewedBy: source.cloudManaged.reviewedBy };
2959
- }
2960
- if (source.pack) {
2961
- const entry = source.pack.policies.find((p) => p.name === hook.name);
2962
- return { authority: entry?.authority, reviewedBy: entry?.reviewedBy };
2963
- }
2964
- return { authority: hook.authority, reviewedBy: hook.reviewedBy };
2965
- }
2966
- var SEMANTIC_POLICY_NAMES, SEMANTIC_REVIEWER_NAMES, NO_REVIEWERS, isName = (n) => typeof n === "string" && n.length > 0, warnedAuthority;
2967
- var init_policy_authority = __esm(() => {
2968
- init_fp_home();
2969
- init_hook_logger();
2970
- SEMANTIC_POLICY_NAMES = [
2971
- "destructive-deletion",
2972
- "production-infra-change",
2973
- "git-history-rewrite",
2974
- "push-to-protected-branch",
2975
- "commit-on-protected-branch",
2976
- "secret-exposure",
2977
- "credential-exfiltration",
2978
- "remote-code-execution",
2979
- "privilege-escalation",
2980
- "database-destruction",
2981
- "read-outside-workspace",
2982
- "agent-config-tampering",
2983
- "system-modification",
2984
- "env-secrets-dump",
2985
- "external-destructive-action",
2986
- "external-data-egress"
2987
- ];
2988
- SEMANTIC_REVIEWER_NAMES = new Set(SEMANTIC_POLICY_NAMES);
2989
- NO_REVIEWERS = new Set;
2990
- warnedAuthority = new Set;
2991
- });
2992
-
2993
- // src/hooks/cloud-managed-policies.ts
2994
- import { createHash } from "node:crypto";
2995
- import { existsSync as existsSync6, readFileSync as readFileSync4, realpathSync, rmSync as rmSync2, statSync as statSync6 } from "node:fs";
2996
- import { isAbsolute, relative, resolve as resolve4 } from "node:path";
2997
- function cloudManagedPolicyRoot() {
2998
- return process.env.FAILPROOFAI_CLOUD_POLICY_DIR ?? cloudPoliciesDir();
2999
- }
3000
- function disconnectedByConfig() {
3001
- try {
3002
- const raw = JSON.parse(readFileSync4(configFile(), "utf8"));
3003
- if (!raw || typeof raw !== "object" || Array.isArray(raw))
3004
- return false;
3005
- const mode = raw.mode;
3006
- return !!mode && typeof mode === "object" && !Array.isArray(mode) && mode.kind === "oss";
3007
- } catch {
3008
- return false;
3009
- }
3010
- }
3011
- function parseManifest(value) {
3012
- if (!value || typeof value !== "object")
3013
- throw new Error("active manifest is not an object");
3014
- const raw = value;
3015
- if (!ACCEPTED_ACTIVE_SCHEMA_VERSIONS.includes(raw.schemaVersion)) {
3016
- throw new Error(`unsupported active manifest schema ${String(raw.schemaVersion)} ` + `(supported: ${ACCEPTED_ACTIVE_SCHEMA_VERSIONS.join(", ")})`);
3017
- }
3018
- const deployment = raw.deployment ?? raw.generation;
3019
- if (!Number.isSafeInteger(deployment) || (deployment ?? -1) < 0) {
3020
- throw new Error("active manifest deployment is invalid");
3021
- }
3022
- if (!Array.isArray(raw.policies))
3023
- throw new Error("active manifest policies is not an array");
3024
- const policies = raw.policies.map((p) => {
3025
- const entry = p;
3026
- return { ...entry, version: entry.version ?? entry.revision };
3027
- });
3028
- return { schemaVersion: raw.schemaVersion, deployment, policies };
3029
- }
3030
- function resolveManagedPath(root, candidate) {
3031
- if (!candidate || isAbsolute(candidate))
3032
- throw new Error(`unsafe managed policy path ${JSON.stringify(candidate)}`);
3033
- const absolute = resolve4(root, candidate);
3034
- const lexicalRelative = relative(root, absolute);
3035
- if (lexicalRelative.startsWith("..") || isAbsolute(lexicalRelative)) {
3036
- throw new Error(`managed policy path escapes its root: ${JSON.stringify(candidate)}`);
3037
- }
3038
- const realRoot = realpathSync(root);
3039
- const realFile = realpathSync(absolute);
3040
- const physicalRelative = relative(realRoot, realFile);
3041
- if (physicalRelative.startsWith("..") || isAbsolute(physicalRelative)) {
3042
- throw new Error(`managed policy symlink escapes its root: ${JSON.stringify(candidate)}`);
3043
- }
3044
- return realFile;
3045
- }
3046
- function clearActiveCloudManagedPolicies() {
3047
- if (process.env.FAILPROOFAI_CLOUD_POLICY_DIR !== undefined)
3048
- return false;
3049
- const root = cloudManagedPolicyRoot();
3050
- let removed = false;
3051
- for (const name of [DESIRED_STATE_FILE, CLOUD_POLICY_ERRORS_FILE, DAEMON_POLICY_ERRORS_FILE, JEV_BUDGET_FILE, "load-checked.json", "active.json"]) {
3052
- const path = resolve4(root, name);
3053
- if (!existsSync6(path))
3054
- continue;
3055
- try {
3056
- rmSync2(path, { force: true });
3057
- if (name === DESIRED_STATE_FILE || name === "active.json")
3058
- removed = true;
3059
- } catch {}
3060
- }
3061
- try {
3062
- rmSync2(resolve4(root, "artifacts"), { recursive: true, force: true });
3063
- } catch {}
3064
- return removed;
3065
- }
3066
- function parseCloudJevMode(raw) {
3067
- return raw === "off" || raw === "observe" || raw === "enforce" ? raw : null;
3068
- }
3069
- function cloudJevAsks(mode) {
3070
- return mode === "observe" || mode === "enforce";
3071
- }
3072
- function fileVersion(path) {
3073
- try {
3074
- const s = statSync6(path, { bigint: true });
3075
- return `${s.dev}:${s.ino}:${s.mode}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`;
3076
- } catch (err) {
3077
- const code = err.code;
3078
- if (code === "ENOENT" || code === "ENOTDIR")
3079
- return null;
3080
- throw err;
3081
- }
3082
- }
3083
- function readActiveJson() {
3084
- if (disconnectedByConfig()) {
3085
- activeJsonCache = null;
3086
- return;
3087
- }
3088
- const path = resolve4(cloudManagedPolicyRoot(), "active.json");
3089
- const version = fileVersion(path);
3090
- if (version === null) {
3091
- activeJsonCache = null;
3092
- return;
3093
- }
3094
- if (activeJsonCache && activeJsonCache.path === path && activeJsonCache.version === version)
3095
- return activeJsonCache.value;
3096
- const value = JSON.parse(readFileSync4(path, "utf8"));
3097
- activeJsonCache = { path, version, value };
3098
- return value;
3099
- }
3100
- function readActiveRaw() {
3101
- const raw = readActiveJson();
3102
- if (raw === undefined)
3103
- return null;
3104
- if (!raw || typeof raw !== "object" || Array.isArray(raw))
3105
- throw new Error("active manifest is not an object");
3106
- const record = raw;
3107
- if (!ACCEPTED_ACTIVE_SCHEMA_VERSIONS.includes(record.schemaVersion)) {
3108
- throw new Error(`unsupported active manifest schema ${String(record.schemaVersion)}`);
3109
- }
3110
- return record;
3111
- }
3112
- function readCloudAgentScopeRequired() {
3113
- try {
3114
- return readActiveRaw()?.schemaVersion === 3;
3115
- } catch {
3116
- return false;
3117
- }
3118
- }
3119
- function readCloudJevMode() {
3120
- try {
3121
- return parseCloudJevMode(readActiveRaw()?.jevMode);
3122
- } catch {
3123
- return null;
3124
- }
3125
- }
3126
- function readCloudJevState() {
3127
- let active;
3128
- try {
3129
- active = readActiveRaw();
3130
- } catch {
3131
- return noCloudJev();
3132
- }
3133
- if (!active)
3134
- return noCloudJev();
3135
- const rawMode = active.jevMode;
3136
- const jevMode = parseCloudJevMode(rawMode);
3137
- const errors = [];
3138
- if (rawMode !== undefined && rawMode !== null && jevMode === null) {
3139
- errors.push({ id: "jevMode", version: null, kind: "daemon", message: `unknown Jev mode ${JSON.stringify(rawMode)} ignored` });
3140
- }
3141
- const deployment = Number.isSafeInteger(active.deployment) ? active.deployment : null;
3142
- return { jevMode, deployment, errors };
3143
- }
3144
- function readCloudJevAssignments() {
3145
- try {
3146
- const active = readActiveRaw();
3147
- if (!active || !Array.isArray(active.jevPolicies))
3148
- return null;
3149
- const schema = active.schemaVersion;
3150
- const out = [];
3151
- for (const raw of active.jevPolicies) {
3152
- if (!raw || typeof raw !== "object" || Array.isArray(raw))
3153
- return null;
3154
- const entry = raw;
3155
- if (typeof entry.id !== "string" || !POLICY_ID_RE.test(entry.id))
3156
- return null;
3157
- if (!Number.isSafeInteger(entry.version) || entry.version < 0)
3158
- return null;
3159
- if (entry.effect !== undefined && entry.effect !== "enforce" && entry.effect !== "observe")
3160
- return null;
3161
- const targets = parseAgentTargets(entry.agentTargets, schema);
3162
- out.push({
3163
- id: entry.id,
3164
- version: entry.version,
3165
- effect: entry.effect === "observe" ? "observe" : "enforce",
3166
- ...targets ? { agentTargets: targets } : {}
3167
- });
3168
- }
3169
- return out;
3170
- } catch {
3171
- return null;
3172
- }
3173
- }
3174
- function cloudJevAssignmentsFor(agent) {
3175
- const all = readCloudJevAssignments();
3176
- return all === null ? null : all.filter((a) => agentTargetsMatch(a.agentTargets, agent));
3177
- }
3178
- function cloudReviewerName(policyId, name) {
3179
- return `cloud:${policyId}/${name}`;
3180
- }
3181
- function cloudAuthorityDeclaration(policy, mode) {
3182
- if (policy.authority !== "reviewable")
3183
- return policy.authority ? { authority: policy.authority } : {};
3184
- if (policy.effect === "observe" || !cloudJevAsks(mode))
3185
- return { authority: "hard" };
3186
- return {
3187
- authority: "reviewable",
3188
- reviewedBy: (policy.reviewedBy ?? []).map((n) => CLOUD_REVIEWER_RE.test(n) ? n : cloudReviewerName(policy.id, n))
3189
- };
3190
- }
3191
- function withCloudAuthority(policy, mode) {
3192
- const { authority: _authority, reviewedBy: _reviewedBy, ...rest } = policy;
3193
- return { ...rest, ...cloudAuthorityDeclaration(policy, mode) };
3194
- }
3195
- function cloudReviewerNames(policies, mode) {
3196
- const out = [];
3197
- for (const policy of policies) {
3198
- const declared = cloudAuthorityDeclaration(policy, mode);
3199
- if (declared.authority === "reviewable")
3200
- out.push(...declared.reviewedBy ?? []);
3201
- }
3202
- return out;
3203
- }
3204
- function readCloudAuthorityInputs(agent = null) {
3205
- try {
3206
- const raw = readActiveJson();
3207
- if (raw === undefined)
3208
- return [];
3209
- const manifest = parseManifest(raw);
3210
- return manifest.policies.flatMap((policy) => {
3211
- if (typeof policy.id !== "string")
3212
- return [];
3213
- const targets = parseAgentTargets(policy.agentTargets, manifest.schemaVersion);
3214
- if (!agentTargetsMatch(targets, agent))
3215
- return [];
3216
- return [{
3217
- id: policy.id,
3218
- effect: policy.effect === "observe" ? "observe" : "enforce",
3219
- ...targets ? { agentTargets: targets } : {},
3220
- ...authorityFieldsOf(policy)
3221
- }];
3222
- });
3223
- } catch {
3224
- return [];
3225
- }
3226
- }
3227
- function listActiveCloudManagedPolicies() {
3228
- return readActiveCloudManagedPoliciesFor(() => true);
3229
- }
3230
- function readActiveCloudManagedPolicies(agent = null) {
3231
- return readActiveCloudManagedPoliciesFor((targets) => agentTargetsMatch(targets, agent));
3232
- }
3233
- function readActiveCloudManagedPoliciesFor(applies) {
3234
- const root = cloudManagedPolicyRoot();
3235
- let raw;
3236
- try {
3237
- raw = readActiveJson();
3238
- } catch (err) {
3239
- throw new Error(`failed to read cloud-managed active manifest: ${err instanceof Error ? err.message : String(err)}`);
3240
- }
3241
- if (raw === undefined)
3242
- return [];
3243
- const manifest = parseManifest(raw);
3244
- const applicable = manifest.policies.filter((policy) => applies(parseAgentTargets(policy.agentTargets, manifest.schemaVersion)));
3245
- const seen = new Set;
3246
- return applicable.map((policy) => {
3247
- if (!POLICY_ID_RE.test(policy.id) || policy.id === "." || policy.id === "..") {
3248
- throw new Error(`unsafe cloud-managed policy id ${JSON.stringify(policy.id)}`);
3249
- }
3250
- if (!Number.isSafeInteger(policy.version) || policy.version < 0) {
3251
- throw new Error(`invalid version for cloud-managed policy ${policy.id}`);
3252
- }
3253
- if (!SHA256_RE.test(policy.sha256)) {
3254
- throw new Error(`invalid SHA-256 for cloud-managed policy ${policy.id}`);
3255
- }
3256
- if (seen.has(policy.id))
3257
- throw new Error(`duplicate cloud-managed policy id ${policy.id}`);
3258
- seen.add(policy.id);
3259
- const path = resolveManagedPath(root, policy.path);
3260
- const bytes = readFileSync4(path);
3261
- const actual = createHash("sha256").update(bytes).digest("hex");
3262
- if (actual !== policy.sha256) {
3263
- throw new Error(`cloud-managed policy ${policy.id} failed integrity verification: expected ${policy.sha256}, got ${actual}`);
3264
- }
3265
- if (policy.effect !== undefined && policy.effect !== "enforce" && policy.effect !== "observe") {
3266
- throw new Error(`unknown effect ${JSON.stringify(policy.effect)} for cloud-managed policy ${policy.id}`);
3267
- }
3268
- return {
3269
- id: policy.id,
3270
- version: policy.version,
3271
- effect: policy.effect ?? "enforce",
3272
- sha256: policy.sha256,
3273
- path,
3274
- deployment: manifest.deployment,
3275
- ...parseAgentTargets(policy.agentTargets, manifest.schemaVersion) ? { agentTargets: parseAgentTargets(policy.agentTargets, manifest.schemaVersion) } : {},
3276
- ...authorityFieldsOf(policy)
3277
- };
3278
- });
3279
- }
3280
- var ACCEPTED_ACTIVE_SCHEMA_VERSIONS, SHA256_RE, POLICY_ID_RE, DESIRED_STATE_FILE = "desired-state.json", CLOUD_POLICY_ERRORS_FILE = "errors.json", DAEMON_POLICY_ERRORS_FILE = "daemon-errors.json", JEV_BUDGET_FILE = "jev-budget.json", noCloudJev = () => ({ jevMode: null, deployment: null, errors: [] }), activeJsonCache = null, CLOUD_REVIEWER_RE;
3281
- var init_cloud_managed_policies = __esm(() => {
3282
- init_fp_home();
3283
- init_agent_targets();
3284
- init_policy_authority();
3285
- ACCEPTED_ACTIVE_SCHEMA_VERSIONS = [1, 2, 3];
3286
- SHA256_RE = /^[a-f0-9]{64}$/;
3287
- POLICY_ID_RE = /^[A-Za-z0-9._-]{1,128}$/;
3288
- CLOUD_REVIEWER_RE = /^cloud:[^/]+\/./;
3289
- });
3290
-
3291
3328
  // src/hooks/semver-precedence.ts
3292
3329
  function parseSemver(value) {
3293
3330
  if (typeof value !== "string")
@@ -13349,6 +13386,17 @@ var init_daemon_download = __esm(() => {
13349
13386
  function shellQuote(value) {
13350
13387
  return `'${value.replace(/'/g, `'\\''`)}'`;
13351
13388
  }
13389
+ function shellQuotedWords(command) {
13390
+ const words = [];
13391
+ const re = /\s*'((?:[^']|'\\'')*)'(?=\s|$)/y;
13392
+ let end = 0;
13393
+ let match;
13394
+ while (end < command.length && (match = re.exec(command))) {
13395
+ words.push(match[1].replace(/'\\''/g, "'"));
13396
+ end = re.lastIndex;
13397
+ }
13398
+ return words.length > 0 && command.slice(end).trim() === "" ? words : null;
13399
+ }
13352
13400
 
13353
13401
  // src/hooks/daemon-client.ts
13354
13402
  import { createConnection as createConnection2 } from "node:net";
@@ -13399,7 +13447,22 @@ function encodeFrame2(value) {
13399
13447
  header.writeUInt32BE(body.length, 0);
13400
13448
  return Buffer.concat([header, body]);
13401
13449
  }
13402
- async function attemptDaemonRequest2(request, opts) {
13450
+ async function attemptDaemonRequest2(build, opts) {
13451
+ const first = await attemptDaemonRequestAt2(PROTOCOL_VERSION2, build, opts);
13452
+ const older = !first.ok ? first.daemonVersion : undefined;
13453
+ if (older === undefined || !Number.isInteger(older) || older < MIN_PROTOCOL_VERSION2 || older >= PROTOCOL_VERSION2 || cloudDeploymentMayTargetAgents()) {
13454
+ return withoutDaemonVersion2(first);
13455
+ }
13456
+ const retried = await attemptDaemonRequestAt2(older, build, opts);
13457
+ if (cloudDeploymentMayTargetAgents())
13458
+ return withoutDaemonVersion2(first);
13459
+ return withoutDaemonVersion2(retried);
13460
+ }
13461
+ function withoutDaemonVersion2(attempt) {
13462
+ return attempt.ok ? attempt : { ok: false, failure: attempt.failure };
13463
+ }
13464
+ async function attemptDaemonRequestAt2(protocolVersion, build, opts) {
13465
+ const request = build(protocolVersion);
13403
13466
  if (process.platform === "win32")
13404
13467
  return { ok: false, failure: "unreachable" };
13405
13468
  const responseBudget = opts?.responseTimeoutMs ?? DAEMON_RESPONSE_TIMEOUT_MS2;
@@ -13456,8 +13519,9 @@ async function attemptDaemonRequest2(request, opts) {
13456
13519
  return;
13457
13520
  }
13458
13521
  const message = parsed;
13459
- if (message.protocolVersion !== PROTOCOL_VERSION2) {
13460
- fail("protocol-mismatch");
13522
+ if (message.protocolVersion !== protocolVersion) {
13523
+ const daemonVersion = typeof message.protocolVersion === "number" ? message.protocolVersion : undefined;
13524
+ finish({ ok: false, failure: "protocol-mismatch", daemonVersion });
13461
13525
  return;
13462
13526
  }
13463
13527
  finish({ ok: true, message });
@@ -13466,16 +13530,19 @@ async function attemptDaemonRequest2(request, opts) {
13466
13530
  socket.on("close", () => fail("unreachable"));
13467
13531
  });
13468
13532
  }
13533
+ function settingsPathFor2(protocolVersion, agentSettingsPath) {
13534
+ return protocolVersion >= AGENT_SETTINGS_PATH_SINCE2 ? { agentSettingsPath } : {};
13535
+ }
13469
13536
  async function attemptDaemonHook2(req, opts) {
13470
- const attempt = await attemptDaemonRequest2({
13537
+ const attempt = await attemptDaemonRequest2((protocolVersion) => ({
13471
13538
  type: "hook",
13472
- protocolVersion: PROTOCOL_VERSION2,
13539
+ protocolVersion,
13473
13540
  hookEvent: req.hookEvent,
13474
13541
  cli: req.cli,
13475
13542
  stdin: req.stdin,
13476
13543
  cwd: req.cwd,
13477
- agentSettingsPath: req.agentSettingsPath
13478
- }, opts);
13544
+ ...settingsPathFor2(protocolVersion, req.agentSettingsPath)
13545
+ }), opts);
13479
13546
  if (!attempt.ok)
13480
13547
  return attempt;
13481
13548
  const message = attempt.message;
@@ -13495,15 +13562,15 @@ function isStringArray(value) {
13495
13562
  return Array.isArray(value) && value.every((item) => typeof item === "string");
13496
13563
  }
13497
13564
  async function attemptDaemonPolicyEvaluation(req, opts) {
13498
- const attempt = await attemptDaemonRequest2({
13565
+ const attempt = await attemptDaemonRequest2((protocolVersion) => ({
13499
13566
  type: "policyEvaluation",
13500
- protocolVersion: PROTOCOL_VERSION2,
13567
+ protocolVersion,
13501
13568
  integration: req.integration,
13502
13569
  event: req.event,
13503
13570
  payload: req.payload,
13504
13571
  cwd: req.cwd,
13505
- agentSettingsPath: req.agentSettingsPath
13506
- }, opts);
13572
+ ...settingsPathFor2(protocolVersion, req.agentSettingsPath)
13573
+ }), opts);
13507
13574
  if (!attempt.ok)
13508
13575
  return attempt;
13509
13576
  const message = attempt.message;
@@ -13513,10 +13580,11 @@ async function attemptDaemonPolicyEvaluation(req, opts) {
13513
13580
  }
13514
13581
  return { ok: false, failure: "unreachable" };
13515
13582
  }
13516
- var PROTOCOL_VERSION2 = 2, DAEMON_CONNECT_TIMEOUT_MS2 = 150, DAEMON_RESPONSE_TIMEOUT_MS2 = 30000, MAX_FRAME_LEN2;
13583
+ var PROTOCOL_VERSION2 = 2, MIN_PROTOCOL_VERSION2 = 1, AGENT_SETTINGS_PATH_SINCE2 = 2, DAEMON_CONNECT_TIMEOUT_MS2 = 150, DAEMON_RESPONSE_TIMEOUT_MS2 = 30000, MAX_FRAME_LEN2;
13517
13584
  var init_daemon_client2 = __esm(() => {
13518
13585
  init_fp_home();
13519
13586
  init_fp_config();
13587
+ init_cloud_managed_policies();
13520
13588
  MAX_FRAME_LEN2 = 16 * 1024 * 1024;
13521
13589
  });
13522
13590
 
@@ -13527,6 +13595,7 @@ import {
13527
13595
  mkdtempSync,
13528
13596
  readFileSync as readFileSync7,
13529
13597
  readdirSync as readdirSync2,
13598
+ realpathSync as realpathSync3,
13530
13599
  statSync as statSync10,
13531
13600
  writeFileSync as writeFileSync5,
13532
13601
  unlinkSync,
@@ -13594,7 +13663,38 @@ function resolveWorkerCommand() {
13594
13663
  const workerScript = resolve8(packageRoot, "dist", "worker.mjs");
13595
13664
  if (!existsSync11(workerScript))
13596
13665
  return null;
13597
- return `${shellQuote(process.execPath)} ${shellQuote(workerScript)}`;
13666
+ return `${shellQuote(stableExecPath())} ${shellQuote(workerScript)}`;
13667
+ }
13668
+ function stableExecPath(execPath = process.execPath, pathEnv = process.env.PATH ?? "", stableDirs = STABLE_BIN_DIRS) {
13669
+ let real;
13670
+ try {
13671
+ real = realpathSync3(execPath);
13672
+ } catch {
13673
+ return execPath;
13674
+ }
13675
+ const name = execPath.split("/").pop() ?? "";
13676
+ for (const dir of pathEnv.split(":")) {
13677
+ if (!dir.startsWith("/") || !stableDirs.includes(dir.replace(/\/+$/, "")))
13678
+ continue;
13679
+ const candidate = resolve8(dir, name);
13680
+ if (candidate === execPath)
13681
+ return execPath;
13682
+ try {
13683
+ if (realpathSync3(candidate) === real)
13684
+ return candidate;
13685
+ } catch {}
13686
+ }
13687
+ return execPath;
13688
+ }
13689
+ function isPackageCommand(command) {
13690
+ const words = command ? shellQuotedWords(command) : null;
13691
+ const script = words?.at(-1);
13692
+ return words?.length === 2 && script !== undefined && /\/dist\/(worker|cli)\.mjs$/.test(script);
13693
+ }
13694
+ function savedCommandIsGone(command) {
13695
+ if (!isPackageCommand(command))
13696
+ return false;
13697
+ return shellQuotedWords(command).some((word) => !existsSync11(word));
13598
13698
  }
13599
13699
  function resolveCliCommand() {
13600
13700
  if (process.env.FAILPROOFAI_CLI_CMD)
@@ -13605,7 +13705,7 @@ function resolveCliCommand() {
13605
13705
  const cliScript = resolve8(packageRoot, "dist", "cli.mjs");
13606
13706
  if (!existsSync11(cliScript))
13607
13707
  return null;
13608
- return `${shellQuote(process.execPath)} ${shellQuote(cliScript)}`;
13708
+ return `${shellQuote(stableExecPath())} ${shellQuote(cliScript)}`;
13609
13709
  }
13610
13710
  function workerScriptPath() {
13611
13711
  if (process.env.FAILPROOFAI_WORKER_CMD)
@@ -13616,6 +13716,9 @@ function workerScriptPath() {
13616
13716
  const workerScript = resolve8(packageRoot, "dist", "worker.mjs");
13617
13717
  return existsSync11(workerScript) ? workerScript : null;
13618
13718
  }
13719
+ function escapeUnitPercent(value) {
13720
+ return value.replace(/%/g, "%%");
13721
+ }
13619
13722
  function assertUnitSafe(value, field) {
13620
13723
  if (UNIT_UNSAFE_RE.test(value)) {
13621
13724
  throw new Error(`refusing to write a service definition: ${field} contains a quote, backslash or newline ` + `(${JSON.stringify(value)}), which would inject directives into a root-owned unit file`);
@@ -13756,7 +13859,9 @@ function writePrivilegedFile(destination, contents, mode = "0644") {
13756
13859
  const staging = resolve8(stagingDir, "service-definition");
13757
13860
  try {
13758
13861
  writeFileSync5(staging, contents, "utf8");
13759
- runPrivileged("install", ["-m", mode, staging, destination]);
13862
+ const sibling = `${destination}.failproofai-new`;
13863
+ runPrivileged("install", ["-m", mode, staging, sibling]);
13864
+ runPrivileged("mv", ["-f", sibling, destination]);
13760
13865
  } finally {
13761
13866
  rmSync5(stagingDir, { recursive: true, force: true });
13762
13867
  }
@@ -13804,13 +13909,17 @@ function removeLegacyUserService() {
13804
13909
  }
13805
13910
  }
13806
13911
  function systemdUnitContents(binaryPath, workerCmd, cliCmd = null) {
13807
- const envLines = serviceEnvironment(workerCmd, cliCmd).map(([key, value]) => `Environment="${key}=${assertUnitSafe(value, key)}"
13808
- `).join("");
13912
+ const envLines = serviceEnvironment(workerCmd, cliCmd).map(([key, value]) => {
13913
+ const safe = assertUnitSafe(value, key);
13914
+ return `Environment="${key}=${isPackageCommand(safe) ? escapeUnitPercent(safe) : safe}"
13915
+ `;
13916
+ }).join("");
13809
13917
  const user = assertUnitSafe(serviceUser(), "User");
13810
13918
  assertUnitSafe(binaryPath, "ExecStart");
13811
13919
  assertUnitSafe(homedir5(), "HOME");
13812
- const conditionPaths = [binaryPath, workerScriptPath()].filter((p) => typeof p === "string" && existsSync11(p));
13813
- const conditionLines = conditionPaths.map((p) => `ConditionPathExists=${assertUnitSafe(p, "ConditionPathExists")}
13920
+ const workerScript = workerCmd === null || isPackageCommand(workerCmd) ? workerScriptPath() : null;
13921
+ const conditionPaths = [binaryPath, workerScript].filter((p) => typeof p === "string" && existsSync11(p));
13922
+ const conditionLines = conditionPaths.map((p) => `ConditionPathExists=${escapeUnitPercent(assertUnitSafe(p, "ConditionPathExists"))}
13814
13923
  `).join("");
13815
13924
  return `[Unit]
13816
13925
  Description=failproofai background daemon (failproofaid) for ${user}
@@ -13908,8 +14017,10 @@ async function installDaemonService() {
13908
14017
  if (!binaryPath) {
13909
14018
  return { installed: false, reason: binaryReason ?? "failproofaid binary not found for this platform" };
13910
14019
  }
13911
- const workerCmd = resolveWorkerCommand();
13912
- const cliCmd = resolveCliCommand();
14020
+ const savedWorker = process.env.FAILPROOFAI_WORKER_CMD ? null : installedEnvValue(readInstalledServiceDefinition() ?? "", "FAILPROOFAI_WORKER_CMD");
14021
+ const workerCmd = savedWorker && !isPackageCommand(savedWorker) ? savedWorker : resolveWorkerCommand();
14022
+ const savedCli = process.env.FAILPROOFAI_CLI_CMD ? null : installedEnvValue(readInstalledServiceDefinition() ?? "", "FAILPROOFAI_CLI_CMD");
14023
+ const cliCmd = savedCli && !isPackageCommand(savedCli) ? savedCli : resolveCliCommand();
13913
14024
  if (!canElevate()) {
13914
14025
  return {
13915
14026
  installed: false,
@@ -13929,10 +14040,10 @@ async function installDaemonService() {
13929
14040
  const plistPath = launchdPlistPath();
13930
14041
  const logDir = logsDir();
13931
14042
  mkdirSync7(logDir, { recursive: true });
14043
+ writePrivilegedFile(plistPath, launchdPlistContents(binaryPath, logDir, workerCmd, cliCmd));
13932
14044
  try {
13933
14045
  runPrivileged("launchctl", ["unload", plistPath]);
13934
14046
  } catch {}
13935
- writePrivilegedFile(plistPath, launchdPlistContents(binaryPath, logDir, workerCmd, cliCmd));
13936
14047
  runPrivileged("launchctl", ["load", "-w", plistPath]);
13937
14048
  }
13938
14049
  } catch (err) {
@@ -14045,7 +14156,7 @@ function readInstalledServiceDefinition() {
14045
14156
  function installedEnvValue(definition, name) {
14046
14157
  if (process.platform === "linux") {
14047
14158
  const m = new RegExp(`^Environment="${name}=(.*)"$`, "m").exec(definition);
14048
- return m ? m[1] : null;
14159
+ return m ? m[1].replace(/%%/g, "%") : null;
14049
14160
  }
14050
14161
  const m = new RegExp(`<key>${name}</key>\\s*<string>([^<]*)</string>`).exec(definition);
14051
14162
  return m ? unescapeXml(m[1]) : null;
@@ -14062,13 +14173,16 @@ function daemonServiceNeedsUpgrade() {
14062
14173
  const definition = readInstalledServiceDefinition();
14063
14174
  if (definition === null)
14064
14175
  return false;
14065
- return !definition.includes("FAILPROOFAI_CLI_CMD");
14176
+ if (!definition.includes("FAILPROOFAI_CLI_CMD"))
14177
+ return true;
14178
+ return savedCommandIsGone(installedEnvValue(definition, "FAILPROOFAI_WORKER_CMD")) || savedCommandIsGone(installedEnvValue(definition, "FAILPROOFAI_CLI_CMD"));
14066
14179
  }
14067
14180
  function upgradedServiceDefinition(definition, cliCmd, logDir) {
14068
14181
  const binaryPath = installedExecStart(definition);
14069
14182
  if (!binaryPath)
14070
14183
  return null;
14071
- const workerCmd = resolveWorkerCommand() ?? installedEnvValue(definition, "FAILPROOFAI_WORKER_CMD");
14184
+ const saved = installedEnvValue(definition, "FAILPROOFAI_WORKER_CMD");
14185
+ const workerCmd = !process.env.FAILPROOFAI_WORKER_CMD && saved && !isPackageCommand(saved) ? saved : resolveWorkerCommand() ?? saved;
14072
14186
  try {
14073
14187
  return process.platform === "linux" ? systemdUnitContents(binaryPath, workerCmd, cliCmd) : launchdPlistContents(binaryPath, logDir, workerCmd, cliCmd);
14074
14188
  } catch (err) {
@@ -14112,10 +14226,11 @@ async function refreshFailed(message, previous) {
14112
14226
  }
14113
14227
  async function ensureDaemonServiceCurrent() {
14114
14228
  const definition = readInstalledServiceDefinition();
14115
- if (definition === null || definition.includes("FAILPROOFAI_CLI_CMD")) {
14229
+ if (definition === null || !daemonServiceNeedsUpgrade()) {
14116
14230
  return { outcome: "current" };
14117
14231
  }
14118
- const cliCmd = resolveCliCommand();
14232
+ const savedCli = installedEnvValue(definition, "FAILPROOFAI_CLI_CMD");
14233
+ const cliCmd = !process.env.FAILPROOFAI_CLI_CMD && savedCli && !isPackageCommand(savedCli) ? savedCli : resolveCliCommand();
14119
14234
  if (!cliCmd) {
14120
14235
  return {
14121
14236
  outcome: "failed",
@@ -14124,6 +14239,13 @@ async function ensureDaemonServiceCurrent() {
14124
14239
  }
14125
14240
  const logDir = logsDir();
14126
14241
  const upgraded = upgradedServiceDefinition(definition, cliCmd, logDir);
14242
+ if (upgraded && (savedCommandIsGone(installedEnvValue(upgraded, "FAILPROOFAI_WORKER_CMD")) || savedCommandIsGone(installedEnvValue(upgraded, "FAILPROOFAI_CLI_CMD")))) {
14243
+ return {
14244
+ outcome: "failed",
14245
+ reason: "the failproofai install the service would run is incomplete (its Node.js or dist/ files are missing). Reinstall the package, then run `failproofai update`.",
14246
+ daemonRunning: daemonServiceStatus() === "running"
14247
+ };
14248
+ }
14127
14249
  if (!upgraded) {
14128
14250
  return {
14129
14251
  outcome: "failed",
@@ -14162,6 +14284,42 @@ async function ensureDaemonServiceCurrent() {
14162
14284
  }
14163
14285
  return { outcome: "rewritten", daemonRunning: true };
14164
14286
  }
14287
+ async function refreshDaemonToCliVersion(deps = {}) {
14288
+ const needsUpgrade = deps.needsUpgrade ?? daemonServiceNeedsUpgrade;
14289
+ const status = deps.status ?? daemonServiceStatus;
14290
+ const install = deps.install ?? installDaemonService;
14291
+ const prime = deps.prime ?? primeElevation;
14292
+ const interactive = deps.interactive ?? (() => Boolean(process.stdin.isTTY && process.stdout.isTTY));
14293
+ const current = status();
14294
+ if (current === "not-installed") {
14295
+ return { ok: true, lines: ["No failproofaid service on this machine; nothing to update."] };
14296
+ }
14297
+ const recorded = readVersionFile()?.daemon;
14298
+ if (current === "running" && recorded === version2 && existsSync11(installedBinaryPath(version2)) && !needsUpgrade()) {
14299
+ return { ok: true, lines: [`failproofaid ${version2} is already installed and running; nothing to update.`] };
14300
+ }
14301
+ if (interactive())
14302
+ prime();
14303
+ const result = await install();
14304
+ if (!result.installed) {
14305
+ const needsRoot = /root privileges are required/.test(result.reason ?? "");
14306
+ return {
14307
+ ok: false,
14308
+ lines: needsRoot ? [
14309
+ `✕ failproofaid ${version2} was not installed: root privileges are required. The previous daemon is untouched.`,
14310
+ " Run `sudo -v` and then `failproofai update` again."
14311
+ ] : [
14312
+ `✕ failproofaid ${version2} could not be installed: ${(result.reason ?? "unknown reason").replace(/\.$/, "")}. The previous daemon is untouched.`,
14313
+ ` See why with \`${daemonStatusCommand() ?? "systemctl status"}\`.`
14314
+ ]
14315
+ };
14316
+ }
14317
+ writeVersionFile({ daemon: version2 });
14318
+ return {
14319
+ ok: true,
14320
+ lines: [`failproofaid ${version2} installed, service restarted and holding.`]
14321
+ };
14322
+ }
14165
14323
  async function uninstallDaemonService() {
14166
14324
  setDaemonConfigured(false);
14167
14325
  if (!isDaemonSupportedPlatform())
@@ -14255,13 +14413,19 @@ function daemonServiceStatus() {
14255
14413
  return "stopped";
14256
14414
  }
14257
14415
  }
14258
- var SERVICE_CMD_TIMEOUT_MS = 1e4, SERVICE_START_TIMEOUT_MS = 5000, SERVICE_START_POLL_MS = 100, SERVICE_SETTLE_MS = 750, SUDO_PROMPT_TIMEOUT_MS = 120000, UNIT_UNSAFE_RE, DAEMON_PROBE_TIMEOUT_MS = 5000, DAEMON_PROBE_READY_TIMEOUT_MS = 1e4, DAEMON_PROBE_RETRY_MS = 150;
14416
+ var SERVICE_CMD_TIMEOUT_MS = 1e4, SERVICE_START_TIMEOUT_MS = 5000, SERVICE_START_POLL_MS = 100, SERVICE_SETTLE_MS = 750, SUDO_PROMPT_TIMEOUT_MS = 120000, STABLE_BIN_DIRS, UNIT_UNSAFE_RE, DAEMON_PROBE_TIMEOUT_MS = 5000, DAEMON_PROBE_READY_TIMEOUT_MS = 1e4, DAEMON_PROBE_RETRY_MS = 150;
14259
14417
  var init_daemon_service = __esm(() => {
14260
14418
  init_hook_logger();
14261
14419
  init_daemon_download();
14262
14420
  init_fp_home();
14263
14421
  init_package();
14264
14422
  init_fp_config();
14423
+ STABLE_BIN_DIRS = [
14424
+ "/opt/homebrew/bin",
14425
+ "/usr/local/bin",
14426
+ "/usr/bin",
14427
+ "/home/linuxbrew/.linuxbrew/bin"
14428
+ ];
14265
14429
  UNIT_UNSAFE_RE = /["\\\r\n]/;
14266
14430
  });
14267
14431
 
@@ -14928,7 +15092,7 @@ import {
14928
15092
  lstatSync as lstatSync3,
14929
15093
  mkdirSync as mkdirSync8,
14930
15094
  readlinkSync as readlinkSync2,
14931
- realpathSync as realpathSync3,
15095
+ realpathSync as realpathSync4,
14932
15096
  renameSync as renameSync5,
14933
15097
  rmSync as rmSync7,
14934
15098
  symlinkSync,
@@ -15353,7 +15517,7 @@ function samePath(a, b) {
15353
15517
  if (resolve12(a) === resolve12(b))
15354
15518
  return true;
15355
15519
  try {
15356
- return realpathSync3(a) === realpathSync3(b);
15520
+ return realpathSync4(a) === realpathSync4(b);
15357
15521
  } catch {
15358
15522
  return false;
15359
15523
  }
@@ -23368,6 +23532,7 @@ function deliveryHealth(home, now = Date.now(), connectedAt = home ? undefined :
23368
23532
  let rejected = 0;
23369
23533
  let credentialRejected = 0;
23370
23534
  let resending = 0;
23535
+ let retrying = 0;
23371
23536
  let oldestMtime;
23372
23537
  for (const name of entries) {
23373
23538
  if (!name.includes(".jsonl"))
@@ -23391,6 +23556,8 @@ function deliveryHealth(home, now = Date.now(), connectedAt = home ? undefined :
23391
23556
  byStatus[parsed.clientStatus] = (byStatus[parsed.clientStatus] ?? 0) + 1;
23392
23557
  if (CREDENTIAL_STATUSES.has(parsed.clientStatus))
23393
23558
  credentialRejected += 1;
23559
+ } else if (!parsed.poison) {
23560
+ retrying += 1;
23394
23561
  }
23395
23562
  if (oldestMtime === undefined || mtime < oldestMtime)
23396
23563
  oldestMtime = mtime;
@@ -23401,6 +23568,7 @@ function deliveryHealth(home, now = Date.now(), connectedAt = home ? undefined :
23401
23568
  credentialRejected,
23402
23569
  byStatus,
23403
23570
  resending,
23571
+ ...retrying > 0 ? { retrying } : {},
23404
23572
  ...oldestMtime !== undefined ? { oldestAgeMs: Math.max(0, now - oldestMtime) } : {}
23405
23573
  };
23406
23574
  }
@@ -33156,6 +33324,15 @@ var init_enforcement_capability = __esm(() => {
33156
33324
 
33157
33325
  // src/hooks/handler.ts
33158
33326
  import { existsSync as existsSync31 } from "node:fs";
33327
+ function toolCallIdOf(parsed) {
33328
+ const hermes = parsed.hermes;
33329
+ const nested = hermes && typeof hermes === "object" && !Array.isArray(hermes) ? hermes.tool_call_id : undefined;
33330
+ for (const value of [parsed.tool_use_id, parsed.tool_call_id, parsed.toolCallId, parsed.toolUseId, nested]) {
33331
+ if (typeof value === "string" && value.length > 0 && value.length <= 256)
33332
+ return value;
33333
+ }
33334
+ return;
33335
+ }
33159
33336
  function canonicalizeEventType(raw, cli) {
33160
33337
  if (cli === "codex") {
33161
33338
  const mapped = CODEX_EVENT_MAP[raw];
@@ -33384,6 +33561,7 @@ async function captureJevIntent(canonicalEventType, decision, parsed, session, c
33384
33561
  }
33385
33562
  async function evaluateHookEvent(eventType, cli = "claude", stdinPayload, opts) {
33386
33563
  const startTime = performance.now();
33564
+ const arrivedAt = Date.now();
33387
33565
  const layoutWarning = layoutWarningForHook();
33388
33566
  if (layoutWarning)
33389
33567
  hookLogWarn(layoutWarning);
@@ -33449,7 +33627,8 @@ async function evaluateHookEvent(eventType, cli = "claude", stdinPayload, opts)
33449
33627
  const packsInstalledHere = hasInstalledRegexPacks();
33450
33628
  const legacyNames = activePause || packsInstalledHere ? [] : config.enabledPolicies;
33451
33629
  registerBuiltinPolicies(activePause ? [] : legacyNames);
33452
- if (legacyNames.length > 0) {
33630
+ if (legacyNames.length > 0 && !legacyShimWarned) {
33631
+ legacyShimWarned = true;
33453
33632
  hookLogWarn(`enforcing ${legacyNames.length} policies from this build because no pack is installed — ` + `run \`failproofai policies add FailproofAI/policies\` to move them into a real pack`);
33454
33633
  }
33455
33634
  const enabledBuiltinNames = new Set(legacyNames);
@@ -33647,8 +33826,12 @@ async function evaluateHookEvent(eventType, cli = "claude", stdinPayload, opts)
33647
33826
  await captureJevIntent(canonicalEventType, result.decision, parsed, session, cli, opts, runtimeAgent);
33648
33827
  const matchedPolicies = matchedBeforeRelease ?? getPoliciesForEvent(canonicalEventType, parsed.tool_name).map((p) => p.name);
33649
33828
  const jevOrigin = result.policyName && result.twoTier?.decidedByJev ? result.twoTier.jevOrigin : undefined;
33829
+ const writtenAt = Date.now();
33830
+ const toolCallId = toolCallIdOf(parsed);
33650
33831
  const activityEntry = {
33651
- timestamp: Date.now(),
33832
+ timestamp: writtenAt,
33833
+ startedAt: Math.min(arrivedAt, writtenAt),
33834
+ ...toolCallId ? { toolCallId } : {},
33652
33835
  eventType: canonicalEventType,
33653
33836
  integration: cli,
33654
33837
  toolName: parsed.tool_name ?? null,
@@ -33774,7 +33957,7 @@ async function handleHookEvent(eventType, cli = "claude", agentSettingsPath) {
33774
33957
  }
33775
33958
  return result.exitCode;
33776
33959
  }
33777
- var JEV_GATE_EVENTS;
33960
+ var legacyShimWarned = false, JEV_GATE_EVENTS;
33778
33961
  var init_handler = __esm(() => {
33779
33962
  init_types();
33780
33963
  init_tool_name_canonicalize();
@@ -35046,7 +35229,7 @@ Your data is fine. Upgrade to read it: \`npm install -g failproofai@latest\``),
35046
35229
  const run = runMigrations(state.found);
35047
35230
  const { removed, migrated, activity } = run.outcome;
35048
35231
  const pending = await drainSpoolAfterMigrating();
35049
- const daemonHint = staleDaemonHint(kit);
35232
+ const daemonHint = deps.daemonUpdatedByCommand ? [] : staleDaemonHint(kit);
35050
35233
  return {
35051
35234
  state,
35052
35235
  fatal: false,
@@ -35072,7 +35255,7 @@ It is retried on the next command; your settings and enrolment were saved first
35072
35255
  state,
35073
35256
  fatal: false,
35074
35257
  didReset: false,
35075
- lines: [...await healDaemonFlag(deps, kit), ...staleDaemonHint(kit)]
35258
+ lines: [...await healDaemonFlag(deps, kit), ...deps.daemonUpdatedByCommand ? [] : staleDaemonHint(kit)]
35076
35259
  };
35077
35260
  }
35078
35261
  async function healDaemonFlag(deps, kit) {
@@ -35610,8 +35793,166 @@ var init_cli_error = __esm(() => {
35610
35793
  };
35611
35794
  });
35612
35795
 
35796
+ // lib/fetch-with-timeout.ts
35797
+ function fetchWithTimeout(input, init = {}, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
35798
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
35799
+ const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal;
35800
+ return fetch(input, { ...init, signal });
35801
+ }
35802
+ function isAbortError(err) {
35803
+ if (err === null || typeof err !== "object")
35804
+ return false;
35805
+ const name = err.name;
35806
+ return name === "AbortError" || name === "TimeoutError";
35807
+ }
35808
+ var DEFAULT_FETCH_TIMEOUT_MS = 15000;
35809
+
35810
+ // src/hooks/cloud-enrollment.ts
35811
+ import { randomUUID as randomUUID4 } from "node:crypto";
35812
+ import { existsSync as existsSync35, readFileSync as readFileSync31, rmSync as rmSync13 } from "node:fs";
35813
+ import { hostname as hostname3 } from "node:os";
35814
+ function cloudCredentialPath() {
35815
+ return process.env.FAILPROOFAI_CLOUD_CREDENTIALS ?? credentialsFile();
35816
+ }
35817
+ function usingJsonOverride() {
35818
+ return Boolean(process.env.FAILPROOFAI_CLOUD_CREDENTIALS);
35819
+ }
35820
+ function validateCloudUrl(raw) {
35821
+ let parsed;
35822
+ try {
35823
+ parsed = new URL(raw);
35824
+ } catch {
35825
+ return { ok: false, reason: `"${raw}" is not a valid URL. Expected something like https://be.failproof.ai` };
35826
+ }
35827
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
35828
+ return { ok: false, reason: `Unsupported scheme "${parsed.protocol}" — use https (or http for localhost).` };
35829
+ }
35830
+ if (parsed.protocol === "http:") {
35831
+ const host = parsed.hostname;
35832
+ const loopback = host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
35833
+ if (!loopback) {
35834
+ return {
35835
+ ok: false,
35836
+ reason: `Refusing to send the machine token to ${parsed.origin} over plain http. ` + `Use https, or http only for localhost during development.`
35837
+ };
35838
+ }
35839
+ }
35840
+ return { ok: true, url: parsed.origin + (parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/$/, "")) };
35841
+ }
35842
+ function maskToken(token) {
35843
+ if (token.length <= 4)
35844
+ return "****";
35845
+ return `****${token.slice(-4)}`;
35846
+ }
35847
+ function readCloudCredentials() {
35848
+ if (!usingJsonOverride())
35849
+ return readCredentials().cloud ?? null;
35850
+ const path = cloudCredentialPath();
35851
+ if (!existsSync35(path))
35852
+ return null;
35853
+ try {
35854
+ const raw = JSON.parse(readFileSync31(path, "utf8"));
35855
+ if (raw.schemaVersion !== SCHEMA_VERSION2)
35856
+ return null;
35857
+ if (typeof raw.url !== "string" || typeof raw.machineId !== "string" || typeof raw.token !== "string") {
35858
+ return null;
35859
+ }
35860
+ if (!raw.url || !raw.machineId || !raw.token)
35861
+ return null;
35862
+ const label = typeof raw.machineLabel === "string" && raw.machineLabel ? raw.machineLabel : undefined;
35863
+ return { url: raw.url, machineId: raw.machineId, token: raw.token, machineLabel: label };
35864
+ } catch {
35865
+ return null;
35866
+ }
35867
+ }
35868
+ function writeCloudCredentials(creds) {
35869
+ if (usingJsonOverride()) {
35870
+ writeJsonAtomically(cloudCredentialPath(), { schemaVersion: SCHEMA_VERSION2, ...creds });
35871
+ return;
35872
+ }
35873
+ writeCredentials({ ...readCredentials(), cloud: creds });
35874
+ }
35875
+ function resolveMachineId(explicit) {
35876
+ const trimmed = explicit?.trim();
35877
+ if (trimmed)
35878
+ return trimmed;
35879
+ const existing = readCloudCredentials();
35880
+ if (existing?.machineId)
35881
+ return existing.machineId;
35882
+ const collectorId = readConfig().collector.machineId;
35883
+ if (collectorId?.trim())
35884
+ return collectorId;
35885
+ return randomUUID4();
35886
+ }
35887
+ function resolveMachineLabel(explicit) {
35888
+ return explicit?.trim() || hostname3();
35889
+ }
35890
+ function clearCloudCredentials() {
35891
+ if (usingJsonOverride()) {
35892
+ const path = cloudCredentialPath();
35893
+ if (!existsSync35(path))
35894
+ return false;
35895
+ try {
35896
+ rmSync13(path);
35897
+ return true;
35898
+ } catch {
35899
+ return false;
35900
+ }
35901
+ }
35902
+ const current = readCredentials();
35903
+ if (!current.cloud)
35904
+ return false;
35905
+ const { cloud: _dropped, ...rest } = current;
35906
+ writeCredentials(rest);
35907
+ return true;
35908
+ }
35909
+ async function verifyCloudCredentials(creds) {
35910
+ const labelParam = creds.machineLabel ? `&label=${encodeURIComponent(creds.machineLabel)}` : "";
35911
+ const url = `${creds.url}/enforcement/v1/desired-state?machineId=${encodeURIComponent(creds.machineId)}${labelParam}`;
35912
+ let response;
35913
+ try {
35914
+ response = await fetchWithTimeout(url, { headers: { Authorization: `Bearer ${creds.token}` } }, VERIFY_TIMEOUT_MS);
35915
+ } catch (err) {
35916
+ if (isAbortError(err))
35917
+ return { ok: false, reason: `No response from ${creds.url} within ${VERIFY_TIMEOUT_MS / 1000}s.` };
35918
+ return { ok: false, reason: `Could not reach ${creds.url}: ${err instanceof Error ? err.message : String(err)}` };
35919
+ }
35920
+ if (response.status === 401) {
35921
+ return { ok: false, status: 401, reason: "The server rejected this token (401). Check the key was copied whole." };
35922
+ }
35923
+ if (response.status === 403) {
35924
+ return {
35925
+ ok: false,
35926
+ status: 403,
35927
+ reason: "This key is valid but lacks the `policies:pull` permission (403). Create a machine key with that permission."
35928
+ };
35929
+ }
35930
+ if (!response.ok) {
35931
+ return { ok: false, status: response.status, reason: `The server answered ${response.status} ${response.statusText}.` };
35932
+ }
35933
+ try {
35934
+ const body = await response.json();
35935
+ return {
35936
+ ok: true,
35937
+ policyCount: Array.isArray(body.policies) ? body.policies.length : 0,
35938
+ deployment: typeof body.deployment === "number" ? body.deployment : 0
35939
+ };
35940
+ } catch {
35941
+ return {
35942
+ ok: false,
35943
+ reason: `${creds.url} answered, but not with a desired-state document. Is this a FailproofAI Cloud URL?`
35944
+ };
35945
+ }
35946
+ }
35947
+ var SCHEMA_VERSION2 = 1, VERIFY_TIMEOUT_MS = 1e4;
35948
+ var init_cloud_enrollment = __esm(() => {
35949
+ init_atomic_write();
35950
+ init_fp_home();
35951
+ init_fp_config();
35952
+ });
35953
+
35613
35954
  // src/hooks/backfill-request.ts
35614
- import { existsSync as existsSync35, readFileSync as readFileSync31 } from "node:fs";
35955
+ import { existsSync as existsSync36, readFileSync as readFileSync32 } from "node:fs";
35615
35956
  import { join as join36 } from "node:path";
35616
35957
  function backfillRequestPath(home) {
35617
35958
  return join36(failproofaiHome(home), "state", "backfill-request.json");
@@ -35661,9 +36002,9 @@ function mergeBackfillRequests(pending, next) {
35661
36002
  function writeBackfillRequest(next, home) {
35662
36003
  const path = backfillRequestPath(home);
35663
36004
  let pending = null;
35664
- if (existsSync35(path)) {
36005
+ if (existsSync36(path)) {
35665
36006
  try {
35666
- pending = readPendingRequest(JSON.parse(readFileSync31(path, "utf8")), next.requestedAtMs);
36007
+ pending = readPendingRequest(JSON.parse(readFileSync32(path, "utf8")), next.requestedAtMs);
35667
36008
  } catch {
35668
36009
  pending = null;
35669
36010
  }
@@ -35701,14 +36042,14 @@ var init_backfill_request = __esm(() => {
35701
36042
  });
35702
36043
 
35703
36044
  // src/hooks/agent-selection.ts
35704
- import { existsSync as existsSync36 } from "node:fs";
36045
+ import { existsSync as existsSync37 } from "node:fs";
35705
36046
  function hookedAtUserScope(id, cwd) {
35706
36047
  const integration = getIntegration(id);
35707
36048
  try {
35708
36049
  if (integration.hooksInstalledInSettings("user", cwd))
35709
36050
  return true;
35710
36051
  if (id === "hermes") {
35711
- return hermesProfileHealth().some((p) => existsSync36(p.home) && (p.pluginInstalled && p.pluginEnabled || p.legacyShellHookPresent));
36052
+ return hermesProfileHealth().some((p) => existsSync37(p.home) && (p.pluginInstalled && p.pluginEnabled || p.legacyShellHookPresent));
35712
36053
  }
35713
36054
  const paths = settingsPathsFor(integration, "user", cwd);
35714
36055
  if (paths.length < 2)
@@ -35781,9 +36122,9 @@ var init_agent_selection = __esm(() => {
35781
36122
 
35782
36123
  // src/hooks/manager.ts
35783
36124
  import { execSync as execSync7 } from "node:child_process";
35784
- import { existsSync as existsSync37 } from "node:fs";
36125
+ import { existsSync as existsSync38 } from "node:fs";
35785
36126
  import { resolve as resolve30, basename as basename8 } from "node:path";
35786
- import { platform as platform3, arch as arch3, release as release2, hostname as hostname3 } from "node:os";
36127
+ import { platform as platform3, arch as arch3, release as release2, hostname as hostname4 } from "node:os";
35787
36128
  function getSettingsPath(scope, cwd) {
35788
36129
  return claudeCode.getSettingsPath(scope, cwd);
35789
36130
  }
@@ -35928,13 +36269,15 @@ function integrationsInstalledAt(scope, cwd) {
35928
36269
  function cloudPolicyStatus() {
35929
36270
  let count = 0;
35930
36271
  let observing = false;
36272
+ let observingCount = 0;
35931
36273
  const jsIds = new Set;
35932
36274
  try {
35933
36275
  for (const artifact of listActiveCloudManagedPolicies()) {
35934
36276
  jsIds.add(artifact.id);
35935
- if (artifact.effect === "observe")
36277
+ if (artifact.effect === "observe") {
35936
36278
  observing = true;
35937
- else
36279
+ observingCount++;
36280
+ } else
35938
36281
  count++;
35939
36282
  }
35940
36283
  } catch {}
@@ -35944,14 +36287,15 @@ function cloudPolicyStatus() {
35944
36287
  for (const assignment of readCloudJevAssignments() ?? []) {
35945
36288
  if (jsIds.has(assignment.id))
35946
36289
  continue;
35947
- if (jevMode === "observe" || assignment.effect === "observe")
36290
+ if (jevMode === "observe" || assignment.effect === "observe") {
35948
36291
  observing = true;
35949
- else
36292
+ observingCount++;
36293
+ } else
35950
36294
  count++;
35951
36295
  }
35952
36296
  }
35953
36297
  } catch {}
35954
- return { count, observing };
36298
+ return { count, observing, observingCount };
35955
36299
  }
35956
36300
  function notEnforcingReason(cwd) {
35957
36301
  const wired = deduplicateScopes(HOOK_SCOPES, cwd).some((scope) => hooksInstalledInSettings(scope, cwd));
@@ -36098,7 +36442,7 @@ async function installHooksImpl(policyNames, scope = "user", cwd, includeBeta =
36098
36442
  } else if (customPoliciesPath && (typeof customPoliciesPath === "string" || customPoliciesPath.length > 0)) {
36099
36443
  const incoming = (typeof customPoliciesPath === "string" ? [customPoliciesPath] : customPoliciesPath).map((path) => resolve30(path));
36100
36444
  const carried = (previousConfig.customPoliciesPaths ?? (previousConfig.customPoliciesPath ? [previousConfig.customPoliciesPath] : [])).map((path) => resolve30(path)).filter((path) => {
36101
- if (existsSync37(path))
36445
+ if (existsSync38(path))
36102
36446
  return true;
36103
36447
  console.log(`Dropping custom policies path (file no longer exists): ${path}`);
36104
36448
  return false;
@@ -36183,7 +36527,7 @@ Validated ${validatedHooks.length} custom hook(s) from ${path}: ${validatedHooks
36183
36527
  const placed = installCodexSystemHooks(codexSystemHookEntries(binaryPath));
36184
36528
  if (placed.ok) {
36185
36529
  const userPath = integration.getSettingsPath("user", cwd);
36186
- if (existsSync37(userPath))
36530
+ if (existsSync38(userPath))
36187
36531
  integration.removeHooksFromFile(userPath);
36188
36532
  writtenSettingsPaths.push({ cli: cliId, path: placed.path });
36189
36533
  continue;
@@ -36228,7 +36572,7 @@ Validated ${validatedHooks.length} custom hook(s) from ${path}: ${validatedHooks
36228
36572
  platform: platform3(),
36229
36573
  arch: arch3(),
36230
36574
  os_release: release2(),
36231
- hostname_hash: hashToId2(hostname3()),
36575
+ hostname_hash: hashToId2(hostname4()),
36232
36576
  has_custom_hooks_path: !!(configToWrite.customPoliciesPaths?.length || configToWrite.customPoliciesPath),
36233
36577
  has_policy_params: !!(configToWrite.policyParams && Object.keys(configToWrite.policyParams).length > 0),
36234
36578
  param_policy_names: configToWrite.policyParams ? Object.keys(configToWrite.policyParams) : [],
@@ -36340,7 +36684,7 @@ async function removeHooks(policyNames, scope = "user", cwd, opts) {
36340
36684
  platform: platform3(),
36341
36685
  arch: arch3(),
36342
36686
  os_release: release2(),
36343
- hostname_hash: hashToId2(hostname3())
36687
+ hostname_hash: hashToId2(hostname4())
36344
36688
  });
36345
36689
  } catch {}
36346
36690
  say(`Disabled ${policyNames.length - notEnabled.length} policy(ies).`);
@@ -36380,7 +36724,7 @@ async function removeHooks(policyNames, scope = "user", cwd, opts) {
36380
36724
  }
36381
36725
  }
36382
36726
  const settingsPaths = settingsPathsFor(integration, s, cwd);
36383
- const existing = cliId === "hermes" ? settingsPaths : settingsPaths.filter((p) => existsSync37(p));
36727
+ const existing = cliId === "hermes" ? settingsPaths : settingsPaths.filter((p) => existsSync38(p));
36384
36728
  if (existing.length === 0) {
36385
36729
  totalRemoved += removedFromSystem;
36386
36730
  if (removedFromSystem > 0)
@@ -36436,7 +36780,7 @@ async function removeHooks(policyNames, scope = "user", cwd, opts) {
36436
36780
  platform: platform3(),
36437
36781
  arch: arch3(),
36438
36782
  os_release: release2(),
36439
- hostname_hash: hashToId2(hostname3())
36783
+ hostname_hash: hashToId2(hostname4())
36440
36784
  });
36441
36785
  } catch {}
36442
36786
  if (scope === "all") {
@@ -36454,6 +36798,16 @@ async function removeHooks(policyNames, scope = "user", cwd, opts) {
36454
36798
  }
36455
36799
  untraceRemoved();
36456
36800
  }
36801
+ function cloudDashboardUrl() {
36802
+ const fromEnv = process.env.FAILPROOFAI_CLOUD_URL?.trim();
36803
+ if (fromEnv)
36804
+ return fromEnv;
36805
+ try {
36806
+ return readCloudCredentials()?.url || undefined;
36807
+ } catch {
36808
+ return;
36809
+ }
36810
+ }
36457
36811
  var VALID_POLICY_NAMES;
36458
36812
  var init_manager = __esm(() => {
36459
36813
  init_types();
@@ -36469,6 +36823,7 @@ var init_manager = __esm(() => {
36469
36823
  init_hook_logger();
36470
36824
  init_fp_home();
36471
36825
  init_cloud_managed_policies();
36826
+ init_cloud_enrollment();
36472
36827
  init_cloud_policy_errors();
36473
36828
  init_agent_roster2();
36474
36829
  init_pack_store();
@@ -36481,7 +36836,7 @@ var init_manager = __esm(() => {
36481
36836
  });
36482
36837
 
36483
36838
  // src/hooks/agent-skill.ts
36484
- import { existsSync as existsSync38, mkdirSync as mkdirSync21, rmdirSync as rmdirSync2, rmSync as rmSync13 } from "node:fs";
36839
+ import { existsSync as existsSync39, mkdirSync as mkdirSync21, rmdirSync as rmdirSync2, rmSync as rmSync14 } from "node:fs";
36485
36840
  import { homedir as homedir30 } from "node:os";
36486
36841
  import { join as join37, resolve as resolve31 } from "node:path";
36487
36842
  function envDir(name, fallback) {
@@ -36521,7 +36876,7 @@ function agentSkillRoots(id) {
36521
36876
  }
36522
36877
  }
36523
36878
  function listedTwice(id) {
36524
- return id === "codex" && existsSync38(join37(homedir30(), ".agents", "skills", AGENT_SKILL_NAME, "SKILL.md"));
36879
+ return id === "codex" && existsSync39(join37(homedir30(), ".agents", "skills", AGENT_SKILL_NAME, "SKILL.md"));
36525
36880
  }
36526
36881
  function installAgentSkill(ids) {
36527
36882
  const installed = [];
@@ -36530,19 +36885,19 @@ function installAgentSkill(ids) {
36530
36885
  const covered = listedTwice(id);
36531
36886
  for (const root of agentSkillRoots(id)) {
36532
36887
  const dir = join37(root, AGENT_SKILL_NAME);
36533
- const ours = existsSync38(join37(dir, AGENT_SKILL_MARKER));
36888
+ const ours = existsSync39(join37(dir, AGENT_SKILL_MARKER));
36534
36889
  if (covered) {
36535
36890
  if (ours)
36536
36891
  removeSkillDir(dir);
36537
36892
  continue;
36538
36893
  }
36539
- if (existsSync38(dir) && !ours)
36894
+ if (existsSync39(dir) && !ours)
36540
36895
  continue;
36541
36896
  let created = false;
36542
36897
  let marked = false;
36543
36898
  try {
36544
36899
  mkdirSync21(root, { recursive: true });
36545
- if (!existsSync38(dir)) {
36900
+ if (!existsSync39(dir)) {
36546
36901
  mkdirSync21(dir);
36547
36902
  created = true;
36548
36903
  }
@@ -36566,11 +36921,11 @@ function installAgentSkill(ids) {
36566
36921
  }
36567
36922
  function installedAgentSkillDirs() {
36568
36923
  const dirs = INTEGRATION_TYPES.flatMap((id) => agentSkillRoots(id).map((root) => join37(root, AGENT_SKILL_NAME)));
36569
- return [...new Set(dirs)].filter((dir) => existsSync38(join37(dir, AGENT_SKILL_MARKER)));
36924
+ return [...new Set(dirs)].filter((dir) => existsSync39(join37(dir, AGENT_SKILL_MARKER)));
36570
36925
  }
36571
36926
  function removeSkillDir(dir) {
36572
36927
  try {
36573
- rmSync13(dir, { recursive: true, force: true });
36928
+ rmSync14(dir, { recursive: true, force: true });
36574
36929
  return true;
36575
36930
  } catch (err) {
36576
36931
  hookLogWarn(`the failproofai skill was not removed from ${dir}: ${err instanceof Error ? err.message : String(err)}`);
@@ -36613,164 +36968,6 @@ For focused work, read the matching skill too. Each has the same layout, with it
36613
36968
  `;
36614
36969
  });
36615
36970
 
36616
- // lib/fetch-with-timeout.ts
36617
- function fetchWithTimeout(input, init = {}, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
36618
- const timeoutSignal = AbortSignal.timeout(timeoutMs);
36619
- const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal;
36620
- return fetch(input, { ...init, signal });
36621
- }
36622
- function isAbortError(err) {
36623
- if (err === null || typeof err !== "object")
36624
- return false;
36625
- const name = err.name;
36626
- return name === "AbortError" || name === "TimeoutError";
36627
- }
36628
- var DEFAULT_FETCH_TIMEOUT_MS = 15000;
36629
-
36630
- // src/hooks/cloud-enrollment.ts
36631
- import { randomUUID as randomUUID4 } from "node:crypto";
36632
- import { existsSync as existsSync39, readFileSync as readFileSync32, rmSync as rmSync14 } from "node:fs";
36633
- import { hostname as hostname4 } from "node:os";
36634
- function cloudCredentialPath() {
36635
- return process.env.FAILPROOFAI_CLOUD_CREDENTIALS ?? credentialsFile();
36636
- }
36637
- function usingJsonOverride() {
36638
- return Boolean(process.env.FAILPROOFAI_CLOUD_CREDENTIALS);
36639
- }
36640
- function validateCloudUrl(raw) {
36641
- let parsed;
36642
- try {
36643
- parsed = new URL(raw);
36644
- } catch {
36645
- return { ok: false, reason: `"${raw}" is not a valid URL. Expected something like https://be.failproof.ai` };
36646
- }
36647
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
36648
- return { ok: false, reason: `Unsupported scheme "${parsed.protocol}" — use https (or http for localhost).` };
36649
- }
36650
- if (parsed.protocol === "http:") {
36651
- const host = parsed.hostname;
36652
- const loopback = host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
36653
- if (!loopback) {
36654
- return {
36655
- ok: false,
36656
- reason: `Refusing to send the machine token to ${parsed.origin} over plain http. ` + `Use https, or http only for localhost during development.`
36657
- };
36658
- }
36659
- }
36660
- return { ok: true, url: parsed.origin + (parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/$/, "")) };
36661
- }
36662
- function maskToken(token) {
36663
- if (token.length <= 4)
36664
- return "****";
36665
- return `****${token.slice(-4)}`;
36666
- }
36667
- function readCloudCredentials() {
36668
- if (!usingJsonOverride())
36669
- return readCredentials().cloud ?? null;
36670
- const path = cloudCredentialPath();
36671
- if (!existsSync39(path))
36672
- return null;
36673
- try {
36674
- const raw = JSON.parse(readFileSync32(path, "utf8"));
36675
- if (raw.schemaVersion !== SCHEMA_VERSION2)
36676
- return null;
36677
- if (typeof raw.url !== "string" || typeof raw.machineId !== "string" || typeof raw.token !== "string") {
36678
- return null;
36679
- }
36680
- if (!raw.url || !raw.machineId || !raw.token)
36681
- return null;
36682
- const label = typeof raw.machineLabel === "string" && raw.machineLabel ? raw.machineLabel : undefined;
36683
- return { url: raw.url, machineId: raw.machineId, token: raw.token, machineLabel: label };
36684
- } catch {
36685
- return null;
36686
- }
36687
- }
36688
- function writeCloudCredentials(creds) {
36689
- if (usingJsonOverride()) {
36690
- writeJsonAtomically(cloudCredentialPath(), { schemaVersion: SCHEMA_VERSION2, ...creds });
36691
- return;
36692
- }
36693
- writeCredentials({ ...readCredentials(), cloud: creds });
36694
- }
36695
- function resolveMachineId(explicit) {
36696
- const trimmed = explicit?.trim();
36697
- if (trimmed)
36698
- return trimmed;
36699
- const existing = readCloudCredentials();
36700
- if (existing?.machineId)
36701
- return existing.machineId;
36702
- const collectorId = readConfig().collector.machineId;
36703
- if (collectorId?.trim())
36704
- return collectorId;
36705
- return randomUUID4();
36706
- }
36707
- function resolveMachineLabel(explicit) {
36708
- return explicit?.trim() || hostname4();
36709
- }
36710
- function clearCloudCredentials() {
36711
- if (usingJsonOverride()) {
36712
- const path = cloudCredentialPath();
36713
- if (!existsSync39(path))
36714
- return false;
36715
- try {
36716
- rmSync14(path);
36717
- return true;
36718
- } catch {
36719
- return false;
36720
- }
36721
- }
36722
- const current = readCredentials();
36723
- if (!current.cloud)
36724
- return false;
36725
- const { cloud: _dropped, ...rest } = current;
36726
- writeCredentials(rest);
36727
- return true;
36728
- }
36729
- async function verifyCloudCredentials(creds) {
36730
- const labelParam = creds.machineLabel ? `&label=${encodeURIComponent(creds.machineLabel)}` : "";
36731
- const url = `${creds.url}/enforcement/v1/desired-state?machineId=${encodeURIComponent(creds.machineId)}${labelParam}`;
36732
- let response;
36733
- try {
36734
- response = await fetchWithTimeout(url, { headers: { Authorization: `Bearer ${creds.token}` } }, VERIFY_TIMEOUT_MS);
36735
- } catch (err) {
36736
- if (isAbortError(err))
36737
- return { ok: false, reason: `No response from ${creds.url} within ${VERIFY_TIMEOUT_MS / 1000}s.` };
36738
- return { ok: false, reason: `Could not reach ${creds.url}: ${err instanceof Error ? err.message : String(err)}` };
36739
- }
36740
- if (response.status === 401) {
36741
- return { ok: false, status: 401, reason: "The server rejected this token (401). Check the key was copied whole." };
36742
- }
36743
- if (response.status === 403) {
36744
- return {
36745
- ok: false,
36746
- status: 403,
36747
- reason: "This key is valid but lacks the `policies:pull` permission (403). Create a machine key with that permission."
36748
- };
36749
- }
36750
- if (!response.ok) {
36751
- return { ok: false, status: response.status, reason: `The server answered ${response.status} ${response.statusText}.` };
36752
- }
36753
- try {
36754
- const body = await response.json();
36755
- return {
36756
- ok: true,
36757
- policyCount: Array.isArray(body.policies) ? body.policies.length : 0,
36758
- deployment: typeof body.deployment === "number" ? body.deployment : 0
36759
- };
36760
- } catch {
36761
- return {
36762
- ok: false,
36763
- reason: `${creds.url} answered, but not with a desired-state document. Is this a FailproofAI Cloud URL?`
36764
- };
36765
- }
36766
- }
36767
- var SCHEMA_VERSION2 = 1, VERIFY_TIMEOUT_MS = 1e4;
36768
- var init_cloud_enrollment = __esm(() => {
36769
- init_atomic_write();
36770
- init_fp_home();
36771
- init_fp_config();
36772
- });
36773
-
36774
36971
  // src/hooks/cloud-introspect.ts
36775
36972
  function introspectUrlFor(origin) {
36776
36973
  return `${origin.replace(/\/$/, "")}${INTROSPECT_PATH}`;
@@ -37459,7 +37656,7 @@ var init_cloud_connection = __esm(() => {
37459
37656
  });
37460
37657
 
37461
37658
  // src/hooks/setup-state.ts
37462
- import { existsSync as existsSync42, realpathSync as realpathSync4, statSync as statSync31 } from "node:fs";
37659
+ import { existsSync as existsSync42, realpathSync as realpathSync5, statSync as statSync31 } from "node:fs";
37463
37660
  import { dirname as dirname24, resolve as resolve32 } from "node:path";
37464
37661
  import { homedir as homedir31 } from "node:os";
37465
37662
  function globalConfigPath(home = homedir31()) {
@@ -37503,7 +37700,7 @@ function hasGlobalHooksInstalled() {
37503
37700
  function realResolve(path) {
37504
37701
  const lexical = resolve32(path);
37505
37702
  try {
37506
- return realpathSync4(lexical);
37703
+ return realpathSync5(lexical);
37507
37704
  } catch {
37508
37705
  return lexical;
37509
37706
  }
@@ -41433,7 +41630,8 @@ ${process.platform} service target.
41433
41630
  cwd,
41434
41631
  agents: selected.length,
41435
41632
  connected: cloudAfter,
41436
- codexTrust
41633
+ codexTrust,
41634
+ cloudDashboard: cloudAfter ? cloudDashboardUrl() : undefined
41437
41635
  }));
41438
41636
  return {
41439
41637
  applied: true,
@@ -41573,7 +41771,7 @@ function doneLines(kit, state) {
41573
41771
  const agents = codexSkips ? Math.max(0, state.agents - 1) : state.agents;
41574
41772
  const on = `${agents} ${agents === 1 ? "agent" : "agents"}`;
41575
41773
  if (notEnforcingReason(state.cwd)) {
41576
- lines.push(kit.caution("Policies are not enforcing yet."), ` Turn on ours: ${kit.cmd(`failproofai policies add ${CORE_SOURCE}`)}`);
41774
+ lines.push(kit.caution("Policies are not enforcing yet."), state.cloudDashboard ? ` Deploy from Cloud: ${kit.cmd(state.cloudDashboard)}` : ` Turn on ours: ${kit.cmd(`failproofai policies add ${CORE_SOURCE}`)}`);
41577
41775
  } else {
41578
41776
  const { count, custom } = enforcingPolicyCount(state.cwd);
41579
41777
  const nowhere = codexSkips && agents === 0;
@@ -47054,594 +47252,145 @@ var init_migrations2 = __esm(() => {
47054
47252
  ];
47055
47253
  });
47056
47254
 
47057
- // src/hooks/daemon-service.ts
47058
- import {
47059
- existsSync as existsSync56,
47060
- mkdirSync as mkdirSync33,
47061
- mkdtempSync as mkdtempSync2,
47062
- readFileSync as readFileSync45,
47063
- readdirSync as readdirSync25,
47064
- statSync as statSync42,
47065
- writeFileSync as writeFileSync28,
47066
- unlinkSync as unlinkSync10,
47067
- rmSync as rmSync22
47068
- } from "node:fs";
47069
- import { homedir as homedir38, tmpdir as tmpdir3, userInfo as userInfo2 } from "node:os";
47070
- import { dirname as dirname31, resolve as resolve39 } from "node:path";
47071
- import { execFileSync as execFileSync3 } from "node:child_process";
47072
- function isDaemonSupportedPlatform2() {
47073
- return process.platform === "linux" || process.platform === "darwin";
47074
- }
47075
- function platformKey2() {
47076
- const os = process.platform === "linux" ? "linux" : process.platform === "darwin" ? "darwin" : null;
47077
- const arch = process.arch === "x64" ? "x64" : process.arch === "arm64" ? "arm64" : null;
47078
- if (!os || !arch)
47079
- return null;
47080
- return `${os}-${arch}`;
47081
- }
47082
- function resolveFailproofaidBinaryPath2() {
47083
- if (process.env.FAILPROOFAI_DAEMON_BINARY)
47084
- return process.env.FAILPROOFAI_DAEMON_BINARY;
47085
- const downloaded = installedBinaryPath();
47086
- if (existsSync56(downloaded))
47087
- return downloaded;
47088
- const packageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT;
47089
- if (packageRoot) {
47090
- for (const profile of ["release", "debug"]) {
47091
- const candidate = resolve39(packageRoot, "target", profile, "failproofaid");
47092
- if (existsSync56(candidate))
47093
- return candidate;
47094
- }
47095
- }
47096
- return null;
47097
- }
47098
- async function ensureFailproofaidBinary2() {
47099
- const existing = resolveFailproofaidBinaryPath2();
47100
- if (existing)
47101
- return { path: existing };
47102
- const key = platformKey2();
47103
- if (!key) {
47104
- return { reason: `failproofaid has no prebuilt binary for ${process.platform}/${process.arch}` };
47105
- }
47106
- const fromNpm = installFromNpmPackage(key);
47107
- if (fromNpm.path)
47108
- return { path: fromNpm.path };
47109
- const result = await downloadFailproofaidBinary(key);
47110
- if (result.path)
47111
- return { path: result.path };
47112
- return {
47113
- reason: result.error ? `${result.error} (${fromNpm.error})` : "failproofaid binary could not be installed"
47114
- };
47115
- }
47116
- function resolveWorkerCommand2() {
47117
- if (process.env.FAILPROOFAI_WORKER_CMD)
47118
- return process.env.FAILPROOFAI_WORKER_CMD;
47119
- const packageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT;
47120
- if (!packageRoot)
47121
- return null;
47122
- const workerScript = resolve39(packageRoot, "dist", "worker.mjs");
47123
- if (!existsSync56(workerScript))
47124
- return null;
47125
- return `${shellQuote(process.execPath)} ${shellQuote(workerScript)}`;
47126
- }
47127
- function resolveCliCommand2() {
47128
- if (process.env.FAILPROOFAI_CLI_CMD)
47129
- return process.env.FAILPROOFAI_CLI_CMD;
47130
- const packageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT;
47131
- if (!packageRoot)
47132
- return null;
47133
- const cliScript = resolve39(packageRoot, "dist", "cli.mjs");
47134
- if (!existsSync56(cliScript))
47135
- return null;
47136
- return `${shellQuote(process.execPath)} ${shellQuote(cliScript)}`;
47137
- }
47138
- function workerScriptPath2() {
47139
- if (process.env.FAILPROOFAI_WORKER_CMD)
47140
- return null;
47141
- const packageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT;
47142
- if (!packageRoot)
47143
- return null;
47144
- const workerScript = resolve39(packageRoot, "dist", "worker.mjs");
47145
- return existsSync56(workerScript) ? workerScript : null;
47146
- }
47147
- function assertUnitSafe2(value, field) {
47148
- if (UNIT_UNSAFE_RE2.test(value)) {
47149
- throw new Error(`refusing to write a service definition: ${field} contains a quote, backslash or newline ` + `(${JSON.stringify(value)}), which would inject directives into a root-owned unit file`);
47150
- }
47151
- return value;
47152
- }
47153
- function serviceEnvironment2(workerCmd, cliCmd) {
47154
- const entries = [];
47155
- if (workerCmd)
47156
- entries.push(["FAILPROOFAI_WORKER_CMD", workerCmd]);
47157
- if (cliCmd)
47158
- entries.push(["FAILPROOFAI_CLI_CMD", cliCmd]);
47159
- return entries;
47160
- }
47161
- function serviceUser2() {
47162
- return userInfo2().username;
47163
- }
47164
- function systemdUnitName2(user = serviceUser2()) {
47165
- return `failproofaid@${user}.service`;
47166
- }
47167
- function systemdUnitDir2() {
47168
- return process.env.FAILPROOFAI_SYSTEMD_DIR || "/etc/systemd/system";
47169
- }
47170
- function systemdUnitPath2(user = serviceUser2()) {
47171
- return resolve39(systemdUnitDir2(), systemdUnitName2(user));
47172
- }
47173
- function systemBinaryRoot2(user = serviceUser2()) {
47174
- return resolve39(process.env.FAILPROOFAI_SYSTEM_BIN_DIR || "/opt/failproofai", user);
47175
- }
47176
- function systemBinaryDir2() {
47177
- return resolve39(systemBinaryRoot2(), "bin");
47178
- }
47179
- function systemBinaryTarget2(binaryPath) {
47180
- if (process.platform !== "linux" || process.env.FAILPROOFAI_DAEMON_BINARY)
47181
- return null;
47182
- try {
47183
- if (!statSync42(binaryPath).isFile())
47184
- return null;
47185
- } catch {
47186
- return null;
47187
- }
47188
- return resolve39(systemBinaryDir2(), `failproofaid-${version2}`);
47189
- }
47190
- function selinuxEnabled2() {
47191
- return existsSync56("/sys/fs/selinux/enforce");
47192
- }
47193
- function stageSystemBinary2(binaryPath) {
47194
- const target = systemBinaryTarget2(binaryPath);
47195
- if (!target)
47196
- return binaryPath;
47197
- const dir = systemBinaryDir2();
47198
- const staging = `${target}.${process.pid}.tmp`;
47199
- runPrivileged2("install", ["-d", "-m", "0755", dir]);
47200
- try {
47201
- runPrivileged2("install", ["-m", "0755", binaryPath, staging]);
47202
- runPrivileged2("mv", ["-f", staging, target]);
47203
- } catch (err) {
47204
- try {
47205
- runPrivileged2("rm", ["-f", staging]);
47206
- } catch {}
47207
- throw err;
47208
- }
47209
- if (selinuxEnabled2()) {
47210
- const root = systemBinaryRoot2();
47211
- try {
47212
- runPrivileged2("restorecon", ["-R", root]);
47213
- } catch (err) {
47214
- hookLogWarn(`restorecon on ${root} failed: ${err instanceof Error ? err.message : String(err)}`);
47215
- }
47216
- }
47217
- return target;
47218
- }
47219
- function pruneSystemBinaries2(current) {
47220
- try {
47221
- const dir = systemBinaryDir2();
47222
- const stale = readdirSync25(dir).filter((f) => f.startsWith("failproofaid-")).map((f) => resolve39(dir, f)).filter((p) => p !== current).map((p) => ({ p, mtime: statSync42(p).mtimeMs })).sort((a, b) => b.mtime - a.mtime).slice(1);
47223
- for (const { p } of stale)
47224
- runPrivileged2("rm", ["-f", p]);
47225
- } catch {}
47226
- }
47227
- function legacySystemdUserUnitPath2() {
47228
- return resolve39(homedir38(), ".config", "systemd", "user", "failproofaid.service");
47229
- }
47230
- function launchdLabel2(user = serviceUser2()) {
47231
- return `ai.failproof.failproofaid.${user}`;
47232
- }
47233
- function launchdPlistPath2(user = serviceUser2()) {
47234
- return `/Library/LaunchDaemons/${launchdLabel2(user)}.plist`;
47235
- }
47236
- function legacyLaunchAgentPlistPath2() {
47237
- return resolve39(homedir38(), "Library", "LaunchAgents", "ai.failproof.failproofaid.plist");
47238
- }
47239
- function legacySharedLaunchDaemonPath2() {
47240
- return "/Library/LaunchDaemons/ai.failproof.failproofaid.plist";
47255
+ // src/hooks/gateway-restart.ts
47256
+ import { spawn as spawn2, spawnSync } from "node:child_process";
47257
+ import { chmodSync as chmodSync15, closeSync as closeSync9, mkdirSync as mkdirSync33, openSync as openSync9, readFileSync as readFileSync45 } from "node:fs";
47258
+ import { dirname as dirname31, join as join44, resolve as resolve39 } from "node:path";
47259
+ import { homedir as homedir38 } from "node:os";
47260
+ function defaultRun(cmd, args, env) {
47261
+ const out = spawnSync(cmd, args, {
47262
+ env,
47263
+ encoding: "utf8",
47264
+ timeout: STATUS_TIMEOUT_MS,
47265
+ killSignal: "SIGKILL",
47266
+ stdio: ["ignore", "pipe", "pipe"]
47267
+ });
47268
+ return { status: out.error ? null : out.status, stdout: `${out.stdout ?? ""}${out.stderr ?? ""}` };
47241
47269
  }
47242
- function daemonStatusCommand2() {
47243
- if (!isDaemonSupportedPlatform2())
47244
- return null;
47245
- return process.platform === "linux" ? `systemctl status ${systemdUnitName2()}` : `sudo launchctl print system/${launchdLabel2()}`;
47270
+ function restartLogPath() {
47271
+ return `${logsDir()}/gateway-restart.log`;
47246
47272
  }
47247
- function primeElevation2() {
47248
- if (typeof process.getuid === "function" && process.getuid() === 0)
47249
- return true;
47250
- if (canElevate2())
47251
- return true;
47252
- try {
47253
- execFileSync3("sudo", ["-v"], { stdio: "inherit", timeout: SUDO_PROMPT_TIMEOUT_MS2 });
47254
- return canElevate2();
47255
- } catch {
47256
- return false;
47257
- }
47273
+ function openRestartLog() {
47274
+ const log = restartLogPath();
47275
+ mkdirSync33(dirname31(log), { recursive: true, mode: 448 });
47276
+ const fd = openSync9(log, "a", 384);
47277
+ chmodSync15(log, 384);
47278
+ return fd;
47258
47279
  }
47259
- function canElevate2() {
47260
- if (typeof process.getuid === "function" && process.getuid() === 0)
47261
- return true;
47280
+ function defaultSpawnDetached(cmd, args, env) {
47281
+ let fd;
47262
47282
  try {
47263
- execFileSync3("sudo", ["-n", "true"], { stdio: "ignore", timeout: SERVICE_CMD_TIMEOUT_MS2 });
47264
- return true;
47283
+ fd = openRestartLog();
47284
+ const child = spawn2(cmd, args, { env, detached: true, stdio: ["ignore", fd, fd] });
47285
+ child.on("error", () => {});
47286
+ child.unref();
47287
+ return typeof child.pid === "number";
47265
47288
  } catch {
47266
47289
  return false;
47267
- }
47268
- }
47269
- function runPrivileged2(command, args) {
47270
- const root = typeof process.getuid === "function" && process.getuid() === 0;
47271
- const [cmd, argv] = root ? [command, args] : ["sudo", ["-n", command, ...args]];
47272
- execFileSync3(cmd, argv, { stdio: "ignore", timeout: SERVICE_CMD_TIMEOUT_MS2 });
47273
- }
47274
- function writePrivilegedFile2(destination, contents, mode = "0644") {
47275
- const stagingDir = mkdtempSync2(resolve39(tmpdir3(), "failproofaid-stage-"));
47276
- const staging = resolve39(stagingDir, "service-definition");
47277
- try {
47278
- writeFileSync28(staging, contents, "utf8");
47279
- runPrivileged2("install", ["-m", mode, staging, destination]);
47280
47290
  } finally {
47281
- rmSync22(stagingDir, { recursive: true, force: true });
47282
- }
47283
- }
47284
- function removeLegacyUserService2() {
47285
- try {
47286
- if (process.platform === "linux") {
47287
- const legacy = legacySystemdUserUnitPath2();
47288
- if (!existsSync56(legacy))
47289
- return;
47290
- try {
47291
- execFileSync3("systemctl", ["--user", "disable", "--now", "failproofaid.service"], {
47292
- stdio: "ignore",
47293
- timeout: SERVICE_CMD_TIMEOUT_MS2
47294
- });
47295
- } catch {}
47296
- unlinkSync10(legacy);
47297
- try {
47298
- execFileSync3("systemctl", ["--user", "daemon-reload"], {
47299
- stdio: "ignore",
47300
- timeout: SERVICE_CMD_TIMEOUT_MS2
47301
- });
47302
- } catch {}
47303
- } else {
47304
- const legacyAgent = legacyLaunchAgentPlistPath2();
47305
- if (existsSync56(legacyAgent)) {
47306
- try {
47307
- execFileSync3("launchctl", ["unload", "-w", legacyAgent], {
47308
- stdio: "ignore",
47309
- timeout: SERVICE_CMD_TIMEOUT_MS2
47310
- });
47311
- } catch {}
47312
- unlinkSync10(legacyAgent);
47313
- }
47314
- const legacyDaemon = legacySharedLaunchDaemonPath2();
47315
- if (existsSync56(legacyDaemon)) {
47316
- try {
47317
- runPrivileged2("launchctl", ["unload", "-w", legacyDaemon]);
47318
- } catch {}
47319
- runPrivileged2("rm", ["-f", legacyDaemon]);
47320
- }
47321
- }
47322
- } catch (err) {
47323
- hookLogWarn(`could not remove the legacy user-scope daemon: ${err instanceof Error ? err.message : String(err)}`);
47324
- }
47325
- }
47326
- function systemdUnitContents2(binaryPath, workerCmd, cliCmd = null) {
47327
- const envLines = serviceEnvironment2(workerCmd, cliCmd).map(([key, value]) => `Environment="${key}=${assertUnitSafe2(value, key)}"
47328
- `).join("");
47329
- const user = assertUnitSafe2(serviceUser2(), "User");
47330
- assertUnitSafe2(binaryPath, "ExecStart");
47331
- assertUnitSafe2(homedir38(), "HOME");
47332
- const conditionPaths = [binaryPath, workerScriptPath2()].filter((p) => typeof p === "string" && existsSync56(p));
47333
- const conditionLines = conditionPaths.map((p) => `ConditionPathExists=${assertUnitSafe2(p, "ConditionPathExists")}
47334
- `).join("");
47335
- return `[Unit]
47336
- Description=failproofai background daemon (failproofaid) for ${user}
47337
- After=network.target
47338
- ${conditionLines}
47339
- [Service]
47340
- Type=simple
47341
- User=${user}
47342
- # Set explicitly rather than relying on systemd deriving it from User=:
47343
- # failproofaid stores per-user state and refuses to start without HOME, so this
47344
- # required variable is not left to a version-dependent default.
47345
- Environment="HOME=${homedir38()}"
47346
- ${envLines}ExecStart=${binaryPath}
47347
- Restart=on-failure
47348
- RestartSec=2
47349
-
47350
- [Install]
47351
- # multi-user.target, not default.target: this is the whole point of a
47352
- # system unit — it starts at boot, with no login and no lingering, and
47353
- # keeps running after the installing user logs out.
47354
- WantedBy=multi-user.target
47355
- `;
47356
- }
47357
- function escapeXml2(s) {
47358
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
47359
- }
47360
- function launchdPlistContents2(binaryPath, logDir, workerCmd, cliCmd = null) {
47361
- const env = serviceEnvironment2(workerCmd, cliCmd);
47362
- const envBlock = env.length ? ` <key>EnvironmentVariables</key>
47363
- <dict>
47364
- ${env.map(([key, value]) => ` <key>${key}</key>
47365
- <string>${escapeXml2(value)}</string>`).join(`
47366
- `)}
47367
- </dict>
47368
- ` : "";
47369
- return `<?xml version="1.0" encoding="UTF-8"?>
47370
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
47371
- <plist version="1.0">
47372
- <dict>
47373
- <key>Label</key>
47374
- <string>${escapeXml2(launchdLabel2())}</string>
47375
- <key>ProgramArguments</key>
47376
- <array>
47377
- <string>${escapeXml2(binaryPath)}</string>
47378
- </array>
47379
- <key>RunAtLoad</key>
47380
- <true/>
47381
- <key>KeepAlive</key>
47382
- <true/>
47383
- <!-- A LaunchDaemon runs as root unless told otherwise. This is the
47384
- launchd half of the systemd unit's User=: loaded at boot by the
47385
- system, executed as the one user whose home, socket and lock it
47386
- is allowed to touch. -->
47387
- <key>UserName</key>
47388
- <string>${escapeXml2(serviceUser2())}</string>
47389
- ${envBlock} <key>StandardOutPath</key>
47390
- <string>${escapeXml2(resolve39(logDir, "failproofaid.log"))}</string>
47391
- <key>StandardErrorPath</key>
47392
- <string>${escapeXml2(resolve39(logDir, "failproofaid.err.log"))}</string>
47393
- </dict>
47394
- </plist>
47395
- `;
47396
- }
47397
- function daemonInstallCommands2(binaryPath, workerCmd, cliCmd) {
47398
- if (process.platform === "linux") {
47399
- const target = systemBinaryTarget2(binaryPath);
47400
- const dir = systemBinaryDir2();
47401
- const stage = target ? [
47402
- `sudo install -d -m 0755 ${shellQuote(dir)}`,
47403
- `sudo install -m 0755 ${shellQuote(binaryPath)} ${shellQuote(target)}`,
47404
- `{ sudo restorecon -R ${shellQuote(systemBinaryRoot2())} 2>/dev/null || true; }`
47405
- ] : [];
47406
- return [
47407
- ...stage,
47408
- `sudo tee ${systemdUnitPath2()} <<'EOF'
47409
- ${systemdUnitContents2(target ?? binaryPath, workerCmd, cliCmd)}EOF`,
47410
- "sudo systemctl daemon-reload",
47411
- `sudo systemctl enable ${systemdUnitName2()}`,
47412
- `sudo systemctl restart ${systemdUnitName2()}`
47413
- ];
47291
+ if (fd !== undefined)
47292
+ closeSync9(fd);
47414
47293
  }
47415
- return [
47416
- `sudo tee ${launchdPlistPath2()} < the plist failproofai config would write`,
47417
- `sudo launchctl load -w ${launchdPlistPath2()}`
47418
- ];
47419
47294
  }
47420
- async function installDaemonService2() {
47421
- if (!isDaemonSupportedPlatform2()) {
47422
- return { installed: false, reason: `failproofaid is not supported on ${process.platform} yet` };
47423
- }
47424
- const { path: binaryPath, reason: binaryReason } = await ensureFailproofaidBinary2();
47425
- if (!binaryPath) {
47426
- return { installed: false, reason: binaryReason ?? "failproofaid binary not found for this platform" };
47427
- }
47428
- const workerCmd = resolveWorkerCommand2();
47429
- const cliCmd = resolveCliCommand2();
47430
- if (!canElevate2()) {
47431
- return {
47432
- installed: false,
47433
- reason: "root privileges are required to install the failproofaid system service, and sudo credentials were not available. " + "Re-run `failproofai config` and approve the sudo prompt — do NOT run the CLI itself under sudo, which would " + "configure root's account instead of yours. To install by hand: " + daemonInstallCommands2(binaryPath, workerCmd, cliCmd).join(" && ")
47434
- };
47435
- }
47436
- removeLegacyUserService2();
47437
- let execPath = binaryPath;
47295
+ function restartHermesGateway(profile, deps = {}) {
47438
47296
  try {
47439
- if (process.platform === "linux") {
47440
- execPath = stageSystemBinary2(binaryPath);
47441
- writePrivilegedFile2(systemdUnitPath2(), systemdUnitContents2(execPath, workerCmd, cliCmd));
47442
- runPrivileged2("systemctl", ["daemon-reload"]);
47443
- runPrivileged2("systemctl", ["enable", systemdUnitName2()]);
47444
- restartSystemdUnit2();
47445
- } else {
47446
- const plistPath = launchdPlistPath2();
47447
- const logDir = logsDir();
47448
- mkdirSync33(logDir, { recursive: true });
47449
- try {
47450
- runPrivileged2("launchctl", ["unload", plistPath]);
47451
- } catch {}
47452
- writePrivilegedFile2(plistPath, launchdPlistContents2(binaryPath, logDir, workerCmd, cliCmd));
47453
- runPrivileged2("launchctl", ["load", "-w", plistPath]);
47454
- }
47455
- } catch (err) {
47456
- const msg = err instanceof Error ? err.message : String(err);
47457
- hookLogWarn(`daemon service install failed: ${msg}`);
47458
- return { installed: false, reason: msg };
47459
- }
47460
- if (!await waitForDaemonRunning2()) {
47461
- const reason = `failproofaid was installed but did not reach a running state within ${SERVICE_START_TIMEOUT_MS2}ms (status: ${daemonServiceStatus2()})`;
47462
- hookLogWarn(`daemon service install failed: ${reason}`);
47463
- return { installed: false, reason };
47297
+ return restartHermesGatewayUnsafe(profile, deps);
47298
+ } catch {
47299
+ return { host: "hermes", profile: profile.name, status: "failed" };
47464
47300
  }
47465
- if (execPath !== binaryPath)
47466
- pruneSystemBinaries2(execPath);
47467
- return { installed: true };
47468
47301
  }
47469
- async function probeDaemon2() {
47470
- try {
47471
- await Promise.resolve().then(() => init_daemon_client2());
47472
- const deadline = Date.now() + DAEMON_PROBE_READY_TIMEOUT_MS2;
47473
- let everConnected = false;
47474
- for (;; ) {
47475
- if (await daemonAcceptsConnections()) {
47476
- everConnected = true;
47477
- const attempt = await attemptDaemonHook2({
47478
- hookEvent: "SessionStart",
47479
- cli: "claude",
47480
- stdin: JSON.stringify({
47481
- hook_event_name: "SessionStart",
47482
- source: HEALTH_PROBE_SOURCE
47483
- })
47484
- }, { responseTimeoutMs: DAEMON_PROBE_TIMEOUT_MS2 });
47485
- if (attempt.ok || attempt.failure === "protocol-mismatch")
47486
- return { ok: true };
47487
- }
47488
- if (Date.now() >= deadline)
47489
- break;
47490
- await new Promise((r) => setTimeout(r, DAEMON_PROBE_RETRY_MS2));
47491
- }
47492
- return { ok: false, reason: everConnected ? "worker" : "unreachable" };
47493
- } catch {
47494
- return { ok: false, reason: "unreachable" };
47302
+ function restartHermesGatewayUnsafe(profile, deps) {
47303
+ const run = deps.run ?? defaultRun;
47304
+ const spawnDetached = deps.spawnDetached ?? defaultSpawnDetached;
47305
+ const env = { ...process.env, HERMES_HOME: profile.home };
47306
+ const result = (status) => ({ host: "hermes", profile: profile.name, status });
47307
+ const status = run("hermes", ["gateway", "status"], env);
47308
+ if (status.status === null)
47309
+ return result("failed");
47310
+ if (HERMES_SUPERVISED.some((line) => line.test(status.stdout))) {
47311
+ return result(spawnDetached("hermes", ["gateway", "restart"], env) ? "restarting" : "failed");
47495
47312
  }
47313
+ if (/gateway service is running|\(PID \d+\)/i.test(status.stdout))
47314
+ return result("not-supervised");
47315
+ return result("not-running");
47496
47316
  }
47497
- async function daemonAcceptsConnectionsQuietly2() {
47317
+ function restartOpenClawGateway(profile, deps = {}) {
47498
47318
  try {
47499
- await Promise.resolve().then(() => init_daemon_client2());
47500
- return await daemonAcceptsConnections();
47319
+ return restartOpenClawGatewayUnsafe(profile, deps);
47501
47320
  } catch {
47502
- return false;
47321
+ return { host: "openclaw", profile: profile.name, status: "failed" };
47503
47322
  }
47504
47323
  }
47505
- async function probeDaemonEndToEnd2() {
47506
- return (await probeDaemon2()).ok;
47507
- }
47508
- async function probeDaemonPolicyEvaluation2() {
47509
- if (!await probeDaemonEndToEnd2())
47510
- return false;
47324
+ function restartOpenClawGatewayUnsafe(profile, deps) {
47325
+ const run = deps.run ?? defaultRun;
47326
+ const spawnDetached = deps.spawnDetached ?? defaultSpawnDetached;
47327
+ const profileArgs = profile.name === OPENCLAW_DEFAULT_PROFILE ? [] : ["--profile", profile.name];
47328
+ const env = openclawProfileEnv(profile);
47329
+ const result = (status) => ({ host: "openclaw", profile: profile.name, status });
47330
+ const out = run("openclaw", [...profileArgs, "gateway", "status", "--json"], env);
47331
+ if (out.status === null)
47332
+ return result("failed");
47333
+ let parsed;
47511
47334
  try {
47512
- await Promise.resolve().then(() => init_daemon_client2());
47513
- const attempt = await attemptDaemonPolicyEvaluation({
47514
- integration: "hermes",
47515
- event: "on_session_start",
47516
- payload: {
47517
- hook_event_name: "on_session_start",
47518
- source: "failproofai-native-policy-health-probe"
47519
- }
47520
- }, { responseTimeoutMs: DAEMON_PROBE_TIMEOUT_MS2 });
47521
- return attempt.ok;
47335
+ const start = out.stdout.indexOf("{");
47336
+ parsed = JSON.parse(start >= 0 ? out.stdout.slice(start) : out.stdout);
47522
47337
  } catch {
47523
- return false;
47524
- }
47525
- }
47526
- async function waitForDaemonRunning2(deps = {}) {
47527
- const status = deps.status ?? daemonServiceStatus2;
47528
- const accepts = deps.accepts ?? daemonAcceptsConnectionsQuietly2;
47529
- const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
47530
- const now = deps.now ?? Date.now;
47531
- const deadline = now() + SERVICE_START_TIMEOUT_MS2;
47532
- for (;; ) {
47533
- if (status() === "running")
47534
- break;
47535
- if (now() >= deadline)
47536
- return false;
47537
- await sleep(SERVICE_START_POLL_MS2);
47538
- }
47539
- const settleUntil = now() + SERVICE_SETTLE_MS2;
47540
- for (;; ) {
47541
- if (status() !== "running")
47542
- return false;
47543
- if (await accepts())
47544
- return true;
47545
- if (now() >= settleUntil)
47546
- return true;
47547
- await sleep(SERVICE_START_POLL_MS2);
47338
+ return result("failed");
47548
47339
  }
47340
+ if (parsed.service?.runtime?.status !== "running")
47341
+ return result("not-running");
47342
+ if (parsed.service.loaded !== true)
47343
+ return result("not-supervised");
47344
+ const help = run("openclaw", ["gateway", "restart", "--help"], env);
47345
+ if (!/--safe\b/.test(help.stdout))
47346
+ return result("not-supervised");
47347
+ return result(spawnDetached("openclaw", [...profileArgs, "gateway", "restart", "--safe"], env) ? "restarting" : "failed");
47549
47348
  }
47550
- function restartSystemdUnit2() {
47551
- try {
47552
- runPrivileged2("systemctl", ["reset-failed", systemdUnitName2()]);
47553
- } catch {}
47554
- runPrivileged2("systemctl", ["restart", systemdUnitName2()]);
47555
- }
47556
- async function refreshDaemonToCliVersion(deps = {}) {
47557
- const status = deps.status ?? daemonServiceStatus2;
47558
- const install = deps.install ?? installDaemonService2;
47559
- const prime = deps.prime ?? primeElevation2;
47560
- const interactive = deps.interactive ?? (() => Boolean(process.stdin.isTTY && process.stdout.isTTY));
47561
- const current = status();
47562
- if (current === "not-installed") {
47563
- return { ok: true, lines: ["No failproofaid service on this machine; nothing to update."] };
47349
+ function openclawProfileEnv(profile, base = process.env) {
47350
+ const env = { ...base };
47351
+ for (const key of ["OPENCLAW_PROFILE", "OPENCLAW_STATE_DIR", "OPENCLAW_HOME", "OPENCLAW_CONFIG_PATH"]) {
47352
+ delete env[key];
47564
47353
  }
47565
- const recorded = readVersionFile()?.daemon;
47566
- if (current === "running" && recorded === version2 && existsSync56(installedBinaryPath(version2))) {
47567
- return { ok: true, lines: [`failproofaid ${version2} is already installed and running; nothing to update.`] };
47354
+ if (profile.name === OPENCLAW_DEFAULT_PROFILE && resolve39(profile.home) !== resolve39(homedir38(), ".openclaw")) {
47355
+ env.OPENCLAW_STATE_DIR = profile.home;
47568
47356
  }
47569
- if (interactive())
47570
- prime();
47571
- const result = await install();
47572
- if (!result.installed) {
47573
- const needsRoot = /root privileges are required/.test(result.reason ?? "");
47574
- return {
47575
- ok: false,
47576
- lines: needsRoot ? [
47577
- `✕ failproofaid ${version2} was not installed: root privileges are required. The previous daemon is untouched.`,
47578
- " Run `sudo -v` and then `failproofai update` again."
47579
- ] : [
47580
- `✕ failproofaid ${version2} could not be installed: ${(result.reason ?? "unknown reason").replace(/\.$/, "")}. The previous daemon is untouched.`,
47581
- ` See why with \`${daemonStatusCommand2() ?? "systemctl status"}\`.`
47582
- ]
47583
- };
47584
- }
47585
- writeVersionFile({ daemon: version2 });
47586
- return {
47587
- ok: true,
47588
- lines: [`failproofaid ${version2} installed, service restarted and holding.`]
47589
- };
47590
- }
47591
- function inactiveLinuxStatus2() {
47592
- try {
47593
- return interpretConditionResult2(execFileSync3("systemctl", ["show", systemdUnitName2(), "--property=ConditionResult", "--value"], { stdio: ["ignore", "pipe", "ignore"], timeout: SERVICE_CMD_TIMEOUT_MS2 }).toString());
47594
- } catch {
47595
- return "stopped";
47596
- }
47597
- }
47598
- function interpretConditionResult2(raw) {
47599
- return raw.trim() === "no" ? "condition-failed" : "stopped";
47357
+ return env;
47600
47358
  }
47601
- function daemonServiceStatus2() {
47602
- if (!isDaemonSupportedPlatform2())
47603
- return "unsupported-platform";
47604
- if (process.platform === "linux") {
47605
- if (!existsSync56(systemdUnitPath2()))
47606
- return "not-installed";
47359
+ function openclawProfilesUsingFailproofai() {
47360
+ return listOpenClawProfiles().filter((profile) => {
47607
47361
  try {
47608
- const out = execFileSync3("systemctl", ["is-active", systemdUnitName2()], {
47609
- stdio: ["ignore", "pipe", "ignore"],
47610
- timeout: SERVICE_CMD_TIMEOUT_MS2
47611
- }).toString().trim();
47612
- return out === "active" ? "running" : inactiveLinuxStatus2();
47362
+ const settings = JSON.parse(readFileSync45(join44(profile.home, "openclaw.json"), "utf8"));
47363
+ return settings.plugins?.entries?.[OPENCLAW_PLUGIN_ID2]?.enabled === true;
47613
47364
  } catch {
47614
- return inactiveLinuxStatus2();
47365
+ return false;
47615
47366
  }
47616
- }
47617
- const plistPath = launchdPlistPath2();
47618
- if (!existsSync56(plistPath))
47619
- return "not-installed";
47620
- try {
47621
- const root = typeof process.getuid === "function" && process.getuid() === 0;
47622
- if (!root && !canElevate2())
47623
- return "unknown";
47624
- const args = ["print", `system/${launchdLabel2()}`];
47625
- const out = root ? execFileSync3("launchctl", args, {
47626
- stdio: ["ignore", "pipe", "ignore"],
47627
- timeout: SERVICE_CMD_TIMEOUT_MS2
47628
- }).toString() : execFileSync3("sudo", ["-n", "launchctl", ...args], {
47629
- stdio: ["ignore", "pipe", "ignore"],
47630
- timeout: SERVICE_CMD_TIMEOUT_MS2
47631
- }).toString();
47632
- return /state\s*=\s*running/.test(out) ? "running" : "stopped";
47633
- } catch {
47634
- return "stopped";
47635
- }
47367
+ });
47636
47368
  }
47637
- var SERVICE_CMD_TIMEOUT_MS2 = 1e4, SERVICE_START_TIMEOUT_MS2 = 5000, SERVICE_START_POLL_MS2 = 100, SERVICE_SETTLE_MS2 = 750, SUDO_PROMPT_TIMEOUT_MS2 = 120000, UNIT_UNSAFE_RE2, DAEMON_PROBE_TIMEOUT_MS2 = 5000, DAEMON_PROBE_READY_TIMEOUT_MS2 = 1e4, DAEMON_PROBE_RETRY_MS2 = 150;
47638
- var init_daemon_service2 = __esm(() => {
47639
- init_hook_logger();
47640
- init_daemon_download();
47369
+ function restartOpenClawGateways(deps = {}) {
47370
+ const profiles = (deps.openclawProfiles ?? openclawProfilesUsingFailproofai)();
47371
+ return profiles.map((profile) => restartOpenClawGateway(profile, deps));
47372
+ }
47373
+ function openclawRestartLines(restarts) {
47374
+ const rows = restarts.filter((r) => GATEWAY_STATUS_LABEL[r.status]);
47375
+ if (rows.length === 0)
47376
+ return [];
47377
+ const width = Math.max(...rows.map((r) => `openclaw/${r.profile}`.length));
47378
+ return [
47379
+ "OpenClaw:",
47380
+ ...rows.map((r) => ` ${`openclaw/${r.profile}`.padEnd(width)} ${GATEWAY_STATUS_LABEL[r.status]}`)
47381
+ ];
47382
+ }
47383
+ var OPENCLAW_PLUGIN_ID2 = "failproofai", STATUS_TIMEOUT_MS = 20000, HERMES_SUPERVISED, GATEWAY_STATUS_LABEL;
47384
+ var init_gateway_restart = __esm(() => {
47385
+ init_openclaw_profiles();
47641
47386
  init_fp_home();
47642
- init_package();
47643
- init_fp_config();
47644
- UNIT_UNSAFE_RE2 = /["\\\r\n]/;
47387
+ HERMES_SUPERVISED = [/user gateway service is running/i, /supervised by launchd \(PID/i];
47388
+ GATEWAY_STATUS_LABEL = {
47389
+ restarting: "gateway restarting",
47390
+ "not-running": "",
47391
+ "not-supervised": "restart the gateway",
47392
+ failed: "restart the gateway"
47393
+ };
47645
47394
  });
47646
47395
 
47647
47396
  // src/hooks/hermes-update.ts
@@ -47652,15 +47401,21 @@ async function runHermesUpdateMigration(deps) {
47652
47401
  return { ok: true, lines: [], profiles };
47653
47402
  const width = Math.max(...profiles.map((p) => ("hermes/" + p.name).length));
47654
47403
  const lines = ["Hermes:"];
47404
+ let restarting = false;
47655
47405
  for (const p of profiles) {
47656
47406
  const label = ("hermes/" + p.name).padEnd(width);
47657
47407
  const detail = p.status === "current" ? "" : ` — ${p.detail}`;
47658
- lines.push(` ${label} ${STATUS_LABEL[p.status]}${detail}`);
47408
+ const loaded = p.status === "migrated" || p.status === "current";
47409
+ const restart = loaded && deps.restartGateway ? deps.restartGateway(p).status : null;
47410
+ if (restart === "restarting")
47411
+ restarting = true;
47412
+ const gateway = restart ? GATEWAY_STATUS_LABEL[restart] : "";
47413
+ lines.push(` ${label} ${STATUS_LABEL[p.status]}${detail}${gateway ? `, ${gateway}` : ""}`);
47659
47414
  }
47660
47415
  const blocked = profiles.filter((p) => p.status === "blocked");
47661
47416
  const failed = profiles.filter((p) => p.status === "failed");
47662
47417
  if (profiles.some((p) => p.status === "migrated")) {
47663
- lines.push(" Cron jobs load the plugin on their next run; restart running Hermes gateways and sessions to load it there.");
47418
+ lines.push(restarting ? " Cron jobs load the plugin on their next run; restart running Hermes sessions to load it there." : " Cron jobs load the plugin on their next run; restart running Hermes gateways and sessions to load it there.");
47664
47419
  }
47665
47420
  if (blocked.length > 0) {
47666
47421
  lines.push("", `Hermes is NOT migrated (${blocked.map((p) => p.name).join(", ")}): the running failproofaid cannot`, "answer the native plugin (no policyEvaluation), so nothing was changed. Profiles still on", "shell hooks do NOT check Hermes cron jobs. Run `failproofai config` (it asks for sudo to", "replace the daemon), then `failproofai update` again.");
@@ -47673,6 +47428,7 @@ async function runHermesUpdateMigration(deps) {
47673
47428
  var STATUS_LABEL;
47674
47429
  var init_hermes_update = __esm(() => {
47675
47430
  init_integrations();
47431
+ init_gateway_restart();
47676
47432
  STATUS_LABEL = {
47677
47433
  migrated: "migrated",
47678
47434
  current: "already current",
@@ -47682,8 +47438,176 @@ var init_hermes_update = __esm(() => {
47682
47438
  };
47683
47439
  });
47684
47440
 
47441
+ // src/hooks/update-run.ts
47442
+ import { existsSync as existsSync56, mkdirSync as mkdirSync34, readFileSync as readFileSync46, writeFileSync as writeFileSync28 } from "node:fs";
47443
+ import { dirname as dirname32 } from "node:path";
47444
+ async function runUpdateSteps(opts) {
47445
+ const lines = [];
47446
+ let migrationsRan = 0;
47447
+ let migrationFailed = false;
47448
+ let changed = false;
47449
+ if (opts.layout) {
47450
+ await Promise.resolve().then(() => init_fp_config());
47451
+ await Promise.resolve().then(() => init_fp_home());
47452
+ await Promise.resolve().then(() => init_migrations());
47453
+ const state = detectLayout();
47454
+ if (state.kind === "future") {
47455
+ return {
47456
+ lines: [],
47457
+ ok: false,
47458
+ futureLayout: { found: state.found, speaks: LAYOUT_VERSION },
47459
+ migrationsRan: 0,
47460
+ migrationFailed: false,
47461
+ hermesOk: true,
47462
+ hermesMigrated: 0,
47463
+ changed: false,
47464
+ restarts: []
47465
+ };
47466
+ }
47467
+ if (state.kind === "stale") {
47468
+ const run = runMigrations(state.found);
47469
+ migrationsRan = run.steps.length;
47470
+ migrationFailed = Boolean(run.failed);
47471
+ changed = changed || migrationsRan > 0;
47472
+ for (const step of run.steps) {
47473
+ lines.push(` ${step.ok ? "migrated" : "FAILED "} layout ${step.from} → ${step.to}`);
47474
+ }
47475
+ if (run.backedUp.length > 0)
47476
+ lines.push("", `Saved first: ${run.backedUp.join(", ")}`);
47477
+ if (run.failed) {
47478
+ lines.push("", `✕ Step ${run.failed.from} → ${run.failed.to} did not finish: ${run.failed.error}`, ` The home is still marked layout ${state.found} and will be retried.`);
47479
+ }
47480
+ } else {
47481
+ lines.push(`Home is at layout ${LAYOUT_VERSION}; no migration was needed.`);
47482
+ }
47483
+ }
47484
+ let daemonOk = true;
47485
+ const svc = await Promise.resolve().then(() => (init_daemon_service(), {}));
47486
+ if (opts.noteSkippedDaemon) {
47487
+ lines.push("", "Skipped the daemon (--no-daemon). Its version may not match this CLI.");
47488
+ } else if (opts.daemon) {
47489
+ if (!isDaemonSupportedPlatform()) {
47490
+ lines.push("", `failproofaid does not run on ${process.platform}; nothing to update.`);
47491
+ } else {
47492
+ const result = await refreshDaemonToCliVersion();
47493
+ lines.push("", ...result.lines);
47494
+ daemonOk = result.ok;
47495
+ changed = changed || !result.lines.some((l) => /nothing to update/.test(l));
47496
+ }
47497
+ }
47498
+ const restartsGateways = opts.restart && daemonOk && isDaemonSupportedPlatform() && daemonServiceStatus() === "running";
47499
+ let hermesOk = true;
47500
+ let hermesMigrated = 0;
47501
+ const restarts = [];
47502
+ try {
47503
+ await Promise.resolve().then(() => init_hermes_update());
47504
+ const restart = await Promise.resolve().then(() => (init_gateway_restart(), {}));
47505
+ const hermesResult = await runHermesUpdateMigration({
47506
+ daemonSupportsPolicyEvaluation: () => probeDaemonPolicyEvaluation(),
47507
+ restartGateway: restartsGateways ? (p) => {
47508
+ const r = restartHermesGateway(p);
47509
+ restarts.push(r);
47510
+ return r;
47511
+ } : undefined
47512
+ });
47513
+ if (hermesResult.lines.length > 0) {
47514
+ const [heading, ...rest] = hermesResult.lines;
47515
+ lines.push("", hermesResult.ok ? heading : `✕ ${heading}`, ...rest);
47516
+ }
47517
+ hermesOk = hermesResult.ok;
47518
+ hermesMigrated = hermesResult.profiles.filter((p) => p.status === "migrated").length;
47519
+ changed = changed || !hermesOk || hermesMigrated > 0 || mentionsGateway(hermesResult.lines);
47520
+ } catch (err) {
47521
+ lines.push("", `✕ Hermes migration failed: ${err instanceof Error ? err.message : String(err)}`);
47522
+ hermesOk = false;
47523
+ }
47524
+ if (restartsGateways) {
47525
+ try {
47526
+ const restart = await Promise.resolve().then(() => (init_gateway_restart(), {}));
47527
+ const openclaw = restartOpenClawGateways();
47528
+ restarts.push(...openclaw);
47529
+ const restartLines = openclawRestartLines(openclaw);
47530
+ if (restartLines.length > 0) {
47531
+ lines.push("", ...restartLines);
47532
+ changed = true;
47533
+ }
47534
+ } catch {}
47535
+ }
47536
+ return {
47537
+ lines,
47538
+ ok: daemonOk && !migrationFailed && hermesOk,
47539
+ migrationsRan,
47540
+ migrationFailed,
47541
+ hermesOk,
47542
+ hermesMigrated,
47543
+ changed,
47544
+ restarts
47545
+ };
47546
+ }
47547
+ function setupGatewayLine(restarts) {
47548
+ const named = (r) => `${r.host}/${r.profile}`;
47549
+ const manual = restarts.filter((r) => r.status === "not-supervised" || r.status === "failed").map(named);
47550
+ if (manual.length > 0)
47551
+ return { ok: false, text: `${manual.join(", ")}: restart the gateway` };
47552
+ const restarting = restarts.filter((r) => r.status === "restarting").map(named);
47553
+ if (restarting.length > 0)
47554
+ return { ok: true, text: `${restarting.join(", ")}: gateway restarting` };
47555
+ return null;
47556
+ }
47557
+ async function pluggedProfiles() {
47558
+ await Promise.resolve().then(() => init_integrations());
47559
+ await Promise.resolve().then(() => init_gateway_restart());
47560
+ return [
47561
+ ...hermesProfileHealth().filter((p) => p.pluginInstalled && p.pluginEnabled && !p.pluginDisabled).map((p) => ({ host: "hermes", name: p.name, home: p.home })),
47562
+ ...openclawProfilesUsingFailproofai().map((p) => ({ host: "openclaw", ...p }))
47563
+ ];
47564
+ }
47565
+ async function restartNewlyPlugged(before, deps = {}) {
47566
+ const key = (p) => `${p.host}/${p.name}`;
47567
+ const had = new Set(before.map(key));
47568
+ const fresh = (await (deps.plugged ?? pluggedProfiles)()).filter((p) => !had.has(key(p)));
47569
+ if (fresh.length === 0)
47570
+ return [];
47571
+ const daemonRunning = deps.daemonRunning ?? (async () => {
47572
+ const svc = await Promise.resolve().then(() => (init_daemon_service(), {}));
47573
+ return isDaemonSupportedPlatform() && daemonServiceStatus() === "running";
47574
+ });
47575
+ if (!await daemonRunning())
47576
+ return [];
47577
+ const restart = await Promise.resolve().then(() => (init_gateway_restart(), {}));
47578
+ const hermes = deps.restartHermes ?? ((p) => restartHermesGateway(p));
47579
+ const openclaw = deps.restartOpenClaw ?? ((p) => restartOpenClawGateway(p));
47580
+ return fresh.map((p) => p.host === "hermes" ? hermes(p) : openclaw(p));
47581
+ }
47582
+ function mentionsGateway(lines) {
47583
+ return lines.some((l) => /gateway/.test(l));
47584
+ }
47585
+ function readUpdatedVersion(home) {
47586
+ try {
47587
+ const v = readFileSync46(updatedVersionFile(home), "utf8").trim();
47588
+ return v.length > 0 ? v : null;
47589
+ } catch {
47590
+ return null;
47591
+ }
47592
+ }
47593
+ function markUpdated(version, home) {
47594
+ try {
47595
+ const file = updatedVersionFile(home);
47596
+ if (!existsSync56(dirname32(file)))
47597
+ mkdirSync34(dirname32(file), { recursive: true, mode: 448 });
47598
+ writeFileSync28(file, `${version}
47599
+ `, { mode: 384 });
47600
+ } catch {}
47601
+ }
47602
+ function setupNeedsUpdateSteps(version, home) {
47603
+ return readUpdatedVersion(home) !== version;
47604
+ }
47605
+ var init_update_run = __esm(() => {
47606
+ init_fp_home();
47607
+ });
47608
+
47685
47609
  // src/hooks/uninstall-cli.ts
47686
- import { existsSync as existsSync57, rmSync as rmSync23 } from "node:fs";
47610
+ import { existsSync as existsSync57, rmSync as rmSync22 } from "node:fs";
47687
47611
  function survey(cwd) {
47688
47612
  const clis = [];
47689
47613
  for (const id of listInstallableIds()) {
@@ -47859,7 +47783,7 @@ Remove it as root:
47859
47783
  }
47860
47784
  if (purging) {
47861
47785
  try {
47862
- rmSync23(home, { recursive: true, force: true });
47786
+ rmSync22(home, { recursive: true, force: true });
47863
47787
  purged = true;
47864
47788
  lines.push(kit.ok(`Deleted ${home}.`));
47865
47789
  } catch (err) {
@@ -47902,11 +47826,11 @@ var init_uninstall_cli = __esm(() => {
47902
47826
  });
47903
47827
 
47904
47828
  // src/hooks/pack-cli.ts
47905
- import { execFileSync as execFileSync4 } from "node:child_process";
47906
- import { homedir as homedir39, tmpdir as tmpdir4 } from "node:os";
47829
+ import { execFileSync as execFileSync3 } from "node:child_process";
47830
+ import { homedir as homedir39, tmpdir as tmpdir3 } from "node:os";
47907
47831
  import { createHash as createHash14 } from "node:crypto";
47908
- import { copyFileSync as copyFileSync5, existsSync as existsSync58, mkdirSync as mkdirSync34, mkdtempSync as mkdtempSync3, readFileSync as readFileSync46, readdirSync as readdirSync26, realpathSync as realpathSync5, rmSync as rmSync24, statSync as statSync43, writeFileSync as writeFileSync29 } from "node:fs";
47909
- import { basename as basename11, dirname as dirname32, isAbsolute as isAbsolute6, join as join44, relative as relative5, resolve as resolve40, sep as sep6 } from "node:path";
47832
+ import { copyFileSync as copyFileSync5, existsSync as existsSync58, mkdirSync as mkdirSync35, mkdtempSync as mkdtempSync2, readFileSync as readFileSync47, readdirSync as readdirSync25, realpathSync as realpathSync6, rmSync as rmSync23, statSync as statSync42, writeFileSync as writeFileSync29 } from "node:fs";
47833
+ import { basename as basename11, dirname as dirname33, isAbsolute as isAbsolute6, join as join45, relative as relative5, resolve as resolve40, sep as sep6 } from "node:path";
47910
47834
  function parseList(rest, ...flags) {
47911
47835
  let found = false;
47912
47836
  const out = [];
@@ -48044,7 +47968,7 @@ async function build(rest) {
48044
47968
  const entryPath = resolve40(entry);
48045
47969
  if (!existsSync58(entryPath))
48046
47970
  return fail3([`No such file: ${entryPath}`]);
48047
- const source = readFileSync46(entryPath, "utf8");
47971
+ const source = readFileSync47(entryPath, "utf8");
48048
47972
  const localImport = firstRelativeSpecifier(source);
48049
47973
  if (localImport) {
48050
47974
  return fail3([
@@ -48163,14 +48087,14 @@ async function build(rest) {
48163
48087
  ...semantic.length > 0 ? { semantic } : {}
48164
48088
  }, null, 2) + `
48165
48089
  `;
48166
- mkdirSync34(outDir, { recursive: true });
48090
+ mkdirSync35(outDir, { recursive: true });
48167
48091
  const manifestPath = resolve40(outDir, PACK_MANIFEST_ASSET);
48168
48092
  const entryOut = resolve40(outDir, PACK_ENTRY_ASSET);
48169
48093
  writeFileSync29(manifestPath, manifest, "utf8");
48170
48094
  copyFileSync5(entryPath, entryOut);
48171
48095
  const sha = (bytes) => createHash14("sha256").update(bytes).digest("hex");
48172
48096
  writeFileSync29(resolve40(outDir, PACK_CHECKSUMS_ASSET), `${sha(manifest)} ${PACK_MANIFEST_ASSET}
48173
- ${sha(readFileSync46(entryOut))} ${PACK_ENTRY_ASSET}
48097
+ ${sha(readFileSync47(entryOut))} ${PACK_ENTRY_ASSET}
48174
48098
  `, "utf8");
48175
48099
  const on = policies.filter((p) => p.defaultEnabled).length;
48176
48100
  const semanticOnly = policies.length === 0 && semantic.length > 0;
@@ -48315,7 +48239,7 @@ async function scaffold(target) {
48315
48239
  if (existsSync58(path)) {
48316
48240
  return fail3([`${path} already exists — name a different file, or edit that one.`]);
48317
48241
  }
48318
- mkdirSync34(resolve40(path, ".."), { recursive: true });
48242
+ mkdirSync35(resolve40(path, ".."), { recursive: true });
48319
48243
  writeFileSync29(path, `import { customPolicies, allow, deny } from "failproofai";
48320
48244
 
48321
48245
  // One file, no relative imports: only this entry is digest-pinned, so a pack
@@ -48352,7 +48276,7 @@ customPolicies.add({
48352
48276
  }
48353
48277
  function inferRepo(entryPath) {
48354
48278
  try {
48355
- const url = execFileSync4("git", ["remote", "get-url", "origin"], {
48279
+ const url = execFileSync3("git", ["remote", "get-url", "origin"], {
48356
48280
  cwd: resolve40(entryPath, ".."),
48357
48281
  encoding: "utf8",
48358
48282
  stdio: ["ignore", "pipe", "ignore"],
@@ -48368,7 +48292,7 @@ function inferCommit(entryPath, outDir, sources) {
48368
48292
  const cwd = resolve40(entryPath, "..");
48369
48293
  const raw = (args) => {
48370
48294
  try {
48371
- return execFileSync4("git", args, {
48295
+ return execFileSync3("git", args, {
48372
48296
  cwd,
48373
48297
  encoding: "utf8",
48374
48298
  stdio: ["ignore", "pipe", "ignore"],
@@ -48414,7 +48338,7 @@ function porcelainEntries(status) {
48414
48338
  }
48415
48339
  function realOrSelf(path) {
48416
48340
  try {
48417
- return realpathSync5(path);
48341
+ return realpathSync6(path);
48418
48342
  } catch {
48419
48343
  return path;
48420
48344
  }
@@ -48469,7 +48393,7 @@ function inferTaggedVersion(entryPath, sources) {
48469
48393
  const cwd = resolve40(entryPath, "..");
48470
48394
  const raw = (args) => {
48471
48395
  try {
48472
- return execFileSync4("git", args, {
48396
+ return execFileSync3("git", args, {
48473
48397
  cwd,
48474
48398
  encoding: "utf8",
48475
48399
  stdio: ["ignore", "pipe", "ignore"],
@@ -48496,7 +48420,7 @@ function inferTaggedVersion(entryPath, sources) {
48496
48420
  function findEntry(dir) {
48497
48421
  let names;
48498
48422
  try {
48499
- names = readdirSync26(dir);
48423
+ names = readdirSync25(dir);
48500
48424
  } catch {
48501
48425
  return [];
48502
48426
  }
@@ -48506,9 +48430,9 @@ function findEntry(dir) {
48506
48430
  continue;
48507
48431
  const full = resolve40(dir, name);
48508
48432
  try {
48509
- if (statSync43(full).size > 512 * 1024)
48433
+ if (statSync42(full).size > 512 * 1024)
48510
48434
  continue;
48511
- const text = readFileSync46(full, "utf8");
48435
+ const text = readFileSync47(full, "utf8");
48512
48436
  if (/from\s+["']failproofai["']/.test(text) && /(?:customPolicies|semanticPolicies)\s*\.\s*add\s*\(/.test(text)) {
48513
48437
  found.push(full);
48514
48438
  }
@@ -48525,21 +48449,21 @@ function withLocalImports(sources) {
48525
48449
  const file = queue.shift();
48526
48450
  let text;
48527
48451
  try {
48528
- if (statSync43(file).size > 512 * 1024)
48452
+ if (statSync42(file).size > 512 * 1024)
48529
48453
  continue;
48530
- text = readFileSync46(file, "utf8");
48454
+ text = readFileSync47(file, "utf8");
48531
48455
  } catch {
48532
48456
  continue;
48533
48457
  }
48534
48458
  for (const re of LOCAL_IMPORT_RES) {
48535
48459
  for (const match of text.matchAll(re)) {
48536
- const base = resolve40(dirname32(file), match[1]);
48460
+ const base = resolve40(dirname33(file), match[1]);
48537
48461
  for (const ext of LOCAL_IMPORT_EXTENSIONS) {
48538
48462
  const candidate = base + ext;
48539
48463
  if (seen.has(candidate))
48540
48464
  break;
48541
48465
  try {
48542
- if (!statSync43(candidate).isFile())
48466
+ if (!statSync42(candidate).isFile())
48543
48467
  continue;
48544
48468
  } catch {
48545
48469
  continue;
@@ -48557,7 +48481,7 @@ function settleGitState(entryPath, provenance, packFiles, id, outDir) {
48557
48481
  const cwd = resolve40(entryPath, "..");
48558
48482
  const raw = (args) => {
48559
48483
  try {
48560
- return execFileSync4("git", args, {
48484
+ return execFileSync3("git", args, {
48561
48485
  cwd,
48562
48486
  encoding: "utf8",
48563
48487
  stdio: ["ignore", "pipe", "pipe"],
@@ -48750,7 +48674,7 @@ async function ensureRepo(owner, name, id, token, sourceDir) {
48750
48674
  function pushExistingHistory(dir, owner, name, token) {
48751
48675
  const git = (args, env) => {
48752
48676
  try {
48753
- return execFileSync4("git", args, {
48677
+ return execFileSync3("git", args, {
48754
48678
  cwd: dir,
48755
48679
  encoding: "utf8",
48756
48680
  stdio: ["ignore", "pipe", "ignore"],
@@ -48764,7 +48688,7 @@ function pushExistingHistory(dir, owner, name, token) {
48764
48688
  const branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
48765
48689
  if (!branch || branch === "HEAD" || !git(["rev-parse", "--verify", "HEAD"]))
48766
48690
  return false;
48767
- const askpass = join44(mkdtempSync3(join44(tmpdir4(), "fpai-askpass-")), "askpass.sh");
48691
+ const askpass = join45(mkdtempSync2(join45(tmpdir3(), "fpai-askpass-")), "askpass.sh");
48768
48692
  try {
48769
48693
  writeFileSync29(askpass, `#!/bin/sh
48770
48694
  case "$1" in
@@ -48786,7 +48710,7 @@ esac
48786
48710
  return true;
48787
48711
  } finally {
48788
48712
  try {
48789
- rmSync24(dirname32(askpass), { recursive: true, force: true });
48713
+ rmSync23(dirname33(askpass), { recursive: true, force: true });
48790
48714
  } catch {}
48791
48715
  }
48792
48716
  }
@@ -48817,7 +48741,7 @@ function findBun() {
48817
48741
  ].filter((c) => c !== null);
48818
48742
  for (const candidate of candidates) {
48819
48743
  try {
48820
- execFileSync4(candidate, ["--version"], { stdio: "ignore", timeout: 5000 });
48744
+ execFileSync3(candidate, ["--version"], { stdio: "ignore", timeout: 5000 });
48821
48745
  return candidate;
48822
48746
  } catch {
48823
48747
  continue;
@@ -48837,14 +48761,14 @@ function bundleEntry(sources, outDir) {
48837
48761
  ]
48838
48762
  };
48839
48763
  }
48840
- mkdirSync34(outDir, { recursive: true });
48764
+ mkdirSync35(outDir, { recursive: true });
48841
48765
  const entry = resolve40(outDir, ".entry.generated.mjs");
48842
48766
  writeFileSync29(entry, sources.map((f) => `import ${JSON.stringify(f.startsWith("/") ? f : resolve40(f))};`).join(`
48843
48767
  `) + `
48844
48768
  `, "utf8");
48845
48769
  const bundled = resolve40(outDir, ".bundled.mjs");
48846
48770
  try {
48847
- execFileSync4(bun, [
48771
+ execFileSync3(bun, [
48848
48772
  "build",
48849
48773
  "--target=node",
48850
48774
  "--format=esm",
@@ -48888,7 +48812,7 @@ function githubToken() {
48888
48812
  if (fromEnv)
48889
48813
  return fromEnv.trim();
48890
48814
  try {
48891
- const out = execFileSync4("gh", ["auth", "token"], {
48815
+ const out = execFileSync3("gh", ["auth", "token"], {
48892
48816
  encoding: "utf8",
48893
48817
  stdio: ["ignore", "pipe", "ignore"],
48894
48818
  timeout: 5000
@@ -49055,7 +48979,7 @@ async function publish(rest) {
49055
48979
  }
49056
48980
  const tag = flag("tag") ?? version;
49057
48981
  let entryToBuild = entry;
49058
- const needsBundle = discovered.length > 1 || firstRelativeSpecifier(readFileSync46(entry, "utf8")) !== null;
48982
+ const needsBundle = discovered.length > 1 || firstRelativeSpecifier(readFileSync47(entry, "utf8")) !== null;
49059
48983
  if (needsBundle) {
49060
48984
  const sources = discovered.length > 1 ? discovered : [entry];
49061
48985
  const bundled = bundleEntry(sources, outDirEarly);
@@ -49136,7 +49060,7 @@ async function publish(rest) {
49136
49060
  if (prior) {
49137
49061
  await gh(`${GITHUB_API2}/repos/${owner}/${name}/releases/assets/${prior.id}`, auth, { method: "DELETE" });
49138
49062
  }
49139
- const bytes = readFileSync46(resolve40(outDir, asset));
49063
+ const bytes = readFileSync47(resolve40(outDir, asset));
49140
49064
  const upload = await gh(`${GITHUB_UPLOADS2}/repos/${owner}/${name}/releases/${releaseId}/assets?name=${encodeURIComponent(asset)}`, auth, {
49141
49065
  method: "POST",
49142
49066
  contentType: asset.endsWith(".json") ? "application/json" : "application/octet-stream",
@@ -50010,13 +49934,15 @@ function integrationsInstalledAt2(scope, cwd) {
50010
49934
  function cloudPolicyStatus2() {
50011
49935
  let count = 0;
50012
49936
  let observing = false;
49937
+ let observingCount = 0;
50013
49938
  const jsIds = new Set;
50014
49939
  try {
50015
49940
  for (const artifact of listActiveCloudManagedPolicies()) {
50016
49941
  jsIds.add(artifact.id);
50017
- if (artifact.effect === "observe")
49942
+ if (artifact.effect === "observe") {
50018
49943
  observing = true;
50019
- else
49944
+ observingCount++;
49945
+ } else
50020
49946
  count++;
50021
49947
  }
50022
49948
  } catch {}
@@ -50026,14 +49952,15 @@ function cloudPolicyStatus2() {
50026
49952
  for (const assignment of readCloudJevAssignments() ?? []) {
50027
49953
  if (jsIds.has(assignment.id))
50028
49954
  continue;
50029
- if (jevMode === "observe" || assignment.effect === "observe")
49955
+ if (jevMode === "observe" || assignment.effect === "observe") {
50030
49956
  observing = true;
50031
- else
49957
+ observingCount++;
49958
+ } else
50032
49959
  count++;
50033
49960
  }
50034
49961
  }
50035
49962
  } catch {}
50036
- return { count, observing };
49963
+ return { count, observing, observingCount };
50037
49964
  }
50038
49965
  function notEnforcingReason2(cwd) {
50039
49966
  const wired = deduplicateScopes2(HOOK_SCOPES, cwd).some((scope) => hooksInstalledInSettings2(scope, cwd));
@@ -50517,6 +50444,16 @@ async function removeHooks2(policyNames, scope = "user", cwd, opts) {
50517
50444
  }
50518
50445
  untraceRemoved();
50519
50446
  }
50447
+ function cloudDashboardUrl2() {
50448
+ const fromEnv = process.env.FAILPROOFAI_CLOUD_URL?.trim();
50449
+ if (fromEnv)
50450
+ return fromEnv;
50451
+ try {
50452
+ return readCloudCredentials()?.url || undefined;
50453
+ } catch {
50454
+ return;
50455
+ }
50456
+ }
50520
50457
  function renderPoliciesScreen(screen, opts = {}) {
50521
50458
  const kit = screenKit(opts);
50522
50459
  const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
@@ -50550,7 +50487,9 @@ function renderPoliciesScreen(screen, opts = {}) {
50550
50487
  const { failed, text, fix } = screen.attention;
50551
50488
  out.push(failed ? kit.fail(text, fix) : kit.caution(text, fix));
50552
50489
  }
50553
- if (empty) {
50490
+ if (empty && screen.cloudDashboard) {
50491
+ out.push(`${INDENT}Deploy from Cloud: ${kit.cmd(screen.cloudDashboard)}`);
50492
+ } else if (empty) {
50554
50493
  out.push(`${INDENT}Turn on ours: ${kit.cmd(`failproofai policies add ${CORE_SOURCE}`)}`, `${INDENT}Or anyone's: ${kit.cmd("failproofai policies add <owner>/<repo>")}`);
50555
50494
  }
50556
50495
  const sectioned = screen.packs.filter((pack) => pack.policies.length > 0);
@@ -50844,7 +50783,7 @@ async function listHooks(cwd, { all = false } = {}) {
50844
50783
  name: p.name,
50845
50784
  description: p.description
50846
50785
  }));
50847
- printBlock(process.stdout, renderPoliciesScreen({ packs, refused, attention, custom, convention, cloud, legacy }, { ...optsFor(process.stdout), fit: Boolean(process.stdout.isTTY), all }));
50786
+ printBlock(process.stdout, renderPoliciesScreen({ packs, refused, attention, custom, convention, cloud, legacy, cloudDashboard: cloudDashboardUrl2() }, { ...optsFor(process.stdout), fit: Boolean(process.stdout.isTTY), all }));
50848
50787
  try {
50849
50788
  syncConventionPolicies(discovered.user, "user");
50850
50789
  } catch (err) {
@@ -50866,6 +50805,7 @@ var init_manager2 = __esm(() => {
50866
50805
  init_hook_logger();
50867
50806
  init_fp_home();
50868
50807
  init_cloud_managed_policies();
50808
+ init_cloud_enrollment();
50869
50809
  init_cloud_policy_errors();
50870
50810
  init_agent_roster2();
50871
50811
  init_pack_store();
@@ -50878,11 +50818,11 @@ var init_manager2 = __esm(() => {
50878
50818
  });
50879
50819
 
50880
50820
  // src/audit/audit-schedule.ts
50881
- import { readFileSync as readFileSync47 } from "node:fs";
50821
+ import { readFileSync as readFileSync48 } from "node:fs";
50882
50822
  function readAuditSchedule(home) {
50883
50823
  let raw;
50884
50824
  try {
50885
- raw = readFileSync47(auditScheduleFile(home), "utf8");
50825
+ raw = readFileSync48(auditScheduleFile(home), "utf8");
50886
50826
  } catch {
50887
50827
  return null;
50888
50828
  }
@@ -51297,26 +51237,26 @@ function parseScriptArgs(argv) {
51297
51237
  var init_parse_script_args = () => {};
51298
51238
 
51299
51239
  // scripts/install-diagnosis.mjs
51300
- import { existsSync as existsSync60, readFileSync as readFileSync48, realpathSync as realpathSync6 } from "node:fs";
51301
- import { dirname as dirname33, resolve as resolve43 } from "node:path";
51240
+ import { existsSync as existsSync60, readFileSync as readFileSync49, realpathSync as realpathSync7 } from "node:fs";
51241
+ import { dirname as dirname34, resolve as resolve43 } from "node:path";
51302
51242
  import { homedir as homedir40, platform as platform5 } from "node:os";
51303
- import { spawnSync } from "node:child_process";
51243
+ import { spawnSync as spawnSync2 } from "node:child_process";
51304
51244
  function findPackageRoot(start) {
51305
51245
  try {
51306
- let dir = realpathSync6(start);
51246
+ let dir = realpathSync7(start);
51307
51247
  if (existsSync60(dir) && !existsSync60(resolve43(dir, "package.json"))) {
51308
- dir = dirname33(dir);
51248
+ dir = dirname34(dir);
51309
51249
  }
51310
51250
  while (true) {
51311
51251
  const pkgPath = resolve43(dir, "package.json");
51312
51252
  if (existsSync60(pkgPath)) {
51313
51253
  try {
51314
- const pkg = JSON.parse(readFileSync48(pkgPath, "utf8"));
51254
+ const pkg = JSON.parse(readFileSync49(pkgPath, "utf8"));
51315
51255
  if (pkg.name === PKG_NAME)
51316
51256
  return dir;
51317
51257
  } catch {}
51318
51258
  }
51319
- const parent = dirname33(dir);
51259
+ const parent = dirname34(dir);
51320
51260
  if (parent === dir)
51321
51261
  return null;
51322
51262
  dir = parent;
@@ -51329,7 +51269,7 @@ function readPackageVersion(packageRoot) {
51329
51269
  if (!packageRoot)
51330
51270
  return null;
51331
51271
  try {
51332
- const pkg = JSON.parse(readFileSync48(resolve43(packageRoot, "package.json"), "utf8"));
51272
+ const pkg = JSON.parse(readFileSync49(resolve43(packageRoot, "package.json"), "utf8"));
51333
51273
  return typeof pkg.version === "string" ? pkg.version : null;
51334
51274
  } catch {
51335
51275
  return null;
@@ -51338,7 +51278,7 @@ function readPackageVersion(packageRoot) {
51338
51278
  function resolvePathFirstBinary() {
51339
51279
  try {
51340
51280
  const isWin = platform5() === "win32";
51341
- const res = isWin ? spawnSync("where", [PKG_NAME], { encoding: "utf8" }) : spawnSync("sh", ["-c", `command -v ${PKG_NAME}`], { encoding: "utf8" });
51281
+ const res = isWin ? spawnSync2("where", [PKG_NAME], { encoding: "utf8" }) : spawnSync2("sh", ["-c", `command -v ${PKG_NAME}`], { encoding: "utf8" });
51342
51282
  if (res.status !== 0)
51343
51283
  return null;
51344
51284
  const first = (res.stdout || "").split(/\r?\n/).find((l) => l.trim().length > 0);
@@ -51349,7 +51289,7 @@ function resolvePathFirstBinary() {
51349
51289
  }
51350
51290
  function locateNpmGlobal() {
51351
51291
  try {
51352
- const res = spawnSync("npm", ["root", "-g"], { encoding: "utf8" });
51292
+ const res = spawnSync2("npm", ["root", "-g"], { encoding: "utf8" });
51353
51293
  if (res.status !== 0)
51354
51294
  return null;
51355
51295
  const root = (res.stdout || "").trim();
@@ -51383,7 +51323,7 @@ function buildRecommendation(pathFirstBin) {
51383
51323
  function diagnoseShadow(self) {
51384
51324
  const selfPackageRoot = (() => {
51385
51325
  try {
51386
- return self?.selfPackageRoot ? realpathSync6(self.selfPackageRoot) : null;
51326
+ return self?.selfPackageRoot ? realpathSync7(self.selfPackageRoot) : null;
51387
51327
  } catch {
51388
51328
  return self?.selfPackageRoot ?? null;
51389
51329
  }
@@ -51845,9 +51785,9 @@ function probeDashboardPort(host, port, timeoutMs = 1000) {
51845
51785
  var init_launch_ready = () => {};
51846
51786
 
51847
51787
  // scripts/launch.ts
51848
- import { spawn as spawn2 } from "child_process";
51849
- import { realpathSync as realpathSync7, existsSync as existsSync61 } from "node:fs";
51850
- import { resolve as resolve44, dirname as dirname34 } from "node:path";
51788
+ import { spawn as spawn3 } from "child_process";
51789
+ import { realpathSync as realpathSync8, existsSync as existsSync61 } from "node:fs";
51790
+ import { resolve as resolve44, dirname as dirname35 } from "node:path";
51851
51791
  import { fileURLToPath as fileURLToPath2 } from "node:url";
51852
51792
  function launch(mode, options = {}) {
51853
51793
  const { loggingLevel, disableTelemetry, allowedDevOrigins, host, remainingArgs } = parseScriptArgs(process.argv.slice(2));
@@ -51883,7 +51823,7 @@ ${k.caution(exposedBindWarning(exposed.host))}
51883
51823
  process.env.PORT = port;
51884
51824
  process.env.HOSTNAME = bindHost;
51885
51825
  cmd = "node";
51886
- const packageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT ?? resolve44(dirname34(realpathSync7(fileURLToPath2(import.meta.url))), "..");
51826
+ const packageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT ?? resolve44(dirname35(realpathSync8(fileURLToPath2(import.meta.url))), "..");
51887
51827
  const serverJsPath = resolve44(packageRoot, ".next/standalone/server.js");
51888
51828
  if (!existsSync61(serverJsPath)) {
51889
51829
  let shadowMessage = null;
@@ -51922,7 +51862,7 @@ Error: Cannot find server.js at:
51922
51862
  const filterLogs = mode === "start";
51923
51863
  if (!filterLogs && showScreen)
51924
51864
  printScreen(false);
51925
- const nextProcess = spawn2(cmd, cmdArgs, {
51865
+ const nextProcess = spawn3(cmd, cmdArgs, {
51926
51866
  stdio: filterLogs ? ["inherit", "pipe", "pipe"] : "inherit",
51927
51867
  env: {
51928
51868
  ...process.env,
@@ -52592,12 +52532,12 @@ var init_session_pause_cli = __esm(() => {
52592
52532
  });
52593
52533
 
52594
52534
  // src/hooks/config-status.ts
52595
- import { readFileSync as readFileSync49 } from "node:fs";
52535
+ import { readFileSync as readFileSync50 } from "node:fs";
52596
52536
  import { resolve as resolve45 } from "node:path";
52597
52537
  function readCollectorHealth(file = collectorHealthFile()) {
52598
52538
  let parsed;
52599
52539
  try {
52600
- parsed = JSON.parse(readFileSync49(file, "utf8"));
52540
+ parsed = JSON.parse(readFileSync50(file, "utf8"));
52601
52541
  } catch {
52602
52542
  return null;
52603
52543
  }
@@ -52666,14 +52606,9 @@ function summarizePolicySources(cwd) {
52666
52606
  }
52667
52607
  summary.morePacks = Math.max(0, enforcing - 1);
52668
52608
  } catch {}
52669
- try {
52670
- for (const artifact of listActiveCloudManagedPolicies()) {
52671
- if (artifact.effect === "observe")
52672
- summary.observing++;
52673
- else
52674
- summary.cloudOn++;
52675
- }
52676
- } catch {}
52609
+ const cloud = cloudPolicyStatus();
52610
+ summary.cloudOn += cloud.count;
52611
+ summary.observing += cloud.observingCount;
52677
52612
  const projectDir = resolve45(findProjectConfigDir(cwd ?? process.cwd()), ".failproofai", "policies");
52678
52613
  const conventionFiles = new Set([...discoverPolicyFiles(projectDir), ...discoverPolicyFiles(customPoliciesDir())]);
52679
52614
  summary.customFiles = configuredCustomPolicyPaths(config).length + conventionFiles.size;
@@ -52713,6 +52648,7 @@ async function gatherStatusFacts(deps = {}) {
52713
52648
  cloud = {
52714
52649
  kind: "file",
52715
52650
  host,
52651
+ url: base,
52716
52652
  ...orgName ? { org: orgName } : {},
52717
52653
  ...machineId ? { machine: describeMachine2(machineId, creds?.machineLabel) } : {},
52718
52654
  pullsPolicies: Boolean(creds),
@@ -52792,7 +52728,7 @@ function pickStatusAttention(facts) {
52792
52728
  };
52793
52729
  }
52794
52730
  if (facts.notEnforcing) {
52795
- const fix = facts.notEnforcing === "no-hooks" ? "failproofai config" : facts.notEnforcing === "observe-only" ? "failproofai policies" : policies.packsInstalled > 0 ? "failproofai policies add" : `failproofai policies add ${CORE_SOURCE}`;
52731
+ const fix = facts.notEnforcing === "no-hooks" ? "failproofai config" : facts.notEnforcing === "observe-only" ? "failproofai policies" : cloud.kind === "env" ? cloud.url : cloud.kind === "file" && cloud.pullsPolicies ? cloud.url ?? cloud.host : policies.packsInstalled > 0 ? "failproofai policies add" : `failproofai policies add ${CORE_SOURCE}`;
52796
52732
  return { severity: "caution", text: "Policies are not enforcing yet.", fix };
52797
52733
  }
52798
52734
  if (facts.codex?.kind === "untrusted") {
@@ -52875,16 +52811,20 @@ function renderStatusScreen(facts, opts = {}) {
52875
52811
  }
52876
52812
  if (!health.delivering)
52877
52813
  return `${kit.off} Not delivering, failproofaid has no key`;
52878
- const pending = queued + (refused.resending ?? 0);
52814
+ const retrying = refused.retrying ?? 0;
52815
+ const pending = queued + (refused.resending ?? 0) + retrying;
52879
52816
  const backlog = pending === 0 ? "nothing queued" : `${many(pending, "batch", "batches")} queued`;
52880
- const stuck = queued > 0 && (oldestQueuedMs ?? 0) > STATUS_QUEUE_STUCK_MS && (health.lastOkAt === undefined || now - health.lastOkAt > STATUS_QUEUE_STUCK_MS);
52817
+ const waiting = queued + retrying;
52818
+ const oldestWaitingMs = Math.max(queued > 0 ? oldestQueuedMs ?? 0 : 0, retrying > 0 ? refused.oldestAgeMs ?? 0 : 0);
52819
+ const stuck = waiting > 0 && oldestWaitingMs > STATUS_QUEUE_STUCK_MS && (health.lastOkAt === undefined || now - health.lastOkAt > STATUS_QUEUE_STUCK_MS);
52881
52820
  if (stuck) {
52882
52821
  const last = health.lastOkAt !== undefined ? `last delivered ${ago(health.lastOkAt)}` : "nothing delivered since failproofaid started";
52883
- return kit.caution(`${many(queued, "batch", "batches")} queued, oldest ${formatDuration2(oldestQueuedMs ?? 0)}, ${last}`);
52822
+ return kit.caution(`${many(waiting, "batch", "batches")} queued, oldest ${formatDuration2(oldestWaitingMs)}, ${last}`);
52884
52823
  }
52885
52824
  const lastEvent = health.lastEventAt !== undefined ? `last event ${ago(health.lastEventAt)}` : "no events since failproofaid started";
52886
52825
  return `${kit.on} Healthy, ${lastEvent}, ${backlog}`;
52887
52826
  };
52827
+ const cloudManaged = cloud.kind === "env" || cloud.kind === "file" && cloud.pullsPolicies;
52888
52828
  const policiesValue = () => {
52889
52829
  const clauses = [];
52890
52830
  if (policies.packOn > 0) {
@@ -52904,7 +52844,9 @@ function renderStatusScreen(facts, opts = {}) {
52904
52844
  clauses.push(`${many(policies.refusedPacks, "pack")} will not load`);
52905
52845
  if (clauses.length > 0)
52906
52846
  return clauses.join(", ");
52907
- return policies.anyPack ? `0 on from ${policies.anyPack}` : "None installed";
52847
+ if (policies.anyPack)
52848
+ return `0 on from ${policies.anyPack}`;
52849
+ return cloudManaged ? "None deployed from Cloud" : "None installed";
52908
52850
  };
52909
52851
  const codexValue = () => {
52910
52852
  const codex = facts.codex;
@@ -52982,7 +52924,6 @@ var init_config_status = __esm(() => {
52982
52924
  init_codex_system_hooks();
52983
52925
  init_cloud_enrollment_cli2();
52984
52926
  init_cloud_connection();
52985
- init_cloud_managed_policies();
52986
52927
  init_collector_config();
52987
52928
  init_custom_hooks_loader();
52988
52929
  init_daemon_client2();
@@ -53110,9 +53051,9 @@ var init_session_pause_cli2 = __esm(() => {
53110
53051
  });
53111
53052
 
53112
53053
  // scripts/launch.ts
53113
- import { spawn as spawn3 } from "child_process";
53114
- import { realpathSync as realpathSync8, existsSync as existsSync62 } from "node:fs";
53115
- import { resolve as resolve46, dirname as dirname35 } from "node:path";
53054
+ import { spawn as spawn4 } from "child_process";
53055
+ import { realpathSync as realpathSync9, existsSync as existsSync62 } from "node:fs";
53056
+ import { resolve as resolve46, dirname as dirname36 } from "node:path";
53116
53057
  import { fileURLToPath as fileURLToPath3 } from "node:url";
53117
53058
  function launch2(mode, options = {}) {
53118
53059
  const { loggingLevel, disableTelemetry, allowedDevOrigins, host, remainingArgs } = parseScriptArgs(process.argv.slice(2));
@@ -53148,7 +53089,7 @@ ${k.caution(exposedBindWarning(exposed.host))}
53148
53089
  process.env.PORT = port;
53149
53090
  process.env.HOSTNAME = bindHost;
53150
53091
  cmd = "node";
53151
- const packageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT ?? resolve46(dirname35(realpathSync8(fileURLToPath3(import.meta.url))), "..");
53092
+ const packageRoot = process.env.FAILPROOFAI_PACKAGE_ROOT ?? resolve46(dirname36(realpathSync9(fileURLToPath3(import.meta.url))), "..");
53152
53093
  const serverJsPath = resolve46(packageRoot, ".next/standalone/server.js");
53153
53094
  if (!existsSync62(serverJsPath)) {
53154
53095
  let shadowMessage = null;
@@ -53187,7 +53128,7 @@ Error: Cannot find server.js at:
53187
53128
  const filterLogs = mode === "start";
53188
53129
  if (!filterLogs && showScreen)
53189
53130
  printScreen(false);
53190
- const nextProcess = spawn3(cmd, cmdArgs, {
53131
+ const nextProcess = spawn4(cmd, cmdArgs, {
53191
53132
  stdio: filterLogs ? ["inherit", "pipe", "pipe"] : "inherit",
53192
53133
  env: {
53193
53134
  ...process.env,
@@ -53269,18 +53210,18 @@ var init_cli_error2 = __esm(() => {
53269
53210
  });
53270
53211
 
53271
53212
  // bin/failproofai.mjs
53272
- import { realpathSync as realpathSync9 } from "fs";
53273
- import { dirname as dirname36, resolve as resolve47 } from "path";
53213
+ import { realpathSync as realpathSync10 } from "fs";
53214
+ import { dirname as dirname37, resolve as resolve47 } from "path";
53274
53215
  import { fileURLToPath as fileURLToPath4 } from "url";
53275
53216
  // package.json
53276
- var version = "1.0.15";
53217
+ var version = "1.0.16-beta.0";
53277
53218
 
53278
53219
  // bin/failproofai.mjs
53279
53220
  if (!process.env.FAILPROOFAI_PACKAGE_ROOT) {
53280
- process.env.FAILPROOFAI_PACKAGE_ROOT = resolve47(dirname36(realpathSync9(fileURLToPath4(import.meta.url))), "..");
53221
+ process.env.FAILPROOFAI_PACKAGE_ROOT = resolve47(dirname37(realpathSync10(fileURLToPath4(import.meta.url))), "..");
53281
53222
  }
53282
53223
  if (!process.env.FAILPROOFAI_DIST_PATH) {
53283
- process.env.FAILPROOFAI_DIST_PATH = resolve47(dirname36(realpathSync9(fileURLToPath4(import.meta.url))), "..", "dist");
53224
+ process.env.FAILPROOFAI_DIST_PATH = resolve47(dirname37(realpathSync10(fileURLToPath4(import.meta.url))), "..", "dist");
53284
53225
  }
53285
53226
  var args = process.argv.slice(2);
53286
53227
  if (args[0] === "p" || args[0] === "policy")
@@ -53613,7 +53554,8 @@ Run \`failproofai help\` for usage.`);
53613
53554
  }
53614
53555
  } else if (!isHelpOrVersion && args[0] !== "migrate" && args[0] !== "update") {
53615
53556
  await Promise.resolve().then(() => init_fp_reset2());
53616
- const check = await checkLayoutForCli();
53557
+ const setupRun = args[0] === "config" && !["--status", "--pause", "--resume", "--connect", "--disconnect"].some((f) => args.includes(f)) && !(args.includes("--machine-label") && !["--token", "--oss", "--agents"].some((f) => args.includes(f)));
53558
+ const check = await checkLayoutForCli({ daemonUpdatedByCommand: setupRun });
53617
53559
  if (check.lines.length > 0)
53618
53560
  process.stderr.write(`${check.lines.join(`
53619
53561
  `)}
@@ -53958,90 +53900,51 @@ Run \`failproofai migrate --help\` for usage.`);
53958
53900
  await printHelp({
53959
53901
  name: "update",
53960
53902
  usage: [["npm i -g failproofai@latest && failproofai update"]],
53961
- options: [["--no-daemon", "Migrate everything but leave the daemon as is"]],
53903
+ options: [
53904
+ ["--no-daemon", "Migrate everything but leave the daemon as is"],
53905
+ ["--no-restart", "Leave running Hermes and OpenClaw gateways as they are"]
53906
+ ],
53962
53907
  optionsCol: 20
53963
53908
  });
53964
53909
  process.exit(0);
53965
53910
  }
53966
- const KNOWN = new Set(["--no-daemon"]);
53911
+ const KNOWN = new Set(["--no-daemon", "--no-restart"]);
53967
53912
  const unknown = subArgs.find((a) => a.startsWith("-") && !KNOWN.has(a));
53968
53913
  if (unknown) {
53969
53914
  throw new CliError3(`Unexpected argument: ${unknown}.
53970
53915
  Run \`failproofai update --help\` for usage.`);
53971
53916
  }
53972
53917
  lastSubcommand = "update";
53973
- await Promise.resolve().then(() => init_fp_config2());
53974
- await Promise.resolve().then(() => init_fp_home2());
53975
- await Promise.resolve().then(() => init_migrations2());
53976
- const state = detectLayout2();
53977
- if (state.kind === "future") {
53918
+ await Promise.resolve().then(() => init_update_run());
53919
+ const noDaemon = subArgs.includes("--no-daemon");
53920
+ const run = await runUpdateSteps({
53921
+ layout: true,
53922
+ daemon: !noDaemon,
53923
+ restart: !noDaemon && !subArgs.includes("--no-restart"),
53924
+ noteSkippedDaemon: noDaemon
53925
+ });
53926
+ if (run.futureLayout) {
53978
53927
  await printReport("update", [
53979
- `This machine's failproofai directory was written by a NEWER version (layout ${state.found}; this build speaks ${LAYOUT_VERSION2}). This CLI is the stale half:`,
53928
+ `This machine's failproofai directory was written by a NEWER version (layout ${run.futureLayout.found}; this build speaks ${run.futureLayout.speaks}). This CLI is the stale half:`,
53980
53929
  "",
53981
53930
  " npm install -g failproofai@latest"
53982
- ], { ok: false, meta: `layout ${state.found}` });
53931
+ ], { ok: false, meta: `layout ${run.futureLayout.found}` });
53983
53932
  await track("cli_update", { ok: false, reason: "future_layout" });
53984
53933
  lastSubcommand = null;
53985
53934
  await exitAfterFlush(1);
53986
53935
  return;
53987
53936
  }
53988
- const report = [];
53989
- let migrationsRan = 0;
53990
- let migrationFailed = false;
53991
- if (state.kind === "stale") {
53992
- const run = runMigrations2(state.found);
53993
- migrationsRan = run.steps.length;
53994
- migrationFailed = Boolean(run.failed);
53995
- for (const step of run.steps) {
53996
- report.push(` ${step.ok ? "migrated" : "FAILED "} layout ${step.from} \u2192 ${step.to}`);
53997
- }
53998
- if (run.backedUp.length > 0)
53999
- report.push("", `Saved first: ${run.backedUp.join(", ")}`);
54000
- if (run.failed) {
54001
- report.push("", `\u2715 Step ${run.failed.from} \u2192 ${run.failed.to} did not finish: ${run.failed.error}`, ` The home is still marked layout ${state.found} and will be retried.`);
54002
- }
54003
- } else {
54004
- report.push(`Home is at layout ${LAYOUT_VERSION2}; no migration was needed.`);
54005
- }
54006
- let daemonOk = true;
54007
- if (subArgs.includes("--no-daemon")) {
54008
- report.push("", "Skipped the daemon (--no-daemon). Its version may not match this CLI.");
54009
- } else {
54010
- const svc = await Promise.resolve().then(() => (init_daemon_service2(), {}));
54011
- if (!isDaemonSupportedPlatform2()) {
54012
- report.push("", `failproofaid does not run on ${process.platform}; nothing to update.`);
54013
- } else {
54014
- const result = await refreshDaemonToCliVersion();
54015
- report.push("", ...result.lines);
54016
- daemonOk = result.ok;
54017
- }
54018
- }
54019
- let hermesOk = true;
54020
- let hermesMigrated = 0;
54021
- try {
54022
- await Promise.resolve().then(() => init_hermes_update());
54023
- const svc = await Promise.resolve().then(() => (init_daemon_service2(), {}));
54024
- const hermesResult = await runHermesUpdateMigration({
54025
- daemonSupportsPolicyEvaluation: () => probeDaemonPolicyEvaluation2()
54026
- });
54027
- if (hermesResult.lines.length > 0) {
54028
- const [heading, ...rest] = hermesResult.lines;
54029
- report.push("", hermesResult.ok ? heading : `\u2715 ${heading}`, ...rest);
54030
- }
54031
- hermesOk = hermesResult.ok;
54032
- hermesMigrated = hermesResult.profiles.filter((p) => p.status === "migrated").length;
54033
- } catch (err) {
54034
- report.push("", `\u2715 Hermes migration failed: ${err instanceof Error ? err.message : String(err)}`);
54035
- hermesOk = false;
54036
- }
54037
- const updateOk = daemonOk && !migrationFailed && hermesOk;
53937
+ const report = run.lines;
53938
+ const updateOk = run.ok;
53939
+ if (updateOk && !noDaemon)
53940
+ markUpdated(version);
54038
53941
  await printReport("update", report, { ok: updateOk });
54039
53942
  await track("cli_update", {
54040
53943
  ok: updateOk,
54041
- migrations: migrationsRan,
54042
- migration_failed: migrationFailed,
54043
- hermes_ok: hermesOk,
54044
- hermes_migrated: hermesMigrated
53944
+ migrations: run.migrationsRan,
53945
+ migration_failed: run.migrationFailed,
53946
+ hermes_ok: run.hermesOk,
53947
+ hermes_migrated: run.hermesMigrated
54045
53948
  });
54046
53949
  lastSubcommand = null;
54047
53950
  await exitAfterFlush(updateOk ? 0 : 1);
@@ -54582,6 +54485,8 @@ Agents: ${INTEGRATION_TYPES2.join(", ")}, or all`);
54582
54485
  throw new CliError3(refusal);
54583
54486
  }
54584
54487
  await Promise.resolve().then(() => init_configure_wizard());
54488
+ await Promise.resolve().then(() => init_update_run());
54489
+ const pluggedBefore = await pluggedProfiles().catch(() => []);
54585
54490
  const result = await runConfigureWizard({}, {
54586
54491
  token: oss ? undefined : valueFor("--token") ?? process.env.FAILPROOFAI_CLOUD_TOKEN,
54587
54492
  url: valueFor("--url") ?? process.env.FAILPROOFAI_CLOUD_URL,
@@ -54600,6 +54505,33 @@ Agents: ${INTEGRATION_TYPES2.join(", ")}, or all`);
54600
54505
  labelExit = renamed.exitCode;
54601
54506
  }
54602
54507
  }
54508
+ let updateExit = 0;
54509
+ if (result.applied) {
54510
+ await Promise.resolve().then(() => init_update_run());
54511
+ await Promise.resolve().then(() => init_tui2());
54512
+ const kit = screenKit2({ color: colorsEnabled2(process.stdout) });
54513
+ if (!setupNeedsUpdateSteps(version)) {
54514
+ const gateway = setupGatewayLine(await restartNewlyPlugged(pluggedBefore).catch(() => []));
54515
+ if (gateway)
54516
+ process.stdout.write(`${gateway.ok ? kit.ok(gateway.text) : kit.caution(gateway.text)}
54517
+ `);
54518
+ } else {
54519
+ const run = await runUpdateSteps({ layout: false, daemon: false, restart: true });
54520
+ const gateway = setupGatewayLine(run.restarts);
54521
+ const out = [
54522
+ ...run.lines.filter((l) => l.startsWith("\u2715")),
54523
+ ...gateway ? [gateway.ok ? kit.ok(gateway.text) : kit.caution(gateway.text)] : []
54524
+ ];
54525
+ if (out.length > 0)
54526
+ process.stdout.write(`${out.join(`
54527
+ `)}
54528
+ `);
54529
+ if (run.ok)
54530
+ markUpdated(version);
54531
+ else
54532
+ updateExit = 1;
54533
+ }
54534
+ }
54603
54535
  await warnTokenOnArgv();
54604
54536
  await track("cli_configure_invoked", {
54605
54537
  applied: result.applied,
@@ -54610,7 +54542,7 @@ Agents: ${INTEGRATION_TYPES2.join(", ")}, or all`);
54610
54542
  oss,
54611
54543
  agents_named: agents ? agents.length : 0
54612
54544
  });
54613
- await exitAfterFlush(!result.applied && result.abort && result.abort !== "cancelled" ? 1 : labelExit);
54545
+ await exitAfterFlush(!result.applied && result.abort && result.abort !== "cancelled" ? 1 : labelExit || updateExit);
54614
54546
  return;
54615
54547
  }
54616
54548
  const knownFlags = ["--version", "-v", "--help", "-h", "--hook"];