@octopi-agent/engine 0.90.11 → 0.98.4

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 (246) hide show
  1. package/dist/config-admin/agent-presets.d.ts +70 -0
  2. package/dist/config-admin/agent-presets.js +243 -0
  3. package/dist/config-admin/discover.d.ts +30 -0
  4. package/dist/config-admin/discover.js +48 -0
  5. package/dist/config-admin/env.d.ts +22 -0
  6. package/dist/config-admin/env.js +41 -0
  7. package/dist/config-admin/index.d.ts +20 -0
  8. package/dist/config-admin/index.js +15 -0
  9. package/dist/config-admin/model-presets.d.ts +75 -0
  10. package/dist/config-admin/model-presets.js +249 -0
  11. package/dist/config-admin/name-guard.d.ts +14 -0
  12. package/dist/config-admin/name-guard.js +24 -0
  13. package/dist/config-admin/patch.d.ts +56 -0
  14. package/dist/config-admin/patch.js +201 -0
  15. package/dist/config-admin/port.d.ts +68 -0
  16. package/dist/config-admin/port.js +21 -0
  17. package/dist/config-admin/redact.d.ts +39 -0
  18. package/dist/config-admin/redact.js +42 -0
  19. package/dist/config-schema/agent.d.ts +45 -1
  20. package/dist/config-schema/context.d.ts +6 -1
  21. package/dist/config-schema/context.js +8 -0
  22. package/dist/config-schema/engine.d.ts +110 -4
  23. package/dist/config-schema/governance.d.ts +45 -1
  24. package/dist/config-schema/governance.js +187 -0
  25. package/dist/config-schema/models.d.ts +5 -2
  26. package/dist/config-schema/models.js +4 -1
  27. package/dist/config-schema/observability.d.ts +9 -0
  28. package/dist/config-schema/observability.js +29 -0
  29. package/dist/config-schema/run.d.ts +3 -0
  30. package/dist/config-schema/run.js +14 -0
  31. package/dist/config.d.ts +29 -4
  32. package/dist/config.js +15 -4
  33. package/dist/harness/activation/dispatcher.d.ts +8 -2
  34. package/dist/harness/activation/dispatcher.js +33 -5
  35. package/dist/harness/activation/inbox.d.ts +87 -0
  36. package/dist/harness/activation/inbox.js +169 -0
  37. package/dist/harness/activation/runtime.d.ts +9 -8
  38. package/dist/harness/activation/runtime.js +100 -8
  39. package/dist/harness/activation/types.d.ts +19 -0
  40. package/dist/harness/activation/types.js +2 -0
  41. package/dist/harness/agent/builder.d.ts +26 -1
  42. package/dist/harness/agent/builder.js +85 -37
  43. package/dist/harness/agent/config-bridge.d.ts +5 -0
  44. package/dist/harness/agent/config-bridge.js +3 -0
  45. package/dist/harness/agent/config-integrity.d.ts +138 -0
  46. package/dist/harness/agent/config-integrity.js +235 -0
  47. package/dist/harness/agent/wire-agent-builder.js +7 -1
  48. package/dist/harness/collaboration/autonomous-subsystem/index.d.ts +2 -2
  49. package/dist/harness/collaboration/autonomous-subsystem/index.js +1 -1
  50. package/dist/harness/collaboration/autonomous-subsystem/loader.js +3 -0
  51. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +19 -2
  52. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.d.ts +40 -0
  53. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.js +59 -0
  54. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -1
  55. package/dist/harness/collaboration/autonomous-subsystem/think/index.d.ts +2 -0
  56. package/dist/harness/collaboration/autonomous-subsystem/think/index.js +1 -0
  57. package/dist/harness/collaboration/autonomous-subsystem/think/model-resolver.js +1 -1
  58. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +9 -0
  59. package/dist/harness/collaboration/delegation/child-run.js +21 -5
  60. package/dist/harness/collaboration/delegation/notifier.js +4 -3
  61. package/dist/harness/collaboration/delegation/service.js +2 -3
  62. package/dist/harness/collaboration/delegation/wiring.js +6 -5
  63. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.d.ts +1 -1
  64. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.js +1 -1
  65. package/dist/harness/context/capabilities/compact/engine.d.ts +30 -0
  66. package/dist/harness/context/capabilities/compact/engine.js +198 -46
  67. package/dist/harness/context/capabilities/compact/handover.d.ts +78 -0
  68. package/dist/harness/context/capabilities/compact/handover.js +107 -0
  69. package/dist/harness/context/capabilities/compact/index.d.ts +3 -1
  70. package/dist/harness/context/capabilities/compact/index.js +2 -1
  71. package/dist/harness/context/capabilities/compact/types.d.ts +30 -1
  72. package/dist/harness/context/capabilities/summary/executor.js +2 -1
  73. package/dist/harness/context/capabilities/summary/policies.js +8 -5
  74. package/dist/harness/context/capabilities/summary/resolver.d.ts +1 -1
  75. package/dist/harness/context/capabilities/summary/resolver.js +4 -4
  76. package/dist/harness/context/capabilities/summary/types.d.ts +2 -2
  77. package/dist/harness/context/constitution/default-agents.md +11 -10
  78. package/dist/harness/context/default-context-engine.d.ts +34 -4
  79. package/dist/harness/context/default-context-engine.js +194 -49
  80. package/dist/harness/context/hybrid-compressor.js +6 -0
  81. package/dist/harness/context/layers.d.ts +2 -4
  82. package/dist/harness/context/layers.js +9 -11
  83. package/dist/harness/context/llm-summarizer.d.ts +2 -8
  84. package/dist/harness/context/llm-summarizer.js +69 -91
  85. package/dist/harness/context/message-selector.js +4 -3
  86. package/dist/harness/context/summarize.d.ts +3 -1
  87. package/dist/harness/context/summarize.js +9 -4
  88. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  89. package/dist/harness/context/system-prompt-assembler.js +1 -0
  90. package/dist/harness/context/truncate-compressor.js +7 -0
  91. package/dist/harness/context/turn-envelope.d.ts +3 -2
  92. package/dist/harness/context/turn-envelope.js +3 -2
  93. package/dist/harness/context/types.d.ts +33 -1
  94. package/dist/harness/extension/execution-environment/dangerous-commands.d.ts +28 -0
  95. package/dist/harness/extension/execution-environment/dangerous-commands.js +129 -0
  96. package/dist/harness/extension/execution-environment/effect-policy.d.ts +149 -8
  97. package/dist/harness/extension/execution-environment/effect-policy.js +274 -19
  98. package/dist/harness/extension/execution-environment/index.d.ts +4 -2
  99. package/dist/harness/extension/execution-environment/index.js +2 -1
  100. package/dist/harness/extension/execution-environment/kill-switch.d.ts +34 -0
  101. package/dist/harness/extension/execution-environment/kill-switch.js +46 -0
  102. package/dist/harness/extension/execution-environment/ops-audit.d.ts +204 -0
  103. package/dist/harness/extension/execution-environment/ops-audit.js +337 -0
  104. package/dist/harness/extension/execution-environment/privileged-exec.d.ts +158 -0
  105. package/dist/harness/extension/execution-environment/privileged-exec.js +418 -0
  106. package/dist/harness/extension/execution-environment/process-info.d.ts +180 -0
  107. package/dist/harness/extension/execution-environment/process-info.js +466 -0
  108. package/dist/harness/extension/execution-environment/process-isolation.d.ts +7 -0
  109. package/dist/harness/extension/execution-environment/process-isolation.js +9 -0
  110. package/dist/harness/extension/execution-environment/sandbox.d.ts +109 -0
  111. package/dist/harness/extension/execution-environment/sandbox.js +228 -21
  112. package/dist/harness/extension/execution-environment/tool-capabilities.d.ts +1 -1
  113. package/dist/harness/extension/execution-environment/tool-capabilities.js +6 -0
  114. package/dist/harness/extension/execution-environment/types.d.ts +19 -0
  115. package/dist/harness/extension/execution-environment/undo-log.d.ts +6 -2
  116. package/dist/harness/extension/execution-environment/undo-log.js +31 -10
  117. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +5 -0
  118. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +33 -0
  119. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.d.ts +4 -5
  120. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.js +5 -15
  121. package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +3 -0
  122. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +70 -26
  123. package/dist/harness/extension/plugin-ecosystem/tools/document-tools.js +3 -9
  124. package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +3 -6
  125. package/dist/harness/extension/plugin-ecosystem/tools/file-ops.js +9 -5
  126. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +9 -130
  127. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +122 -14
  128. package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +2 -0
  129. package/dist/harness/extension/plugin-ecosystem/tools/index.js +2 -0
  130. package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +4 -13
  131. package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +25 -11
  132. package/dist/harness/extension/plugin-ecosystem/tools/platform.js +168 -62
  133. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.d.ts +43 -0
  134. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.js +350 -0
  135. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.d.ts +30 -0
  136. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.js +137 -0
  137. package/dist/harness/governance/human-in-the-loop/decision-cache.d.ts +54 -4
  138. package/dist/harness/governance/human-in-the-loop/decision-cache.js +42 -16
  139. package/dist/harness/governance/security/default-risk-policy.d.ts +1 -0
  140. package/dist/harness/governance/security/default-risk-policy.js +1 -0
  141. package/dist/harness/governance/security/default-security-guard.js +9 -0
  142. package/dist/harness/governance/security/index.d.ts +1 -0
  143. package/dist/harness/governance/security/index.js +2 -0
  144. package/dist/harness/governance/security/risk-evaluator.js +13 -0
  145. package/dist/harness/governance/security/risk-types.d.ts +12 -0
  146. package/dist/harness/governance/security/shell-parser-fallback.d.ts +29 -0
  147. package/dist/harness/governance/security/shell-parser-fallback.js +410 -0
  148. package/dist/harness/governance/security/shell-parser-shared.d.ts +83 -0
  149. package/dist/harness/governance/security/shell-parser-shared.js +188 -0
  150. package/dist/harness/governance/security/shell-parser-treesitter.d.ts +52 -0
  151. package/dist/harness/governance/security/shell-parser-treesitter.js +370 -0
  152. package/dist/harness/governance/security/shell-parser.d.ts +23 -10
  153. package/dist/harness/governance/security/shell-parser.js +37 -496
  154. package/dist/harness/governance/security/temp-path.d.ts +9 -0
  155. package/dist/harness/governance/security/temp-path.js +13 -2
  156. package/dist/harness/governance/security/vendor/README.md +24 -0
  157. package/dist/harness/governance/security/vendor/tree-sitter-bash.LICENSE.txt +21 -0
  158. package/dist/harness/governance/security/vendor/tree-sitter-bash.wasm +0 -0
  159. package/dist/harness/governance/session-acl/seed-roles.js +14 -0
  160. package/dist/harness/index.d.ts +2 -0
  161. package/dist/harness/index.js +2 -0
  162. package/dist/harness/knowledge/fts.js +1 -2
  163. package/dist/harness/knowledge/index-store.js +59 -9
  164. package/dist/harness/memory/index.d.ts +6 -2
  165. package/dist/harness/memory/index.js +4 -1
  166. package/dist/harness/memory/memory-events.d.ts +25 -0
  167. package/dist/harness/memory/memory-events.js +38 -0
  168. package/dist/harness/memory/sqlite/agent-db.js +15 -0
  169. package/dist/harness/memory/sqlite/keyword-search.d.ts +1 -0
  170. package/dist/harness/memory/sqlite/keyword-search.js +4 -3
  171. package/dist/harness/memory/sqlite/wisdom-store.d.ts +7 -2
  172. package/dist/harness/memory/sqlite/wisdom-store.js +51 -2
  173. package/dist/harness/memory/steward-policy.d.ts +3 -0
  174. package/dist/harness/memory/steward-policy.js +1 -1
  175. package/dist/harness/memory/types.d.ts +41 -3
  176. package/dist/harness/memory/wisdom-attribution.d.ts +136 -0
  177. package/dist/harness/memory/wisdom-attribution.js +287 -0
  178. package/dist/harness/memory/wisdom-events.d.ts +37 -0
  179. package/dist/harness/memory/wisdom-events.js +61 -0
  180. package/dist/harness/memory/wisdom-formation.d.ts +20 -1
  181. package/dist/harness/memory/wisdom-formation.js +55 -21
  182. package/dist/harness/memory/wisdom.d.ts +7 -2
  183. package/dist/harness/memory/wisdom.js +40 -2
  184. package/dist/harness/observability/observer/hub.js +8 -0
  185. package/dist/harness/observability/observer/run-snapshot.js +1 -0
  186. package/dist/harness/observability/observer/types.d.ts +4 -0
  187. package/dist/harness/run/agent/agent.d.ts +7 -0
  188. package/dist/harness/run/agent/agent.js +23 -1
  189. package/dist/harness/run/reliability/fallback-provider.d.ts +117 -5
  190. package/dist/harness/run/reliability/fallback-provider.js +262 -22
  191. package/dist/harness/run/reliability/harness-events.d.ts +24 -1
  192. package/dist/harness/run/reliability/model-error-policy.d.ts +32 -0
  193. package/dist/harness/run/reliability/model-error-policy.js +42 -0
  194. package/dist/harness/run/reliability/provider-wrapper.js +29 -2
  195. package/dist/harness/run/reliability/refusal-guard.d.ts +20 -0
  196. package/dist/harness/run/reliability/refusal-guard.js +102 -0
  197. package/dist/harness/run/reliability/run-agent.js +231 -33
  198. package/dist/harness/run/run-guard/default-run-guard.js +1 -1
  199. package/dist/harness/run/run-scope.d.ts +35 -0
  200. package/dist/harness/run/runner.d.ts +141 -2
  201. package/dist/harness/run/runner.js +592 -42
  202. package/dist/harness/session/attachments/llm-intent.js +2 -1
  203. package/dist/harness/session/tasks/render.d.ts +4 -1
  204. package/dist/harness/session/tasks/render.js +10 -7
  205. package/dist/harness/shared/events/agent-event-map.d.ts +66 -0
  206. package/dist/harness/shared/events/agent-event-map.js +5 -0
  207. package/dist/harness/shared/paths/glob.d.ts +52 -0
  208. package/dist/harness/shared/paths/glob.js +218 -0
  209. package/dist/harness/shared/paths/index.d.ts +84 -0
  210. package/dist/harness/shared/paths/index.js +179 -0
  211. package/dist/index.d.ts +3 -3
  212. package/dist/index.js +2 -2
  213. package/dist/integration/agent-runtime/channel-message-source.js +19 -1
  214. package/dist/integration/index.d.ts +2 -0
  215. package/dist/integration/index.js +1 -0
  216. package/dist/integration/observability/loop-watchdog.d.ts +56 -0
  217. package/dist/integration/observability/loop-watchdog.js +177 -0
  218. package/dist/integration/observability/metrics.d.ts +3 -0
  219. package/dist/integration/observability/metrics.js +18 -7
  220. package/dist/integration/providers/anthropic.d.ts +23 -0
  221. package/dist/integration/providers/anthropic.js +97 -12
  222. package/dist/integration/providers/fetch-timeout.d.ts +42 -0
  223. package/dist/integration/providers/fetch-timeout.js +51 -0
  224. package/dist/integration/providers/openai.d.ts +10 -0
  225. package/dist/integration/providers/openai.js +58 -11
  226. package/dist/integration/providers/provider-diagnostics.d.ts +80 -0
  227. package/dist/integration/providers/provider-diagnostics.js +89 -0
  228. package/dist/integration/providers/timeout-coherence.d.ts +52 -0
  229. package/dist/integration/providers/timeout-coherence.js +68 -0
  230. package/dist/integration/providers/wire-dump.d.ts +62 -0
  231. package/dist/integration/providers/wire-dump.js +111 -2
  232. package/dist/integration/storage/jsonl.js +4 -1
  233. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +4 -2
  234. package/dist/subsystems/cognition-steward/conceptualize/handler.js +12 -20
  235. package/dist/subsystems/memory-steward/backfill/config.yaml +4 -2
  236. package/dist/subsystems/memory-steward/backfill/handler.js +44 -52
  237. package/dist/subsystems/wisdom-steward/attribute/SUBSYSTEM.md +24 -0
  238. package/dist/subsystems/wisdom-steward/attribute/config.yaml +60 -0
  239. package/dist/subsystems/wisdom-steward/attribute/handler.d.ts +23 -0
  240. package/dist/subsystems/wisdom-steward/attribute/handler.js +167 -0
  241. package/dist/subsystems/wisdom-steward/evaluate/handler.js +3 -1
  242. package/dist/subsystems/wisdom-steward/formation/config.yaml +12 -5
  243. package/dist/subsystems/wisdom-steward/formation/handler.js +12 -18
  244. package/dist/subsystems/wisdom-steward/govern/config.yaml +1 -1
  245. package/dist/subsystems/wisdom-steward/govern/handler.js +4 -0
  246. package/package.json +8 -2
@@ -7,6 +7,8 @@
7
7
  export { ProcessSandbox, createProcessSandbox, assessL4ProcessMinimum, supervisedSpawnProfile, } from './sandbox.js';
8
8
  export { probeProcessIsolation, scrubEnv, killProcessTree, L4_PROCESS_MINIMUM, } from './process-isolation.js';
9
9
  export type { ProcessIsolationProfile, IsolationBackend, ProcessTreeIsolation, FilesystemIsolation, ResourceIsolation, NetworkIsolation, PrivilegeIsolation, EnvHygiene, L4ProcessAssessment, } from './process-isolation.js';
10
+ export { listProcesses, getAncestorPidChain, resolveProcessImage, buildAncestorChain, selectProcesses, parsePsProcessTable, parseCpuTimeToMs, parseProcPidEntry, parsePowerShellProcessTable, firstExecutableFromLsof, } from './process-info.js';
11
+ export type { ProcessInfoEntry, ProcessListResult, ListProcessesOptions, SelectedProcesses, AncestorChain, TableParseResult, } from './process-info.js';
10
12
  export { FileWorkspace } from './workspace.js';
11
13
  export type { FileWorkspaceConfig } from './workspace.js';
12
14
  export { DEFAULT_TOOL_ISOLATION, resolveToolIsolationCwd, safeSessionDirSegment, looksLikeAbsoluteSessionPath, } from './isolation.js';
@@ -15,8 +17,8 @@ export { TurnFileUndoLog, commitSessionFileUndo, discardSessionFileUndo, resolve
15
17
  export type { SessionUndoPaths, FileUndoEntry, DiscardFileEffectsResult, DiscardConflictReason, } from './undo-log.js';
16
18
  export { isProbablyText, reverseAgentOverwrite, merge3Lines } from './undo-merge.js';
17
19
  export { snapshotShellRoots, captureShellInventory, diffShellInventory, journalShellDiff, writeNotReversed, } from './shell-journal.js';
18
- export { resolveEffectiveEffectPolicy, requiresJail, isPathAllowed, isToolAllowedOnSurface, gateEffect, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './effect-policy.js';
19
- export type { UntrustedAdmission, ToolSurface, SecurityDegradation, EffectiveEffectPolicy, SessionEffectOverrides, } from './effect-policy.js';
20
+ export { resolveEffectiveEffectPolicy, requiresJail, buildOpsJailState, isPathAllowed, isToolAllowedOnSurface, gateEffect, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './effect-policy.js';
21
+ export type { UntrustedAdmission, JailIntent, OnJailUnavailable, OpsJailState, ToolSurface, SecurityDegradation, EffectiveEffectPolicy, SessionEffectOverrides, } from './effect-policy.js';
20
22
  export { runWithToolLimits, resolveToolTimeoutMs, ToolTimeoutError, } from './resource-limits.js';
21
23
  export type { ToolRunLimits } from './resource-limits.js';
22
24
  export { TurnMemoryJournal, JournaledMemoryStore, createMemoryRestorer, discardMemoryUndo, } from './memory-undo.js';
@@ -6,12 +6,13 @@
6
6
  */
7
7
  export { ProcessSandbox, createProcessSandbox, assessL4ProcessMinimum, supervisedSpawnProfile, } from './sandbox.js';
8
8
  export { probeProcessIsolation, scrubEnv, killProcessTree, L4_PROCESS_MINIMUM, } from './process-isolation.js';
9
+ export { listProcesses, getAncestorPidChain, resolveProcessImage, buildAncestorChain, selectProcesses, parsePsProcessTable, parseCpuTimeToMs, parseProcPidEntry, parsePowerShellProcessTable, firstExecutableFromLsof, } from './process-info.js';
9
10
  export { FileWorkspace } from './workspace.js';
10
11
  export { DEFAULT_TOOL_ISOLATION, resolveToolIsolationCwd, safeSessionDirSegment, looksLikeAbsoluteSessionPath, } from './isolation.js';
11
12
  export { TurnFileUndoLog, commitSessionFileUndo, discardSessionFileUndo, resolveSessionUndoPaths, resolveSessionUndoOnClose, } from './undo-log.js';
12
13
  export { isProbablyText, reverseAgentOverwrite, merge3Lines } from './undo-merge.js';
13
14
  export { snapshotShellRoots, captureShellInventory, diffShellInventory, journalShellDiff, writeNotReversed, } from './shell-journal.js';
14
- export { resolveEffectiveEffectPolicy, requiresJail, isPathAllowed, isToolAllowedOnSurface, gateEffect, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './effect-policy.js';
15
+ export { resolveEffectiveEffectPolicy, requiresJail, buildOpsJailState, isPathAllowed, isToolAllowedOnSurface, gateEffect, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './effect-policy.js';
15
16
  export { runWithToolLimits, resolveToolTimeoutMs, ToolTimeoutError, } from './resource-limits.js';
16
17
  export { TurnMemoryJournal, JournaledMemoryStore, createMemoryRestorer, discardMemoryUndo, } from './memory-undo.js';
17
18
  export { resolveToolCapabilities, deniesReducedSurface, BUILTIN_TOOL_CAPABILITIES, REDUCED_DENIED_CAPABILITIES, } from './tool-capabilities.js';
@@ -0,0 +1,34 @@
1
+ /**
2
+ * kill switch(ops P5,`arch/ops-privileged-mode.md` §5 P5)——宿主侧急停
3
+ *
4
+ * 一条命令停掉 agent 的全部执行能力,**不依赖 LLM 判断与 agent 合作**:
5
+ * 宿主写一个哨兵文件(`octopi ops kill <agentId>`),引擎在 run 准入与每次工具
6
+ * 调用前检查——文件在 = 什么都不执行。删除文件(`octopi ops revive`)恢复。
7
+ *
8
+ * 设计约束:
9
+ * - **宿主侧信号**:不走 LLM、不走 agent 工具面(agent 无法自己解除;它甚至无法
10
+ * 阻止检查——检查点在 beforeToolCall,先于一切工具 handler)。
11
+ * - **每次实查,不缓存**:急停必须即时生效,也必须可即时恢复。
12
+ * - fail-closed:检查本身异常(stat 失败)按「未触发」处理不降级——哨兵缺失是
13
+ * 常态;但**路径未配置**时不得假装有急停(诚实:没有检查点 = 没有 kill switch)。
14
+ */
15
+ /** 急停状态 */
16
+ export interface KillSwitchState {
17
+ engaged: boolean;
18
+ /** 触发的哨兵文件路径(engaged=true 时给出) */
19
+ path?: string;
20
+ }
21
+ /**
22
+ * 默认哨兵路径(宿主布局):`<OCTOPI_HOME>/agents/<agentId>/KILL`。
23
+ *
24
+ * @param agentId - agent 标识
25
+ * @returns 哨兵文件绝对路径
26
+ */
27
+ export declare function defaultKillSwitchPath(agentId: string): string;
28
+ /**
29
+ * 检查急停哨兵(每次实查;文件存在 = engaged)。
30
+ *
31
+ * @param paths - 哨兵路径列表(任一存在即触发)
32
+ * @returns 急停状态
33
+ */
34
+ export declare function checkKillSwitch(paths: readonly string[] | undefined): KillSwitchState;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * kill switch(ops P5,`arch/ops-privileged-mode.md` §5 P5)——宿主侧急停
3
+ *
4
+ * 一条命令停掉 agent 的全部执行能力,**不依赖 LLM 判断与 agent 合作**:
5
+ * 宿主写一个哨兵文件(`octopi ops kill <agentId>`),引擎在 run 准入与每次工具
6
+ * 调用前检查——文件在 = 什么都不执行。删除文件(`octopi ops revive`)恢复。
7
+ *
8
+ * 设计约束:
9
+ * - **宿主侧信号**:不走 LLM、不走 agent 工具面(agent 无法自己解除;它甚至无法
10
+ * 阻止检查——检查点在 beforeToolCall,先于一切工具 handler)。
11
+ * - **每次实查,不缓存**:急停必须即时生效,也必须可即时恢复。
12
+ * - fail-closed:检查本身异常(stat 失败)按「未触发」处理不降级——哨兵缺失是
13
+ * 常态;但**路径未配置**时不得假装有急停(诚实:没有检查点 = 没有 kill switch)。
14
+ */
15
+ import { statSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ import { getOctopiHome } from '../../../paths.js';
18
+ /**
19
+ * 默认哨兵路径(宿主布局):`<OCTOPI_HOME>/agents/<agentId>/KILL`。
20
+ *
21
+ * @param agentId - agent 标识
22
+ * @returns 哨兵文件绝对路径
23
+ */
24
+ export function defaultKillSwitchPath(agentId) {
25
+ return join(getOctopiHome(), 'agents', agentId, 'KILL');
26
+ }
27
+ /**
28
+ * 检查急停哨兵(每次实查;文件存在 = engaged)。
29
+ *
30
+ * @param paths - 哨兵路径列表(任一存在即触发)
31
+ * @returns 急停状态
32
+ */
33
+ export function checkKillSwitch(paths) {
34
+ if (!paths || paths.length === 0)
35
+ return { engaged: false };
36
+ for (const path of paths) {
37
+ try {
38
+ if (statSync(path).isFile())
39
+ return { engaged: true, path };
40
+ }
41
+ catch {
42
+ // 哨兵缺失是常态(未急停);stat 失败同义,不制造假触发
43
+ }
44
+ }
45
+ return { engaged: false };
46
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * 运维审计账本(ops P2,`arch/ops-privileged-mode.md` §5 P2 / §7)
3
+ *
4
+ * 提权(P3)的前置条件:碰过什么必须可查。本模块提供:
5
+ * - **hash 链 JSONL 账本**(`OpsAuditJournal`):追加即锚定前条 hash,事后可验证
6
+ * 改写/插入/中间截断(`verify()`);**尾部截断与整文件删除无法本地自证**——那需要
7
+ * 外部见证(P5 外送的计数/尾 hash 锚点)。这是 T0 档的「防篡改」上限(同 uid 进程
8
+ * 可写账本所在目录),真正不可抵赖靠 P5 外送,见规格原则 8。
9
+ * - **事件词表**:`ops.command.executed`(统一动作记录)/ `ops.system_path.write`
10
+ * (效应 root 之外的写入)/ `ops.policy.degraded` / `ops.config.security_changed`
11
+ * / `ops.jail.state`。
12
+ * - **`ToolFileEffects` 包装器**:文件效应写口集中拦截 roots 外写入(覆盖全部经
13
+ * fileEffects 的文件工具写口)。**shell 的 roots 外写入不在其内**:shell 账本只
14
+ * 清点 roots,任意命令的写盘面无法穷举追踪——`jail: none`(unconfined)命令以
15
+ * `jail.unconfined: true` 声明「写入未入账」;根因追踪属 P5/增强。
16
+ *
17
+ * 只追加不修改;写失败向上抛(调用方决定降级),绝不静默丢账。
18
+ */
19
+ import type { ToolFileEffects } from '@octopi-agent/core/types/tools.js';
20
+ /** 审计事件词表(§7) */
21
+ export type OpsAuditEvent = 'ops.jail.state' | 'ops.command.executed' | 'ops.system_path.write' | 'ops.policy.degraded' | 'ops.config.security_changed' | 'ops.escalation.requested' | 'ops.escalation.denied' | 'ops.privileged.exec' | 'ops.kill_switch.tripped';
22
+ /** 账本条目(hash 链节点) */
23
+ export interface OpsAuditEntry {
24
+ /** 从 1 起单调递增 */
25
+ seq: number;
26
+ /** epoch ms */
27
+ ts: number;
28
+ event: OpsAuditEvent;
29
+ data: Record<string, unknown>;
30
+ /** 前一条 hash;首条为 `GENESIS_HASH` */
31
+ prevHash: string;
32
+ /** sha256(canonical({seq,ts,event,data,prevHash})) */
33
+ hash: string;
34
+ }
35
+ /** 链首哨兵 */
36
+ export declare const GENESIS_HASH: string;
37
+ /**
38
+ * 规范化 JSON(对象键排序)——hash 输入必须与键序无关。
39
+ *
40
+ * @param value - 任意 JSON 兼容值
41
+ * @returns 稳定序列化文本
42
+ */
43
+ export declare function canonicalJson(value: unknown): string;
44
+ /**
45
+ * 计算账目 hash(链的唯一真相源)。
46
+ *
47
+ * @param entry - 不含 hash 的条目字段
48
+ * @returns sha256 十六进制
49
+ */
50
+ export declare function computeOpsAuditEntryHash(entry: Omit<OpsAuditEntry, 'hash'>): string;
51
+ /**
52
+ * 验证一段链(整文件或任意连续片段)。
53
+ *
54
+ * @param entries - 按 seq 升序的条目
55
+ * @returns ok 或首个断裂点
56
+ */
57
+ export declare function verifyOpsAuditChain(entries: readonly OpsAuditEntry[]): {
58
+ ok: true;
59
+ entries: number;
60
+ } | {
61
+ ok: false;
62
+ entries: number;
63
+ brokenAtSeq: number;
64
+ reason: string;
65
+ };
66
+ /**
67
+ * 读回账本全文(供验证/查询)。
68
+ *
69
+ * **只有 ENOENT 是合法空账**(尚未建账);其余读失败抛 `ops_audit_unreadable`、
70
+ * 坏行抛 `ops_audit_corrupt`——把读失败当空账会静默重链并把账本写坏(评审实证)。
71
+ *
72
+ * @param path - 账本文件路径
73
+ * @returns 条目(按写入序);文件不存在返回空数组
74
+ * @throws `ops_audit_unreadable` / `ops_audit_corrupt`
75
+ */
76
+ export declare function readOpsAuditEntries(path: string): OpsAuditEntry[];
77
+ /** 账本追加结果 */
78
+ export interface OpsAuditAppendResult {
79
+ entry: OpsAuditEntry;
80
+ /** tail 衔接被验证过(追加即轻校验) */
81
+ tailVerified: boolean;
82
+ }
83
+ /**
84
+ * 运维审计账本(append-only JSONL + hash 链)。
85
+ *
86
+ * 追加为同步写(`appendFileSync`):审计语义优先于吞吐,且顺序天然确定。
87
+ * 启动/首次追加时回读尾条衔接 `seq/prevHash`;尾部不可解析 → 抛
88
+ * `ops_audit_corrupt`(**拒绝续链**——静默重链会把篡改洗成新链)。
89
+ */
90
+ export declare class OpsAuditJournal {
91
+ private readonly path;
92
+ private tail;
93
+ /**
94
+ * @param options - `path` 为账本 JSONL 绝对路径
95
+ */
96
+ constructor(options: {
97
+ path: string;
98
+ });
99
+ /** 账本路径(诊断/测试用) */
100
+ get filePath(): string;
101
+ private bootstrapTail;
102
+ /**
103
+ * 追加一条账目。
104
+ *
105
+ * @param event - 事件名(§7 词表)
106
+ * @param data - 事件载荷(键序无关,hash 走 canonicalJson)
107
+ * @returns 落盘的账目
108
+ */
109
+ append(event: OpsAuditEvent, data: Record<string, unknown>): OpsAuditEntry;
110
+ /**
111
+ * 全链验证(追加只验尾;中段篡改靠本方法)。
112
+ *
113
+ * @returns ok 或首个断裂点
114
+ */
115
+ verify(): ReturnType<typeof verifyOpsAuditChain>;
116
+ }
117
+ /**
118
+ * 工具上下文回传的事件输入(core 契约 shape)
119
+ */
120
+ export interface OpsEventInput {
121
+ event: OpsAuditEvent;
122
+ data: Record<string, unknown>;
123
+ }
124
+ /**
125
+ * 审计外送信封(P5 唯一不可抵赖档,原则 8)。
126
+ *
127
+ * 本地账本的 hash 链防「改写/插入」,但**尾部截断与整文件删除本地无法自证**——
128
+ * 那需要外部见证。外送档把每条账目(连同链证据)推到宿主可达的收口
129
+ * (宿主侧文件 / HTTP),宿主按 `count`(= 账本 seq)查缺、用 `entry` 原样重验链:
130
+ *
131
+ * - `count`:单调递增账目序号——外送流缺号 = 丢账可查;
132
+ * - `tailHash`:本条落链后的尾锚点——与宿主已收最后一条对得上才叫连续;
133
+ * - `entry`:账目原样(含 `prevHash`/`hash`,`verifyOpsAuditChain` 可直接重放)。
134
+ */
135
+ export interface OpsAuditExportEnvelope {
136
+ count: number;
137
+ tailHash: string;
138
+ entry: OpsAuditEntry;
139
+ /** 外送时刻(epoch ms;账目 `ts` 是发生时刻,两者都留) */
140
+ forwardedAt: number;
141
+ }
142
+ /** 外送收口(append-only) */
143
+ export interface OpsAuditExportSink {
144
+ forward(envelope: OpsAuditExportEnvelope): void;
145
+ }
146
+ /**
147
+ * 文件外送收口:宿主侧 append-only JSONL(每行一个信封)。
148
+ *
149
+ * 路径应放在 **agent 可写面之外**(`~/.octopi` 在 host 模式的可写面内——放那里
150
+ * 等于没外送)。写失败向上抛,由调用方降级申报,绝不静默丢外送。
151
+ */
152
+ export declare class OpsAuditFileExportSink implements OpsAuditExportSink {
153
+ private readonly path;
154
+ /**
155
+ * @param options.path - 外送文件绝对路径(宿主侧,agent 不可写)
156
+ */
157
+ constructor(options: {
158
+ path: string;
159
+ });
160
+ /** 外送文件路径(诊断用) */
161
+ get filePath(): string;
162
+ /** @inheritdoc */
163
+ forward(envelope: OpsAuditExportEnvelope): void;
164
+ }
165
+ /**
166
+ * `ToolFileEffects` 装饰器:效应 root 之外的写入统一入 `ops.system_path.write`。
167
+ *
168
+ * 单点覆盖全部文件工具与 shell 账本(它们都经 `fileEffects` 写口),不逐工具打补丁。
169
+ * 记账失败不影响业务写(与 §5.6 记账同策略),但会抛给调用方的降级通道。
170
+ */
171
+ export declare class OpsAuditedFileEffects implements ToolFileEffects {
172
+ private readonly inner;
173
+ private readonly roots;
174
+ private readonly record;
175
+ /**
176
+ * @param inner - 被装饰的真实效应 journal
177
+ * @param options.roots - 效应 root(root 内写入不记 system_path 账)
178
+ * @param options.record - 账目回传(通常进 OpsAuditJournal)
179
+ */
180
+ constructor(inner: ToolFileEffects, options: {
181
+ roots: readonly string[];
182
+ record: (event: OpsAuditEvent, data: Record<string, unknown>) => void;
183
+ });
184
+ private underRoots;
185
+ private noteWrite;
186
+ /** @inheritdoc */
187
+ writeFile(path: string, data: string | Uint8Array, options?: {
188
+ refuseFinalSymlink?: boolean;
189
+ }): Promise<void>;
190
+ /** @inheritdoc */
191
+ appendFile(path: string, data: string | Uint8Array, options?: {
192
+ refuseFinalSymlink?: boolean;
193
+ }): Promise<void>;
194
+ /** @inheritdoc */
195
+ recordDelete(path: string, before: string | Uint8Array): Promise<void>;
196
+ /** @inheritdoc */
197
+ recordCreate(path: string, after?: string | Uint8Array): Promise<void>;
198
+ /** @inheritdoc */
199
+ recordRename(from: string, to: string): Promise<void>;
200
+ /** @inheritdoc */
201
+ recordOverwrite(path: string, before: string | Uint8Array, after?: string | Uint8Array): Promise<void>;
202
+ /** @inheritdoc */
203
+ noteNotReversed(payload: Parameters<ToolFileEffects['noteNotReversed']>[0]): Promise<void>;
204
+ }
@@ -0,0 +1,337 @@
1
+ /**
2
+ * 运维审计账本(ops P2,`arch/ops-privileged-mode.md` §5 P2 / §7)
3
+ *
4
+ * 提权(P3)的前置条件:碰过什么必须可查。本模块提供:
5
+ * - **hash 链 JSONL 账本**(`OpsAuditJournal`):追加即锚定前条 hash,事后可验证
6
+ * 改写/插入/中间截断(`verify()`);**尾部截断与整文件删除无法本地自证**——那需要
7
+ * 外部见证(P5 外送的计数/尾 hash 锚点)。这是 T0 档的「防篡改」上限(同 uid 进程
8
+ * 可写账本所在目录),真正不可抵赖靠 P5 外送,见规格原则 8。
9
+ * - **事件词表**:`ops.command.executed`(统一动作记录)/ `ops.system_path.write`
10
+ * (效应 root 之外的写入)/ `ops.policy.degraded` / `ops.config.security_changed`
11
+ * / `ops.jail.state`。
12
+ * - **`ToolFileEffects` 包装器**:文件效应写口集中拦截 roots 外写入(覆盖全部经
13
+ * fileEffects 的文件工具写口)。**shell 的 roots 外写入不在其内**:shell 账本只
14
+ * 清点 roots,任意命令的写盘面无法穷举追踪——`jail: none`(unconfined)命令以
15
+ * `jail.unconfined: true` 声明「写入未入账」;根因追踪属 P5/增强。
16
+ *
17
+ * 只追加不修改;写失败向上抛(调用方决定降级),绝不静默丢账。
18
+ */
19
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, writeSync } from 'node:fs';
20
+ import { createHash } from 'node:crypto';
21
+ import { dirname } from 'node:path';
22
+ import { isPathUnderRoots } from '../../shared/paths/index.js';
23
+ /** 链首哨兵 */
24
+ export const GENESIS_HASH = '0'.repeat(64);
25
+ /**
26
+ * 规范化 JSON(对象键排序)——hash 输入必须与键序无关。
27
+ *
28
+ * @param value - 任意 JSON 兼容值
29
+ * @returns 稳定序列化文本
30
+ */
31
+ export function canonicalJson(value) {
32
+ if (value === null || typeof value !== 'object')
33
+ return JSON.stringify(value) ?? 'null';
34
+ if (Array.isArray(value))
35
+ return `[${value.map((v) => canonicalJson(v)).join(',')}]`;
36
+ const entries = Object.entries(value)
37
+ .filter(([, v]) => v !== undefined)
38
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
39
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
40
+ }
41
+ /**
42
+ * 计算账目 hash(链的唯一真相源)。
43
+ *
44
+ * @param entry - 不含 hash 的条目字段
45
+ * @returns sha256 十六进制
46
+ */
47
+ export function computeOpsAuditEntryHash(entry) {
48
+ return createHash('sha256').update(canonicalJson(entry)).digest('hex');
49
+ }
50
+ /**
51
+ * 验证一段链(整文件或任意连续片段)。
52
+ *
53
+ * @param entries - 按 seq 升序的条目
54
+ * @returns ok 或首个断裂点
55
+ */
56
+ export function verifyOpsAuditChain(entries) {
57
+ let prevHash = GENESIS_HASH;
58
+ let prevSeq = 0;
59
+ const allowedKeys = ['data', 'event', 'hash', 'prevHash', 'seq', 'ts'];
60
+ for (const entry of entries) {
61
+ // 附加字段不受 hash 保护——读取方不得信任;有即判断裂(防「加字段伪造」)
62
+ const keys = Object.keys(entry).sort();
63
+ if (keys.join(',') !== allowedKeys.join(',')) {
64
+ return { ok: false, entries: entries.length, brokenAtSeq: entry.seq, reason: 'extra_fields' };
65
+ }
66
+ if (entry.seq !== prevSeq + 1) {
67
+ return { ok: false, entries: entries.length, brokenAtSeq: entry.seq, reason: 'seq_gap' };
68
+ }
69
+ if (entry.prevHash !== prevHash) {
70
+ return { ok: false, entries: entries.length, brokenAtSeq: entry.seq, reason: 'prev_hash_mismatch' };
71
+ }
72
+ const expected = computeOpsAuditEntryHash({
73
+ seq: entry.seq,
74
+ ts: entry.ts,
75
+ event: entry.event,
76
+ data: entry.data,
77
+ prevHash: entry.prevHash,
78
+ });
79
+ if (expected !== entry.hash) {
80
+ return { ok: false, entries: entries.length, brokenAtSeq: entry.seq, reason: 'hash_mismatch' };
81
+ }
82
+ prevHash = entry.hash;
83
+ prevSeq = entry.seq;
84
+ }
85
+ return { ok: true, entries: entries.length };
86
+ }
87
+ /**
88
+ * 读回账本全文(供验证/查询)。
89
+ *
90
+ * **只有 ENOENT 是合法空账**(尚未建账);其余读失败抛 `ops_audit_unreadable`、
91
+ * 坏行抛 `ops_audit_corrupt`——把读失败当空账会静默重链并把账本写坏(评审实证)。
92
+ *
93
+ * @param path - 账本文件路径
94
+ * @returns 条目(按写入序);文件不存在返回空数组
95
+ * @throws `ops_audit_unreadable` / `ops_audit_corrupt`
96
+ */
97
+ export function readOpsAuditEntries(path) {
98
+ let body;
99
+ try {
100
+ body = readFileSync(path, 'utf8');
101
+ }
102
+ catch (err) {
103
+ if (err?.code === 'ENOENT')
104
+ return [];
105
+ throw new Error(`ops_audit_unreadable: cannot read ${path}: ${err instanceof Error ? err.message : String(err)}`);
106
+ }
107
+ const entries = [];
108
+ let lineNo = 0;
109
+ for (const line of body.split('\n')) {
110
+ lineNo += 1;
111
+ if (line.trim() === '')
112
+ continue;
113
+ try {
114
+ entries.push(JSON.parse(line));
115
+ }
116
+ catch {
117
+ // 半行(崩溃/写断电)或外部损坏:拒绝当正常读,绝不静默跳行
118
+ throw new Error(`ops_audit_corrupt: unparseable line ${lineNo} in ${path}`);
119
+ }
120
+ }
121
+ return entries;
122
+ }
123
+ /**
124
+ * 运维审计账本(append-only JSONL + hash 链)。
125
+ *
126
+ * 追加为同步写(`appendFileSync`):审计语义优先于吞吐,且顺序天然确定。
127
+ * 启动/首次追加时回读尾条衔接 `seq/prevHash`;尾部不可解析 → 抛
128
+ * `ops_audit_corrupt`(**拒绝续链**——静默重链会把篡改洗成新链)。
129
+ */
130
+ export class OpsAuditJournal {
131
+ path;
132
+ tail;
133
+ /**
134
+ * @param options - `path` 为账本 JSONL 绝对路径
135
+ */
136
+ constructor(options) {
137
+ this.path = options.path;
138
+ }
139
+ /** 账本路径(诊断/测试用) */
140
+ get filePath() {
141
+ return this.path;
142
+ }
143
+ bootstrapTail() {
144
+ if (this.tail)
145
+ return this.tail;
146
+ let entries;
147
+ try {
148
+ entries = readOpsAuditEntries(this.path);
149
+ }
150
+ catch (err) {
151
+ // 读失败/坏行一律拒绝续链(静默重链会把篡改洗成新链);附上类型码
152
+ throw err instanceof Error && err.message.startsWith('ops_audit_')
153
+ ? err
154
+ : new Error(`ops_audit_corrupt: ${err instanceof Error ? err.message : String(err)}`);
155
+ }
156
+ const last = entries.at(-1);
157
+ if (!last) {
158
+ this.tail = { seq: 0, hash: GENESIS_HASH };
159
+ return this.tail;
160
+ }
161
+ // 尾条必须能自证:hash 对不上 = 文件被动过,拒绝把新账接上去
162
+ const expected = computeOpsAuditEntryHash({
163
+ seq: last.seq,
164
+ ts: last.ts,
165
+ event: last.event,
166
+ data: last.data,
167
+ prevHash: last.prevHash,
168
+ });
169
+ if (expected !== last.hash) {
170
+ throw new Error(`ops_audit_corrupt: tail entry hash mismatch at seq ${last.seq} (${this.path})`);
171
+ }
172
+ this.tail = { seq: last.seq, hash: last.hash };
173
+ return this.tail;
174
+ }
175
+ /**
176
+ * 追加一条账目。
177
+ *
178
+ * @param event - 事件名(§7 词表)
179
+ * @param data - 事件载荷(键序无关,hash 走 canonicalJson)
180
+ * @returns 落盘的账目
181
+ */
182
+ append(event, data) {
183
+ const tail = this.bootstrapTail();
184
+ // 载荷先 JSON 归一:hash 口径必须与落盘字节一致(Date 等对象若不归一,
185
+ // verify 会对未篡改的账报 hash_mismatch——评审实证的假告警)
186
+ const normalized = JSON.parse(JSON.stringify(data));
187
+ const body = {
188
+ seq: tail.seq + 1,
189
+ ts: Date.now(),
190
+ event,
191
+ data: normalized,
192
+ prevHash: tail.hash,
193
+ };
194
+ const entry = { ...body, hash: computeOpsAuditEntryHash(body) };
195
+ mkdirSync(dirname(this.path), { recursive: true });
196
+ // 耐久写(fsync):一次崩溃/磁盘满留半行会让账本拒绝续链(fail-loud),
197
+ // 但那是人工修复成本——先把半行概率压到最低
198
+ const fd = openSync(this.path, 'a');
199
+ try {
200
+ writeSync(fd, `${JSON.stringify(entry)}\n`);
201
+ fsyncSync(fd);
202
+ }
203
+ finally {
204
+ closeSync(fd);
205
+ }
206
+ this.tail = { seq: entry.seq, hash: entry.hash };
207
+ return entry;
208
+ }
209
+ /**
210
+ * 全链验证(追加只验尾;中段篡改靠本方法)。
211
+ *
212
+ * @returns ok 或首个断裂点
213
+ */
214
+ verify() {
215
+ // 读不到/坏行也是「验不过」的一种——返回结论而不是把异常抛给调用方
216
+ let entries;
217
+ try {
218
+ entries = readOpsAuditEntries(this.path);
219
+ }
220
+ catch (err) {
221
+ return {
222
+ ok: false,
223
+ entries: 0,
224
+ brokenAtSeq: -1,
225
+ reason: err instanceof Error ? err.message : String(err),
226
+ };
227
+ }
228
+ return verifyOpsAuditChain(entries);
229
+ }
230
+ }
231
+ /**
232
+ * 文件外送收口:宿主侧 append-only JSONL(每行一个信封)。
233
+ *
234
+ * 路径应放在 **agent 可写面之外**(`~/.octopi` 在 host 模式的可写面内——放那里
235
+ * 等于没外送)。写失败向上抛,由调用方降级申报,绝不静默丢外送。
236
+ */
237
+ export class OpsAuditFileExportSink {
238
+ path;
239
+ /**
240
+ * @param options.path - 外送文件绝对路径(宿主侧,agent 不可写)
241
+ */
242
+ constructor(options) {
243
+ this.path = options.path;
244
+ }
245
+ /** 外送文件路径(诊断用) */
246
+ get filePath() {
247
+ return this.path;
248
+ }
249
+ /** @inheritdoc */
250
+ forward(envelope) {
251
+ mkdirSync(dirname(this.path), { recursive: true });
252
+ const fd = openSync(this.path, 'a');
253
+ try {
254
+ writeSync(fd, `${JSON.stringify(envelope)}\n`);
255
+ fsyncSync(fd);
256
+ }
257
+ finally {
258
+ closeSync(fd);
259
+ }
260
+ }
261
+ }
262
+ /**
263
+ * `ToolFileEffects` 装饰器:效应 root 之外的写入统一入 `ops.system_path.write`。
264
+ *
265
+ * 单点覆盖全部文件工具与 shell 账本(它们都经 `fileEffects` 写口),不逐工具打补丁。
266
+ * 记账失败不影响业务写(与 §5.6 记账同策略),但会抛给调用方的降级通道。
267
+ */
268
+ export class OpsAuditedFileEffects {
269
+ inner;
270
+ roots;
271
+ record;
272
+ /**
273
+ * @param inner - 被装饰的真实效应 journal
274
+ * @param options.roots - 效应 root(root 内写入不记 system_path 账)
275
+ * @param options.record - 账目回传(通常进 OpsAuditJournal)
276
+ */
277
+ constructor(inner, options) {
278
+ this.inner = inner;
279
+ this.roots = options.roots;
280
+ this.record = options.record;
281
+ }
282
+ underRoots(path) {
283
+ // Containment in real coordinates: tools now hand back symlink-resolved
284
+ // paths while `roots` keeps the configured spelling. A lexical-only check
285
+ // would audit every in-root write as an out-of-root write under alias roots
286
+ // (macOS /var → /private/var, a symlinked HOME).
287
+ return isPathUnderRoots(path, this.roots);
288
+ }
289
+ noteWrite(op, path, fromPath) {
290
+ // 经 fileEffects 写口的写入本身是 undo 账在管(before/after 都在 TurnFileUndoLog,
291
+ // 含 root 外路径)——本账目只是「越权写告警」的可见层,不虚报可逆性
292
+ const outside = [path, fromPath].filter((p) => p !== undefined && !this.underRoots(p));
293
+ if (outside.length === 0)
294
+ return;
295
+ this.record('ops.system_path.write', {
296
+ op,
297
+ path,
298
+ ...(fromPath !== undefined ? { fromPath } : {}),
299
+ outsideRoots: outside,
300
+ });
301
+ }
302
+ /** @inheritdoc */
303
+ async writeFile(path, data, options) {
304
+ await this.inner.writeFile(path, data, options);
305
+ this.noteWrite('writeFile', path);
306
+ }
307
+ /** @inheritdoc */
308
+ async appendFile(path, data, options) {
309
+ await this.inner.appendFile(path, data, options);
310
+ this.noteWrite('appendFile', path);
311
+ }
312
+ /** @inheritdoc */
313
+ async recordDelete(path, before) {
314
+ await this.inner.recordDelete(path, before);
315
+ this.noteWrite('recordDelete', path);
316
+ }
317
+ /** @inheritdoc */
318
+ async recordCreate(path, after) {
319
+ await this.inner.recordCreate(path, after);
320
+ this.noteWrite('recordCreate', path);
321
+ }
322
+ /** @inheritdoc */
323
+ async recordRename(from, to) {
324
+ await this.inner.recordRename(from, to);
325
+ // mv 进 root = root 外文件消失:from 端也要入账
326
+ this.noteWrite('recordRename', to, from);
327
+ }
328
+ /** @inheritdoc */
329
+ async recordOverwrite(path, before, after) {
330
+ await this.inner.recordOverwrite(path, before, after);
331
+ this.noteWrite('recordOverwrite', path);
332
+ }
333
+ /** @inheritdoc */
334
+ async noteNotReversed(payload) {
335
+ await this.inner.noteNotReversed(payload);
336
+ }
337
+ }