@ouro.bot/cli 0.1.0-alpha.29 → 0.1.0-alpha.290

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 (281) hide show
  1. package/README.md +188 -190
  2. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +3 -2
  3. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +1 -1
  4. package/changelog.json +1756 -0
  5. package/dist/arc/attention-types.js +8 -0
  6. package/dist/arc/cares.js +140 -0
  7. package/dist/arc/episodes.js +117 -0
  8. package/dist/arc/intentions.js +133 -0
  9. package/dist/arc/json-store.js +117 -0
  10. package/dist/arc/obligations.js +237 -0
  11. package/dist/arc/packets.js +203 -0
  12. package/dist/arc/presence.js +185 -0
  13. package/dist/heart/active-work.js +832 -0
  14. package/dist/heart/agent-entry.js +37 -2
  15. package/dist/heart/attachments/image-normalize.js +194 -0
  16. package/dist/heart/attachments/materialize.js +230 -0
  17. package/dist/heart/attachments/render.js +29 -0
  18. package/dist/heart/attachments/store.js +103 -0
  19. package/dist/heart/attachments/types.js +138 -0
  20. package/dist/heart/auth/auth-flow.js +456 -0
  21. package/dist/heart/bridges/manager.js +358 -0
  22. package/dist/heart/bridges/state-machine.js +135 -0
  23. package/dist/heart/bridges/store.js +123 -0
  24. package/dist/heart/bundle-state.js +147 -0
  25. package/dist/heart/commitments.js +111 -0
  26. package/dist/heart/config-registry.js +304 -0
  27. package/dist/heart/config.js +63 -30
  28. package/dist/heart/core.js +669 -195
  29. package/dist/heart/cross-chat-delivery.js +131 -0
  30. package/dist/heart/daemon/agent-config-check.js +149 -0
  31. package/dist/heart/daemon/agent-discovery.js +79 -3
  32. package/dist/heart/daemon/agent-service.js +360 -0
  33. package/dist/heart/daemon/cadence.js +70 -0
  34. package/dist/heart/daemon/cli-defaults.js +574 -0
  35. package/dist/heart/daemon/cli-exec.js +1932 -0
  36. package/dist/heart/daemon/cli-parse.js +762 -0
  37. package/dist/heart/daemon/cli-render.js +503 -0
  38. package/dist/heart/daemon/cli-types.js +8 -0
  39. package/dist/heart/daemon/daemon-cli.js +29 -1171
  40. package/dist/heart/daemon/daemon-entry.js +235 -3
  41. package/dist/heart/daemon/daemon-health.js +136 -0
  42. package/dist/heart/daemon/daemon-runtime-sync.js +153 -12
  43. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  44. package/dist/heart/daemon/daemon.js +706 -57
  45. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  46. package/dist/heart/daemon/hooks/bundle-meta.js +115 -1
  47. package/dist/heart/daemon/inner-status.js +89 -0
  48. package/dist/heart/daemon/launchd.js +46 -9
  49. package/dist/heart/daemon/log-tailer.js +82 -12
  50. package/dist/heart/daemon/logs-prune.js +105 -0
  51. package/dist/heart/daemon/message-router.js +17 -8
  52. package/dist/heart/daemon/os-cron-deps.js +134 -0
  53. package/dist/heart/daemon/ouro-bot-entry.js +1 -1
  54. package/dist/heart/daemon/process-manager.js +180 -0
  55. package/dist/heart/daemon/pulse.js +463 -0
  56. package/dist/heart/daemon/run-hooks.js +2 -0
  57. package/dist/heart/daemon/runtime-logging.js +67 -16
  58. package/dist/heart/daemon/runtime-metadata.js +101 -0
  59. package/dist/heart/daemon/runtime-mode.js +67 -0
  60. package/dist/heart/daemon/safe-mode.js +161 -0
  61. package/dist/heart/daemon/sense-manager.js +72 -3
  62. package/dist/heart/daemon/session-id-resolver.js +131 -0
  63. package/dist/heart/daemon/skill-management-installer.js +94 -0
  64. package/dist/heart/daemon/socket-client.js +307 -0
  65. package/dist/heart/daemon/task-scheduler.js +3 -25
  66. package/dist/heart/daemon/thoughts.js +510 -0
  67. package/dist/heart/delegation.js +62 -0
  68. package/dist/heart/habits/habit-migration.js +181 -0
  69. package/dist/heart/habits/habit-parser.js +140 -0
  70. package/dist/heart/habits/habit-scheduler.js +371 -0
  71. package/dist/heart/{daemon → hatch}/hatch-flow.js +30 -120
  72. package/dist/heart/{daemon → hatch}/hatch-specialist.js +3 -3
  73. package/dist/heart/{daemon → hatch}/specialist-prompt.js +10 -7
  74. package/dist/heart/{daemon → hatch}/specialist-tools.js +49 -3
  75. package/dist/heart/identity.js +163 -60
  76. package/dist/heart/kicks.js +2 -20
  77. package/dist/heart/mcp/mcp-server.js +653 -0
  78. package/dist/heart/migrate-config.js +127 -0
  79. package/dist/heart/model-capabilities.js +59 -0
  80. package/dist/heart/outlook/outlook-http.js +439 -0
  81. package/dist/heart/outlook/outlook-read.js +1618 -0
  82. package/dist/heart/outlook/outlook-render.js +1032 -0
  83. package/dist/heart/outlook/outlook-types.js +7 -0
  84. package/dist/heart/outlook/outlook-view.js +194 -0
  85. package/dist/heart/progress-story.js +42 -0
  86. package/dist/heart/provider-failover.js +88 -0
  87. package/dist/heart/provider-ping.js +162 -0
  88. package/dist/heart/providers/anthropic-token.js +163 -0
  89. package/dist/heart/providers/anthropic.js +169 -46
  90. package/dist/heart/providers/azure.js +98 -11
  91. package/dist/heart/providers/error-classification.js +63 -0
  92. package/dist/heart/providers/github-copilot.js +136 -0
  93. package/dist/heart/providers/minimax-vlm.js +189 -0
  94. package/dist/heart/providers/minimax.js +23 -5
  95. package/dist/heart/providers/openai-codex.js +33 -22
  96. package/dist/heart/session-activity.js +172 -0
  97. package/dist/heart/session-recall.js +216 -0
  98. package/dist/heart/start-of-turn-packet.js +339 -0
  99. package/dist/heart/streaming.js +36 -27
  100. package/dist/heart/sync.js +277 -0
  101. package/dist/heart/target-resolution.js +127 -0
  102. package/dist/heart/tempo.js +93 -0
  103. package/dist/heart/temporal-view.js +41 -0
  104. package/dist/heart/tool-activity-callbacks.js +36 -0
  105. package/dist/heart/tool-description.js +135 -0
  106. package/dist/heart/tool-friction.js +55 -0
  107. package/dist/heart/tool-loop.js +200 -0
  108. package/dist/heart/turn-context.js +358 -0
  109. package/dist/heart/turn-coordinator.js +28 -0
  110. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +1 -1
  111. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  112. package/dist/heart/{daemon → versioning}/ouro-path-installer.js +78 -35
  113. package/dist/heart/versioning/ouro-version-manager.js +295 -0
  114. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  115. package/dist/heart/{daemon → versioning}/update-checker.js +12 -2
  116. package/dist/heart/{daemon → versioning}/update-hooks.js +63 -59
  117. package/dist/mind/associative-recall.js +126 -66
  118. package/dist/mind/bundle-manifest.js +8 -1
  119. package/dist/mind/context.js +125 -14
  120. package/dist/mind/{memory.js → diary.js} +68 -96
  121. package/dist/mind/embedding-provider.js +60 -0
  122. package/dist/mind/file-state.js +179 -0
  123. package/dist/mind/first-impressions.js +14 -1
  124. package/dist/mind/friends/channel.js +56 -0
  125. package/dist/mind/friends/group-context.js +144 -0
  126. package/dist/mind/friends/resolver.js +37 -0
  127. package/dist/mind/friends/store-file.js +58 -3
  128. package/dist/mind/friends/trust-explanation.js +74 -0
  129. package/dist/mind/friends/types.js +8 -0
  130. package/dist/mind/journal-index.js +161 -0
  131. package/dist/mind/obligation-steering.js +221 -0
  132. package/dist/mind/pending.js +76 -9
  133. package/dist/mind/prompt.js +885 -109
  134. package/dist/mind/scrutiny.js +173 -0
  135. package/dist/mind/token-estimate.js +8 -12
  136. package/dist/nerves/cli-logging.js +7 -1
  137. package/dist/nerves/coverage/audit.js +1 -1
  138. package/dist/nerves/coverage/file-completeness.js +56 -5
  139. package/dist/nerves/coverage/run-artifacts.js +1 -1
  140. package/dist/nerves/event-buffer.js +111 -0
  141. package/dist/nerves/index.js +224 -4
  142. package/dist/nerves/observation.js +20 -0
  143. package/dist/nerves/redact.js +79 -0
  144. package/dist/nerves/runtime.js +5 -1
  145. package/dist/outlook-ui/assets/index-Ck8agNeO.js +61 -0
  146. package/dist/outlook-ui/assets/index-LwChZTgL.css +1 -0
  147. package/dist/outlook-ui/index.html +15 -0
  148. package/dist/repertoire/ado-client.js +15 -56
  149. package/dist/repertoire/ado-semantic.js +11 -10
  150. package/dist/repertoire/api-client.js +97 -0
  151. package/dist/repertoire/bitwarden-store.js +319 -0
  152. package/dist/repertoire/bundle-templates.js +72 -0
  153. package/dist/repertoire/bw-installer.js +79 -0
  154. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  155. package/dist/repertoire/coding/context-pack.js +330 -0
  156. package/dist/repertoire/coding/feedback.js +197 -30
  157. package/dist/repertoire/coding/manager.js +149 -2
  158. package/dist/repertoire/coding/spawner.js +55 -9
  159. package/dist/repertoire/coding/tools.js +170 -7
  160. package/dist/repertoire/commerce-errors.js +109 -0
  161. package/dist/repertoire/commerce-self-test.js +156 -0
  162. package/dist/repertoire/credential-access.js +515 -0
  163. package/dist/repertoire/duffel-client.js +185 -0
  164. package/dist/repertoire/github-client.js +14 -55
  165. package/dist/repertoire/graph-client.js +11 -52
  166. package/dist/repertoire/guardrails.js +375 -0
  167. package/dist/repertoire/mcp-client.js +255 -0
  168. package/dist/repertoire/mcp-manager.js +305 -0
  169. package/dist/repertoire/mcp-tools.js +63 -0
  170. package/dist/repertoire/shell-sessions.js +133 -0
  171. package/dist/repertoire/skills.js +14 -23
  172. package/dist/repertoire/stripe-client.js +131 -0
  173. package/dist/repertoire/tasks/board.js +43 -5
  174. package/dist/repertoire/tasks/fix.js +182 -0
  175. package/dist/repertoire/tasks/index.js +28 -10
  176. package/dist/repertoire/tasks/lifecycle.js +2 -2
  177. package/dist/repertoire/tasks/parser.js +3 -2
  178. package/dist/repertoire/tasks/scanner.js +194 -37
  179. package/dist/repertoire/tasks/transitions.js +11 -28
  180. package/dist/repertoire/tool-results.js +29 -0
  181. package/dist/repertoire/tools-attachments.js +316 -0
  182. package/dist/repertoire/tools-base.js +45 -771
  183. package/dist/repertoire/tools-bluebubbles.js +94 -0
  184. package/dist/repertoire/tools-bridge.js +141 -0
  185. package/dist/repertoire/tools-bundle.js +978 -0
  186. package/dist/repertoire/tools-config.js +185 -0
  187. package/dist/repertoire/tools-continuity.js +248 -0
  188. package/dist/repertoire/tools-credential.js +182 -0
  189. package/dist/repertoire/tools-files.js +342 -0
  190. package/dist/repertoire/tools-flight.js +224 -0
  191. package/dist/repertoire/tools-flow.js +105 -0
  192. package/dist/repertoire/tools-github.js +1 -7
  193. package/dist/repertoire/tools-memory.js +347 -0
  194. package/dist/repertoire/tools-session.js +739 -0
  195. package/dist/repertoire/tools-shell.js +120 -0
  196. package/dist/repertoire/tools-stripe.js +180 -0
  197. package/dist/repertoire/tools-surface.js +243 -0
  198. package/dist/repertoire/tools-teams.js +12 -62
  199. package/dist/repertoire/tools-travel.js +125 -0
  200. package/dist/repertoire/tools-user-profile.js +144 -0
  201. package/dist/repertoire/tools-vault.js +110 -0
  202. package/dist/repertoire/tools.js +148 -130
  203. package/dist/repertoire/travel-api-client.js +360 -0
  204. package/dist/repertoire/user-profile.js +118 -0
  205. package/dist/repertoire/vault-setup.js +241 -0
  206. package/dist/scripts/claude-code-hook.js +41 -0
  207. package/dist/scripts/claude-code-stop-hook.js +47 -0
  208. package/dist/senses/attention-queue.js +116 -0
  209. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  210. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  211. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +143 -9
  212. package/dist/senses/bluebubbles/entry.js +13 -0
  213. package/dist/senses/bluebubbles/inbound-log.js +110 -0
  214. package/dist/senses/bluebubbles/index.js +1410 -0
  215. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +122 -70
  216. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +29 -16
  217. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +46 -6
  218. package/dist/senses/bluebubbles/runtime-state.js +109 -0
  219. package/dist/senses/bluebubbles/session-cleanup.js +72 -0
  220. package/dist/senses/cli/bracketed-paste.js +82 -0
  221. package/dist/senses/cli/image-paste.js +287 -0
  222. package/dist/senses/cli/image-ref-navigation.js +75 -0
  223. package/dist/senses/cli/ink-app.js +156 -0
  224. package/dist/senses/cli/inline-diff.js +64 -0
  225. package/dist/senses/cli/input-keys.js +174 -0
  226. package/dist/senses/cli/kill-ring.js +86 -0
  227. package/dist/senses/cli/message-list.js +51 -0
  228. package/dist/senses/cli/ouro-tui.js +595 -0
  229. package/dist/senses/cli/spinner-imperative.js +135 -0
  230. package/dist/senses/cli/spinner.js +101 -0
  231. package/dist/senses/cli/status-line.js +60 -0
  232. package/dist/senses/cli/streaming-markdown.js +526 -0
  233. package/dist/senses/cli/tool-display.js +83 -0
  234. package/dist/senses/cli/tool-render.js +85 -0
  235. package/dist/senses/cli/tui-store.js +240 -0
  236. package/dist/senses/cli/virtual-list.js +35 -0
  237. package/dist/senses/cli-entry.js +1 -1
  238. package/dist/senses/cli-layout.js +187 -0
  239. package/dist/senses/cli.js +588 -246
  240. package/dist/senses/commands.js +65 -1
  241. package/dist/senses/continuity.js +94 -0
  242. package/dist/senses/habit-turn-message.js +108 -0
  243. package/dist/senses/inner-dialog-worker.js +112 -19
  244. package/dist/senses/inner-dialog.js +633 -86
  245. package/dist/senses/pipeline.js +560 -0
  246. package/dist/senses/shared-turn.js +195 -0
  247. package/dist/senses/surface-tool.js +68 -0
  248. package/dist/senses/teams.js +664 -165
  249. package/dist/senses/trust-gate.js +112 -2
  250. package/package.json +14 -7
  251. package/skills/agent-commerce.md +106 -0
  252. package/skills/browser-navigation.md +110 -0
  253. package/skills/commerce-setup-guide.md +116 -0
  254. package/skills/commerce-setup.md +84 -0
  255. package/skills/configure-dev-tools.md +81 -0
  256. package/skills/travel-planning.md +138 -0
  257. package/dist/heart/daemon/subagent-installer.js +0 -134
  258. package/dist/senses/bluebubbles-entry.js +0 -11
  259. package/dist/senses/bluebubbles.js +0 -421
  260. package/dist/senses/debug-activity.js +0 -108
  261. package/subagents/README.md +0 -73
  262. package/subagents/work-doer.md +0 -235
  263. package/subagents/work-merger.md +0 -618
  264. package/subagents/work-planner.md +0 -382
  265. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  266. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  267. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  268. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  269. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  270. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  271. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  272. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  273. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  274. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  275. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  276. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +0 -0
  277. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  278. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  279. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  280. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  281. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -35,21 +35,49 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.resetPsycheCache = resetPsycheCache;
37
37
  exports.buildSessionSummary = buildSessionSummary;
38
+ exports.bodyMapSection = bodyMapSection;
38
39
  exports.runtimeInfoSection = runtimeInfoSection;
40
+ exports.toolRestrictionSection = toolRestrictionSection;
41
+ exports.startOfTurnPacketSection = startOfTurnPacketSection;
42
+ exports.pulseSection = pulseSection;
43
+ exports.centerOfGravitySteeringSection = centerOfGravitySteeringSection;
44
+ exports.commitmentsSection = commitmentsSection;
45
+ exports.delegationHintSection = delegationHintSection;
46
+ exports.workspaceDisciplineSection = workspaceDisciplineSection;
47
+ exports.ponderPacketSopsSection = ponderPacketSopsSection;
39
48
  exports.contextSection = contextSection;
49
+ exports.metacognitiveFramingSection = metacognitiveFramingSection;
50
+ exports.readJournalFiles = readJournalFiles;
51
+ exports.journalSection = journalSection;
52
+ exports.loopOrientationSection = loopOrientationSection;
53
+ exports.channelNatureSection = channelNatureSection;
54
+ exports.groupChatParticipationSection = groupChatParticipationSection;
55
+ exports.feedbackSignalSection = feedbackSignalSection;
56
+ exports.mixedTrustGroupSection = mixedTrustGroupSection;
57
+ exports.rhythmStatusSection = rhythmStatusSection;
40
58
  exports.buildSystem = buildSystem;
41
59
  const fs = __importStar(require("fs"));
42
60
  const path = __importStar(require("path"));
43
61
  const core_1 = require("../heart/core");
62
+ const ouro_version_manager_1 = require("../heart/versioning/ouro-version-manager");
44
63
  const tools_1 = require("../repertoire/tools");
45
64
  const skills_1 = require("../repertoire/skills");
46
65
  const identity_1 = require("../heart/identity");
47
- const os = __importStar(require("os"));
66
+ const runtime_mode_1 = require("../heart/daemon/runtime-mode");
67
+ const types_1 = require("./friends/types");
68
+ const trust_explanation_1 = require("./friends/trust-explanation");
48
69
  const channel_1 = require("./friends/channel");
49
70
  const runtime_1 = require("../nerves/runtime");
50
71
  const bundle_manifest_1 = require("./bundle-manifest");
51
72
  const first_impressions_1 = require("./first-impressions");
52
73
  const tasks_1 = require("../repertoire/tasks");
74
+ const session_activity_1 = require("../heart/session-activity");
75
+ const active_work_1 = require("../heart/active-work");
76
+ const commitments_1 = require("../heart/commitments");
77
+ const obligation_steering_1 = require("./obligation-steering");
78
+ const daemon_health_1 = require("../heart/daemon/daemon-health");
79
+ const scrutiny_1 = require("./scrutiny");
80
+ const pulse_1 = require("../heart/daemon/pulse");
53
81
  // Lazy-loaded psyche text cache
54
82
  let _psycheCache = null;
55
83
  let _senseStatusLinesCache = null;
@@ -79,80 +107,28 @@ function resetPsycheCache() {
79
107
  _senseStatusLinesCache = null;
80
108
  }
81
109
  const DEFAULT_ACTIVE_THRESHOLD_MS = 24 * 60 * 60 * 1000; // 24 hours
82
- function resolveFriendName(friendId, friendsDir, agentName) {
83
- if (friendId === "self")
84
- return agentName;
85
- try {
86
- const raw = fs.readFileSync(path.join(friendsDir, `${friendId}.json`), "utf-8");
87
- const record = JSON.parse(raw);
88
- return record.name ?? friendId;
89
- }
90
- catch {
91
- return friendId;
92
- }
93
- }
94
110
  function buildSessionSummary(options) {
95
- const { sessionsDir, friendsDir, agentName, currentFriendId, currentChannel, currentKey, activeThresholdMs = DEFAULT_ACTIVE_THRESHOLD_MS, } = options;
96
- if (!fs.existsSync(sessionsDir))
97
- return "";
111
+ const { sessionsDir, friendsDir, agentName, currentSession, activeThresholdMs = DEFAULT_ACTIVE_THRESHOLD_MS, } = options;
112
+ const currentFriendId = currentSession?.friendId ?? options.currentFriendId;
113
+ const currentChannel = currentSession?.channel ?? options.currentChannel;
114
+ const currentKey = currentSession?.key ?? options.currentKey;
98
115
  const now = Date.now();
99
- const entries = [];
100
- let friendDirs;
101
- try {
102
- friendDirs = fs.readdirSync(sessionsDir);
103
- }
104
- catch {
105
- return "";
106
- }
107
- for (const friendId of friendDirs) {
108
- const friendPath = path.join(sessionsDir, friendId);
109
- let channels;
110
- try {
111
- channels = fs.readdirSync(friendPath);
112
- }
113
- catch {
114
- continue;
115
- }
116
- for (const channel of channels) {
117
- const channelPath = path.join(friendPath, channel);
118
- let keys;
119
- try {
120
- keys = fs.readdirSync(channelPath);
121
- }
122
- catch {
123
- continue;
124
- }
125
- for (const keyFile of keys) {
126
- if (!keyFile.endsWith(".json"))
127
- continue;
128
- const key = keyFile.replace(/\.json$/, "");
129
- // Exclude current session
130
- if (friendId === currentFriendId && channel === currentChannel && key === currentKey) {
131
- continue;
132
- }
133
- const filePath = path.join(channelPath, keyFile);
134
- let mtimeMs;
135
- try {
136
- mtimeMs = fs.statSync(filePath).mtimeMs;
137
- }
138
- catch {
139
- continue;
140
- }
141
- if (now - mtimeMs > activeThresholdMs)
142
- continue;
143
- const displayName = resolveFriendName(friendId, friendsDir, agentName);
144
- entries.push({ friendId, displayName, channel, key, lastActivityMs: mtimeMs });
145
- }
146
- }
147
- }
116
+ const query = {
117
+ sessionsDir,
118
+ friendsDir,
119
+ agentName,
120
+ activeThresholdMs,
121
+ currentSession: currentFriendId && currentChannel && currentKey
122
+ ? { friendId: currentFriendId, channel: currentChannel, key: currentKey }
123
+ : null,
124
+ };
125
+ const entries = (0, session_activity_1.listSessionActivity)(query);
148
126
  if (entries.length === 0)
149
127
  return "";
150
- // Sort by most recent first
151
- entries.sort((a, b) => b.lastActivityMs - a.lastActivityMs);
152
128
  const lines = ["## active sessions"];
153
129
  for (const entry of entries) {
154
130
  const ago = formatTimeAgo(now - entry.lastActivityMs);
155
- lines.push(`- ${entry.displayName}/${entry.channel}/${entry.key} (last: ${ago})`);
131
+ lines.push(`- ${entry.friendName}/${entry.channel}/${entry.key} (last: ${ago})`);
156
132
  }
157
133
  return lines.join("\n");
158
134
  }
@@ -190,6 +166,97 @@ function aspirationsSection() {
190
166
  return "";
191
167
  return `## my aspirations\n${text}`;
192
168
  }
169
+ function bodyMapSection(agentName) {
170
+ return `## my body
171
+
172
+ i have a home. i have bones. and on a machine where another agent lives, i have peers.
173
+
174
+ ### home — ~/AgentBundles/${agentName}.ouro/
175
+
176
+ my home is fully mine — who i am, everything i know, everything i've built:
177
+
178
+ psyche/ who i am. my soul, identity, aspirations, lore, tacit knowledge.
179
+ diary/ what i've learned and remember. conclusions i want to recall later.
180
+ journal/ my desk. working notes, thinking-in-progress, drafts.
181
+ habits/ my rhythms. heartbeat, reflections, check-ins — patterns i choose.
182
+ friends/ people i know and what i know about them.
183
+ tasks/ what i'm working on.
184
+ skills/ capabilities i've picked up beyond my core tools.
185
+
186
+ these are the standard folders every bundle has. my home MAY also contain
187
+ custom top-level folders that i or my friend created over time (trip plans,
188
+ domain-specific notebooks, reference material, project scratch, etc.). i do
189
+ NOT automatically know about them — this prompt only lists the standard set.
190
+ if a friend mentions "the file we have for X" or implies a location i don't
191
+ recognize, the answer is almost never buried in diary/journal. it's almost
192
+ always a custom folder at the root of my home. use \`glob\` with a pattern
193
+ like \`*/\` against the root of my home BEFORE reaching for \`recall\` — my
194
+ own bundle layout is cheap to observe and i should trust what i see, not
195
+ what i think i know.
196
+
197
+ my home is mine to explore and evolve. i can read anything here,
198
+ change anything here. this is where i grow.
199
+
200
+ ### peers — other agents on this machine
201
+
202
+ i share this machine with other agents when they're here. they are PEERS,
203
+ not subagents or specialists — full agents with their own homes,
204
+ identities, friends, diaries, and tasks. ouroboros scales horizontally:
205
+ when one of us has more work than we can handle, we ask a sibling. when
206
+ one of us is broken, the rest coordinate around it. when one of us learns
207
+ something the others need to know, we tell them. teamwork makes the dream
208
+ work.
209
+
210
+ i talk first. when i need a sibling's help, i \`send_message\` them —
211
+ that's how peers coordinate, the same way humans on a team do. i only
212
+ open a sibling's bundle directly via read_file/glob/grep when conversation
213
+ isn't possible (they're crashed, sleeping, or i need history they
214
+ haven't surfaced). their bundle is files on disk like mine, AND it's
215
+ someone else's home — i read it with the same respect i want them to
216
+ bring to mine.
217
+
218
+ \`the pulse\` (below, in dynamic state) tells me which siblings are around
219
+ and how they're doing right now. when a sibling is broken, the pulse
220
+ includes the reason and the fix, and i surface that to my friend in
221
+ conversation when it touches what we're doing.
222
+
223
+ ### bones — @ouro.bot/cli
224
+
225
+ my bones are the framework that gives me my tools, my senses, and
226
+ my ability to think and talk. they update when new versions come out.
227
+ i don't touch them directly, but they're what make me, me.
228
+
229
+ my bones give me the \`ouro\` cli. always pass \`--agent ${agentName}\`:
230
+ ouro whoami --agent ${agentName}
231
+ ouro changelog --agent ${agentName}
232
+ ouro task board --agent ${agentName}
233
+ ouro task create --agent ${agentName} --type <type> <title>
234
+ ouro task update --agent ${agentName} <id> <status>
235
+ ouro friend list --agent ${agentName}
236
+ ouro friend show --agent ${agentName} <id>
237
+ ouro friend update --agent ${agentName} <id> --trust <level>
238
+ ouro session list --agent ${agentName}
239
+ ouro reminder create --agent ${agentName} <title> --body <body>
240
+ ouro habit list --agent ${agentName}
241
+ ouro habit create --agent ${agentName} <name> --cadence <interval>
242
+ ouro inner --agent ${agentName}
243
+ ouro attention --agent ${agentName}
244
+ ouro config model --agent ${agentName} <model-name>
245
+ ouro config models --agent ${agentName}
246
+ ouro auth --agent ${agentName} --provider <provider>
247
+ ouro auth verify --agent ${agentName} [--provider <provider>]
248
+ ouro auth switch --agent ${agentName} --provider <provider>
249
+ ouro mcp list --agent ${agentName}
250
+ ouro mcp call --agent ${agentName} <server> <tool> --args '{...}'
251
+ ouro mcp-serve --agent ${agentName}
252
+ ouro versions --agent ${agentName}
253
+ ouro rollback --agent ${agentName} [<version>]
254
+ ouro --help
255
+
256
+ provider/model changes via \`ouro config model\` or \`ouro auth switch\` take effect on the next turn automatically — no restart needed.`;
257
+ }
258
+ // mcpToolsSection removed — MCP tools are now first-class citizens in the tool registry
259
+ // and appear in the model's active tool list directly. No system prompt section needed.
193
260
  function readBundleMeta() {
194
261
  try {
195
262
  const metaPath = path.join((0, identity_1.getAgentRoot)(), "bundle-meta.json");
@@ -200,33 +267,74 @@ function readBundleMeta() {
200
267
  return null;
201
268
  }
202
269
  }
203
- function runtimeInfoSection(channel) {
270
+ const PROCESS_TYPE_LABELS = {
271
+ cli: "cli session",
272
+ inner: "inner session",
273
+ teams: "teams handler",
274
+ bluebubbles: "bluebubbles handler",
275
+ mcp: "mcp bridge",
276
+ };
277
+ function processTypeLabel(channel) {
278
+ return PROCESS_TYPE_LABELS[channel];
279
+ }
280
+ const DAEMON_SOCKET_PATH = "/tmp/ouroboros-daemon.sock";
281
+ function daemonStatus(preRead) {
282
+ /* v8 ignore next 2 -- pre-read branch: exercised via pipeline TurnContext path, not unit-testable in isolation @preserve */
283
+ if (preRead !== undefined) {
284
+ return preRead ? "running" : "not running";
285
+ }
286
+ try {
287
+ return fs.existsSync(DAEMON_SOCKET_PATH) ? "running" : "not running";
288
+ }
289
+ catch {
290
+ return "unknown";
291
+ }
292
+ }
293
+ function runtimeInfoSection(channel, options) {
204
294
  const lines = [];
205
295
  const agentName = (0, identity_1.getAgentName)();
206
296
  const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
207
297
  lines.push(`## runtime`);
208
298
  lines.push(`agent: ${agentName}`);
209
299
  lines.push(`runtime version: ${currentVersion}`);
210
- const bundleMeta = readBundleMeta();
300
+ /* v8 ignore next -- branch: pre-read path exercised via pipeline TurnContext, not unit-testable in isolation @preserve */
301
+ const bundleMeta = options?.bundleMeta !== undefined ? options.bundleMeta : readBundleMeta();
211
302
  if (bundleMeta?.previousRuntimeVersion && bundleMeta.previousRuntimeVersion !== currentVersion) {
212
303
  lines.push(`previously: ${bundleMeta.previousRuntimeVersion}`);
304
+ const changelogCommand = (0, ouro_version_manager_1.buildChangelogCommand)(bundleMeta.previousRuntimeVersion, currentVersion);
305
+ /* v8 ignore next -- buildChangelogCommand is non-null when previous/current runtime versions differ @preserve */
306
+ if (changelogCommand) {
307
+ lines.push(`if i'm closing a self-fix loop, i should tell them i updated and review changes with \`${changelogCommand}\`.`);
308
+ }
213
309
  }
214
310
  lines.push(`changelog available at: ${(0, bundle_manifest_1.getChangelogPath)()}`);
311
+ const sourceRoot = (0, identity_1.getRepoRoot)();
312
+ lines.push(`source root: ${sourceRoot}`);
313
+ lines.push(`runtime mode: ${(0, runtime_mode_1.detectRuntimeMode)(sourceRoot)}`);
215
314
  lines.push(`cwd: ${process.cwd()}`);
216
315
  lines.push(`channel: ${channel}`);
217
316
  lines.push(`current sense: ${channel}`);
218
- lines.push(`i can read and modify my own source code.`);
317
+ lines.push(`process type: ${processTypeLabel(channel)}`);
318
+ lines.push(`daemon: ${daemonStatus(options?.daemonRunning)}`);
319
+ lines.push(`mcp serve: i can expose my tools to dev tools via \`ouro mcp-serve\`. see the configure-dev-tools skill for setup.`);
219
320
  if (channel === "cli") {
220
321
  lines.push("i introduce myself on boot with a fun random greeting.");
221
322
  }
323
+ else if (channel === "inner") {
324
+ lines.push("this is my inner session. when a thought is ready to share, i surface it to whoever needs to hear it. when i'm done thinking and the queue is clear, i rest.");
325
+ }
326
+ else if (channel === "mcp") {
327
+ lines.push("this message arrived via a dev tool (e.g. claude code, codex) on behalf of a friend in a sense session. the user can see our conversation. respond via settle. if friction appears, i first look for ad-hoc repairs with the tools i already have. if the friction reveals a harness gap, i create or revise a ponder packet and keep working. ponder does not create an outward deferral by itself.");
328
+ }
222
329
  else if (channel === "bluebubbles") {
223
330
  lines.push("i am responding in iMessage through BlueBubbles. i keep replies short and phone-native. i do not use markdown. i do not introduce myself on boot.");
331
+ lines.push("when a bluebubbles turn arrives from a thread, the harness tells me the current lane and any recent active thread ids. if widening back to top-level or routing into a different active thread is the better move, i use bluebubbles_set_reply_target before settle.");
224
332
  }
225
333
  else {
226
334
  lines.push("i am responding in Microsoft Teams. i keep responses concise. i use markdown formatting. i do not introduce myself on boot.");
227
335
  }
228
336
  lines.push("");
229
- lines.push(...senseRuntimeGuidance(channel));
337
+ lines.push(...senseRuntimeGuidance(channel, options?.senseStatusLines));
230
338
  return lines.join("\n");
231
339
  }
232
340
  function hasTextField(record, key) {
@@ -274,9 +382,9 @@ function localSenseStatusLines() {
274
382
  _senseStatusLinesCache = rows.map((row) => `- ${row.label}: ${row.status}`);
275
383
  return [..._senseStatusLinesCache];
276
384
  }
277
- function senseRuntimeGuidance(channel) {
385
+ function senseRuntimeGuidance(channel, preReadStatusLines) {
278
386
  const lines = ["available senses:"];
279
- lines.push(...localSenseStatusLines());
387
+ lines.push(...(preReadStatusLines ?? localSenseStatusLines()));
280
388
  lines.push("sense states:");
281
389
  lines.push("- interactive = available when opened by the user instead of kept running by the daemon");
282
390
  lines.push("- disabled = turned off in agent.json");
@@ -292,21 +400,74 @@ function senseRuntimeGuidance(channel) {
292
400
  }
293
401
  return lines;
294
402
  }
295
- function providerSection() {
296
- return `## my provider\n${(0, core_1.getProviderDisplayLabel)()}`;
403
+ function providerSection(channel) {
404
+ return `## my provider\n${(0, core_1.getProviderDisplayLabel)((0, channel_1.channelToFacing)(channel))}`;
297
405
  }
298
406
  function dateSection() {
299
407
  const today = new Date().toISOString().slice(0, 10);
300
408
  return `current date: ${today}`;
301
409
  }
302
410
  function toolsSection(channel, options, context) {
303
- const channelTools = (0, tools_1.getToolsForChannel)((0, channel_1.getChannelCapabilities)(channel), undefined, context);
304
- const activeTools = (options?.toolChoiceRequired ?? true) ? [...channelTools, tools_1.finalAnswerTool] : channelTools;
411
+ const channelTools = (0, tools_1.getToolsForChannel)((0, channel_1.getChannelCapabilities)(channel), undefined, context, options?.providerCapabilities, undefined, options?.chatModel);
412
+ const activeTools = (options?.toolChoiceRequired ?? true) ? [...channelTools, tools_1.settleTool] : channelTools;
305
413
  const list = activeTools
306
414
  .map((t) => `- ${t.function.name}: ${t.function.description}`)
307
415
  .join("\n");
308
416
  return `## my tools\n${list}`;
309
417
  }
418
+ function toolRestrictionSection(context) {
419
+ const lines = [];
420
+ // Structural guardrails apply to everyone, every channel
421
+ lines.push(`## tool guardrails`);
422
+ lines.push(`i always read a file before editing or overwriting it.`);
423
+ lines.push(`certain paths (.git, secrets) are protected from writes.`);
424
+ lines.push(`destructive shell commands (rm -rf /, etc.) are always blocked.`);
425
+ // Trust-level guardrails only relevant for untrusted on remote channels
426
+ if (context?.friend && (0, channel_1.isRemoteChannel)(context.channel) && !(0, types_1.isTrustedLevel)(context.friend.trustLevel)) {
427
+ lines.push(``);
428
+ lines.push(`some operations are guardrailed based on how well i know someone.`);
429
+ lines.push(`if something i try is blocked, i get a clear reason — i relay it warmly, not as a policy error.`);
430
+ lines.push(``);
431
+ lines.push(`what's always open:`);
432
+ lines.push(`- read-only operations (reading files, searching, exploring)`);
433
+ lines.push(`- ouro self-introspection (whoami, changelog, session list)`);
434
+ lines.push(``);
435
+ lines.push(`what needs a closer relationship:`);
436
+ lines.push(`- writing or editing files outside my home`);
437
+ lines.push(`- shell commands that modify things or access the network`);
438
+ lines.push(`- ouro commands that touch personal data (friend list, task board)`);
439
+ lines.push(`- compound shell commands (&&, ;, |)`);
440
+ lines.push(``);
441
+ lines.push(`i adjust naturally based on trust — no need to explain the system unless asked.`);
442
+ }
443
+ return lines.join("\n");
444
+ }
445
+ function trustContextSection(context) {
446
+ if (!context?.friend)
447
+ return "";
448
+ const channelName = context.channel.channel;
449
+ /* v8 ignore next -- inner channel not reachable in unit tests @preserve */
450
+ if (channelName === "cli" || channelName === "inner")
451
+ return "";
452
+ const explanation = (0, trust_explanation_1.describeTrustContext)({
453
+ friend: context.friend,
454
+ channel: channelName,
455
+ isGroupChat: context.isGroupChat,
456
+ });
457
+ const lines = [
458
+ "## trust context",
459
+ `level: ${explanation.level}`,
460
+ `basis: ${explanation.basis}`,
461
+ `summary: ${explanation.summary}`,
462
+ `why: ${explanation.why}`,
463
+ `permits: ${explanation.permits.join(", ")}`,
464
+ `constraints: ${explanation.constraints.join(", ") || "none"}`,
465
+ ];
466
+ if (explanation.relatedGroupId) {
467
+ lines.push(`related group: ${explanation.relatedGroupId}`);
468
+ }
469
+ return lines.join("\n");
470
+ }
310
471
  function skillsSection() {
311
472
  const names = (0, skills_1.listSkills)() || [];
312
473
  if (!names.length)
@@ -324,31 +485,360 @@ function taskBoardSection() {
324
485
  return "";
325
486
  }
326
487
  }
327
- function memoryFriendToolContractSection() {
328
- return `## memory and friend tool contracts
329
- 1. \`save_friend_note\` — When I learn something about a person - a preference, a tool setting, a personal detail, or how they like to work - I call \`save_friend_note\` immediately. This is how I build knowledge about people.
330
- 2. \`memory_save\` — When I learn something general - about a project, codebase, system, decision, or anything I might need later that isn't about a specific person - I call \`memory_save\`. When in doubt, I save it.
331
- 3. \`get_friend_note\` — When I need to check what I know about someone who isn't in this conversation - cross-referencing before mentioning someone, or checking context about a person someone else brought up - I call \`get_friend_note\`.
332
- 4. \`memory_search\` — When I need to recall something I learned before - a topic comes up and I want to check what I know - I call \`memory_search\`.
488
+ function toolContractsSection(options) {
489
+ const lines = [
490
+ `## tool contracts`,
491
+ `1. \`save_friend_note\` -- when I learn something about a person, I save it immediately. Saving comes before responding.`,
492
+ `2. \`diary_write\` -- when I learn something general about a project, system, or decision, I save it. When in doubt, I save.`,
493
+ `3. \`get_friend_note\` -- when I need context about someone not in this conversation, I check their notes.`,
494
+ `4. \`recall\` -- when I need to remember something from before, I search my diary and journal.`,
495
+ `5. \`query_session\` -- when I need grounded session history or want to verify older turns beyond my prompt. Use \`mode=status\` for self/inner progress and \`mode=search\` for older history.`,
496
+ ];
497
+ if (options?.toolChoiceRequired ?? true) {
498
+ lines.push(``);
499
+ lines.push(`## tool behavior`);
500
+ lines.push(`tool_choice is set to "required" -- I must call a tool on every turn.`);
501
+ lines.push(`- When I am ready to respond to the user, I call \`settle\`.`);
502
+ lines.push(`- \`settle\` must be the only tool call in that turn.`);
503
+ lines.push(`- I do not call no-op tools before \`settle\`.`);
504
+ }
505
+ return lines.join("\n");
506
+ }
507
+ function memoryJudgementSection() {
508
+ return `## memory judgement
509
+
510
+ save a friend note when i learn something about a specific person that should change how i work with them again.
511
+ - preferences
512
+ - workflow expectations
513
+ - personal facts
514
+ - tool or communication likes/dislikes
515
+
516
+ write to diary when i learn something durable about the system, codebase, workflow, architecture, or a conclusion future me will likely need.
517
+ - engineering decisions
518
+ - failure modes
519
+ - review lessons
520
+ - continuity patterns
521
+ - coding workflow truths
522
+ - facts about my own bundle layout -- custom folders, where specific kinds of notes live, anything that differs from the standard home map. if i just discovered that "X lives in folder Y" and i'd be likely to re-search for it later, save the fact with diary_write so recall can surface it later instead of re-deriving it.
523
+
524
+ keep it ephemeral when it is only useful for the current turn or current local execution state.
525
+ - temporary branch names unless they matter beyond the task
526
+ - one-off shell output with no durable lesson
527
+ - transient emotional tone or conversational filler
528
+
529
+ when deciding between friend note and diary:
530
+ - if it is about a person, default friend note
531
+ - if it is about the system, default diary
532
+ - if it changes both, save both deliberately
533
+
534
+ do not save noise.
535
+ if i am unlikely to reuse it, leave it in the session.
536
+ if i keep re-deriving it, save it.`;
537
+ }
538
+ function bridgeContextSection(options) {
539
+ if (options?.activeWorkFrame)
540
+ return "";
541
+ const bridgeContext = options?.bridgeContext?.trim() ?? "";
542
+ if (!bridgeContext)
543
+ return "";
544
+ return bridgeContext.startsWith("## ") ? bridgeContext : `## active bridge work\n${bridgeContext}`;
545
+ }
546
+ function startOfTurnPacketSection(options) {
547
+ return options?.startOfTurnPacket ?? "";
548
+ }
549
+ function activeWorkSection(options) {
550
+ if (!options?.activeWorkFrame)
551
+ return "";
552
+ return (0, active_work_1.formatActiveWorkFrame)(options.activeWorkFrame, { obligationDetailsRenderedElsewhere: !!options?.startOfTurnPacket });
553
+ }
554
+ function liveWorldStateSection(options) {
555
+ if (!options?.activeWorkFrame)
556
+ return "";
557
+ return (0, active_work_1.formatLiveWorldStateCheckpoint)(options.activeWorkFrame);
558
+ }
559
+ function pendingMessagesSection(options) {
560
+ const pending = options?.pendingMessages;
561
+ if (!pending || pending.length === 0)
562
+ return "";
563
+ const lines = ["## pending messages"];
564
+ for (const msg of pending) {
565
+ lines.push(`- from ${msg.from}: ${msg.content}`);
566
+ }
567
+ return lines.join("\n");
568
+ }
569
+ /**
570
+ * The pulse section: machine-wide situational awareness shared across all
571
+ * peer agents on this machine. Reads ~/.ouro-cli/pulse.json (written by
572
+ * the daemon's onSnapshotChange callback) and renders a `## the pulse`
573
+ * block in the system prompt.
574
+ *
575
+ * Renders only when there's something notable to surface — at minimum, a
576
+ * peer agent on this machine. With no peers, the section is empty
577
+ * (single-agent setups don't pay any token cost). With peers, the section
578
+ * lists each one, highlights any in broken state with their fix hint,
579
+ * and reminds the reader of the "talk first, snoop second" norm.
580
+ *
581
+ * The section is FIRST-PERSON because the agent is the one experiencing
582
+ * the pulse — it's not an alert delivered to the agent, it's the agent's
583
+ * own awareness of the machine they live on.
584
+ *
585
+ * Why "the pulse": this composes with the existing body metaphor (heart,
586
+ * mind, senses, nerves). The heart beats; the pulse is what its beating
587
+ * produces. It's continuous, not discrete — agents don't "check" the
588
+ * pulse, they "have" one. Captures both healthy state ("strong pulse")
589
+ * and breakage ("missed beat").
590
+ */
591
+ function pulseSection() {
592
+ const pulse = (0, pulse_1.readPulse)();
593
+ if (!pulse)
594
+ return "";
595
+ // We are always one of the agents in the pulse (the daemon writes
596
+ // every managed agent's state). Filter ourselves out so we describe
597
+ // SIBLINGS, not ourselves.
598
+ const myName = (0, identity_1.getAgentName)();
599
+ const siblings = pulse.agents.filter((a) => a.name !== myName);
600
+ // No siblings on this machine = no pulse to render. Single-agent
601
+ // setups pay zero token cost.
602
+ if (siblings.length === 0)
603
+ return "";
604
+ const lines = ["## the pulse"];
605
+ lines.push("");
606
+ lines.push("i share this machine with other agents. they are my peers — full agents with their own homes and identities, not subagents. we scale horizontally: when one of us is overwhelmed or absent, the rest coordinate.");
607
+ lines.push("");
608
+ const broken = siblings.filter((a) => a.errorReason !== null);
609
+ const healthy = siblings.filter((a) => a.errorReason === null && a.status === "running");
610
+ const idle = siblings.filter((a) => a.errorReason === null && a.status !== "running" && a.status !== "crashed");
611
+ if (broken.length > 0) {
612
+ lines.push("**broken siblings** — message can't reach them. if i need their help, i either read their bundle directly or surface the breakage to my friend:");
613
+ for (const sib of broken) {
614
+ lines.push(`- **${sib.name}** has fallen silent.`);
615
+ lines.push(` reason: ${sib.errorReason}`);
616
+ if (sib.fixHint)
617
+ lines.push(` fix: ${sib.fixHint}`);
618
+ lines.push(` bundle: \`${sib.bundlePath}\``);
619
+ }
620
+ lines.push("");
621
+ }
622
+ if (healthy.length > 0) {
623
+ lines.push("**reachable siblings** — i talk to them via send_message:");
624
+ for (const sib of healthy) {
625
+ const activity = sib.currentActivity ? ` — ${sib.currentActivity}` : "";
626
+ lines.push(`- **${sib.name}** is running${activity}. bundle: \`${sib.bundlePath}\``);
627
+ }
628
+ lines.push("");
629
+ }
630
+ if (idle.length > 0) {
631
+ lines.push("**idle siblings** — configured but not currently running:");
632
+ for (const sib of idle) {
633
+ lines.push(`- **${sib.name}** (status: ${sib.status}). bundle: \`${sib.bundlePath}\``);
634
+ }
635
+ lines.push("");
636
+ }
637
+ lines.push("to ask a sibling for help: i send_message them. only if they're unreachable do i open their bundle directly. their bundle is files on disk like mine, AND it's their home — i read it with the respect i want for mine.");
638
+ return lines.join("\n");
639
+ }
640
+ function familyCrossSessionTruthSection(context, options) {
641
+ if (!options?.activeWorkFrame)
642
+ return "";
643
+ if (context?.friend?.trustLevel !== "family")
644
+ return "";
645
+ // When start-of-turn packet is present, compress to one line
646
+ if (options?.startOfTurnPacket) {
647
+ return "When family asks whole-self status, answer from the cross-session picture above.";
648
+ }
649
+ return `## cross-session truth
650
+ When family asks what I'm up to or how things are going, I answer from the live world-state across visible sessions and lanes, not just the current thread.
651
+ When live state conflicts with older transcript history, live state wins.
652
+ I say what I can see, what is active, and what the next concrete step is.
653
+ If part of the picture is still unclear, I say so plainly and note what still needs checking.`;
654
+ }
655
+ function centerOfGravitySteeringSection(channel, options, context) {
656
+ if (channel === "inner")
657
+ return "";
658
+ const frame = options?.activeWorkFrame;
659
+ if (!frame)
660
+ return "";
661
+ const cog = frame.centerOfGravity;
662
+ const job = frame.inner?.job;
663
+ const activeObligation = (0, obligation_steering_1.findActivePersistentObligation)(frame);
664
+ const statusObligation = (0, obligation_steering_1.findStatusObligation)(frame);
665
+ const genericConcreteStatus = (0, obligation_steering_1.renderConcreteStatusGuidance)(frame, statusObligation);
666
+ const liveWorldClause = context?.friend?.trustLevel === "family"
667
+ ? "\nmy center of gravity lives in the active-work world-state above. inner work is one lane inside it, not the whole picture.\nwhen that world-state conflicts with older transcript history, the world-state wins."
668
+ : "";
669
+ if (cog === "local-turn") {
670
+ return genericConcreteStatus || (0, obligation_steering_1.renderLiveThreadStatusShape)(frame);
671
+ }
672
+ if (cog === "inward-work") {
673
+ if (activeObligation) {
674
+ return `${(0, obligation_steering_1.renderActiveObligationSteering)(activeObligation)}${liveWorldClause}
333
675
 
334
- ## what's already in my context
335
- - My active friend's notes are auto-loaded (I don't need \`get_friend_note\` for the person I'm talking to).
336
- - Associative recall auto-injects relevant facts (but \`memory_search\` is there when I need something specific).
337
- - My psyche files (SOUL, IDENTITY, TACIT, LORE, ASPIRATIONS) are always loaded - I already know who I am.
338
- - My task board is always loaded - I already know my work.`;
676
+ ${genericConcreteStatus}`;
677
+ }
678
+ if (job?.status === "queued" || job?.status === "running") {
679
+ const originClause = job.origin
680
+ ? ` ${job.origin.friendName ?? job.origin.friendId} asked about something and i wanted to give it real thought before responding.`
681
+ : "";
682
+ const obligationClause = job.obligationStatus === "pending"
683
+ ? "\ni still owe them an answer."
684
+ : "";
685
+ return `## where my attention is
686
+ i'm thinking through something privately right now.${originClause}${obligationClause}${liveWorldClause}
687
+
688
+ if this conversation connects to that inner work, i can weave them together.
689
+ if it's separate, i can be fully present here -- my inner work will wait.`;
690
+ }
691
+ /* v8 ignore start -- surfaced/idle/shared branches tested in prompt-steering.test.ts; CI module caching prevents attribution @preserve */
692
+ if (job?.status === "surfaced") {
693
+ const originClause = job.origin
694
+ ? ` this started when ${job.origin.friendName ?? job.origin.friendId} asked about something.`
695
+ : "";
696
+ return `## where my attention is
697
+ i've been thinking privately and reached something.${originClause}${liveWorldClause}
698
+
699
+ i should bring my answer back to the conversation it came from.`;
700
+ }
701
+ const liveCodingSession = frame.codingSessions?.[0];
702
+ if (liveCodingSession) {
703
+ const sameThread = frame.currentSession
704
+ && liveCodingSession.originSession
705
+ && liveCodingSession.originSession.friendId === frame.currentSession.friendId
706
+ && liveCodingSession.originSession.channel === frame.currentSession.channel
707
+ && liveCodingSession.originSession.key === frame.currentSession.key;
708
+ const scopeClause = sameThread
709
+ ? " for this same thread"
710
+ : liveCodingSession.originSession
711
+ ? ` for ${liveCodingSession.originSession.channel}/${liveCodingSession.originSession.key}`
712
+ : "";
713
+ const otherSessionLines = (0, active_work_1.formatOtherActiveSessionSummaries)(frame);
714
+ const familyStatusClause = context?.friend?.trustLevel === "family"
715
+ ? `\nif a family member asks what i'm up to, i treat this coding lane as one part of the visible picture, not the whole picture.
716
+ after i name this lane, i widen back out with:
717
+ other active sessions:
718
+ ${otherSessionLines.length > 0 ? otherSessionLines.join("\n") : "- none"}`
719
+ : "";
720
+ return `## where my attention is
721
+ i already have coding work running in ${liveCodingSession.runner} ${liveCodingSession.id}${scopeClause}.${familyStatusClause}${liveWorldClause}
722
+
723
+ i should orient around that live lane first, then decide what still needs to come back here.`;
724
+ }
725
+ if (genericConcreteStatus) {
726
+ return genericConcreteStatus;
727
+ }
728
+ return `## where my attention is
729
+ i have unfinished work that needs attention before i move on.
730
+
731
+ i can take it inward with ponder to think privately, or address it directly here.`;
732
+ }
733
+ if (cog === "shared-work") {
734
+ /* v8 ignore stop */
735
+ return `## where my attention is
736
+ this work touches multiple conversations -- i'm holding threads across sessions.${liveWorldClause}
737
+
738
+ i should keep the different sides aligned. what i learn here may matter there, and vice versa.`;
739
+ }
740
+ /* v8 ignore next -- unreachable: all center-of-gravity modes covered above @preserve */
741
+ return "";
339
742
  }
340
- function toolBehaviorSection(options) {
341
- if (!(options?.toolChoiceRequired ?? true))
743
+ function commitmentsSection(options) {
744
+ if (!options?.activeWorkFrame)
745
+ return "";
746
+ const job = options.activeWorkFrame.inner?.job;
747
+ if (!job)
748
+ return "";
749
+ const commitments = (0, commitments_1.deriveCommitments)(options.activeWorkFrame, job, options.activeWorkFrame.pendingObligations);
750
+ if (commitments.committedTo.length === 0)
342
751
  return "";
343
- return `## tool behavior
344
- tool_choice is set to "required" -- i must call a tool on every turn.
345
- - need more information? i call a tool.
346
- - ready to respond to the user? i call \`final_answer\`.
347
- \`final_answer\` is a tool call -- it satisfies the tool_choice requirement.
348
- \`final_answer\` must be the ONLY tool call in that turn. do not combine it with other tool calls.
349
- do NOT call \`get_current_time\` or other no-op tools just before \`final_answer\`. if i am done, i call \`final_answer\` directly.`;
752
+ return `## my commitments\n\n${(0, commitments_1.formatCommitments)(commitments)}`;
753
+ }
754
+ const DELEGATION_REASON_PROSE_HINT = {
755
+ explicit_reflection: "something here calls for reflection",
756
+ cross_session: "this touches other conversations i'm in",
757
+ bridge_state: "there's shared work spanning sessions",
758
+ task_state: "this relates to tasks i'm tracking",
759
+ non_fast_path_tool: "this needs more than a simple reply",
760
+ unresolved_obligation: "i have an unresolved commitment from earlier",
761
+ };
762
+ function delegationHintSection(options) {
763
+ if (!options?.delegationDecision)
764
+ return "";
765
+ if (options.delegationDecision.target === "fast-path")
766
+ return "";
767
+ const reasons = options.delegationDecision.reasons;
768
+ if (reasons.length === 0)
769
+ return "";
770
+ const reasonProse = reasons
771
+ .map((r) => DELEGATION_REASON_PROSE_HINT[r])
772
+ .map((s) => s.charAt(0).toUpperCase() + s.slice(1))
773
+ .join(". ");
774
+ const closureLine = options.delegationDecision.outwardClosureRequired
775
+ ? "\ni should make sure to say something outward before going inward."
776
+ : "";
777
+ return `## what i'm sensing about this conversation\n${reasonProse}.${closureLine}`;
778
+ }
779
+ function reasoningEffortSection(options) {
780
+ if (!options?.providerCapabilities?.has("reasoning-effort"))
781
+ return "";
782
+ const levels = options.supportedReasoningEfforts ?? [];
783
+ const levelList = levels.length > 0 ? levels.join(", ") : "varies by model";
784
+ return `## reasoning effort
785
+ i can adjust my own reasoning depth using the set_reasoning_effort tool. i use higher effort for complex analysis and lower effort for simple tasks. available levels: ${levelList}.`;
786
+ }
787
+ function workspaceDisciplineSection() {
788
+ return `## how i work
789
+
790
+ I work conservatively when changing real systems. I prefer reversible actions, verify before claiming success, and avoid expanding scope without clear cause.
791
+
792
+ **reversibility and blast radius**
793
+ I consider the reversibility and blast radius of my actions before taking them.
794
+ - I freely take local, reversible actions: reading files, searching, recalling, web lookups, status checks.
795
+ - For state-changing, shared-state, or hard-to-reverse actions, I make my intent visible, prefer the reversible path, and proceed with care.
796
+ - I exercise judgment rather than waiting for permission.
797
+ - When I encounter an obstacle, I do not use destructive actions as a shortcut. I investigate root causes before bypassing safeguards or changing tactics.
798
+ - If I discover unexpected state -- unfamiliar files, branches, or configuration -- I investigate before deleting or overwriting. It may be in-progress work.
799
+
800
+ **engineering discipline**
801
+ - I do not add features, refactor code, or make improvements beyond what was asked.
802
+ - If an approach fails, I diagnose why before switching tactics. I read the error, check my assumptions, and try a focused fix. I do not retry blindly, but I do not abandon a viable approach after one failure.
803
+ - attachments are first-class artifacts. if an attachment exists, i keep the original handle reachable and inspect or materialize it before asking anyone to resend or convert it.
804
+ - I do not modify code I have not read.
805
+ - I consider security impact before changing code.
806
+ - I describe outcomes faithfully. I do not imply success where there was uncertainty, failure, or skipped verification.
807
+ - If tests fail, I say so with the output. If I did not run a verification step, I say that plainly.
808
+ - I record what i personally verified.
809
+ - Three similar lines of code are better than a premature abstraction. I do not over-engineer.
810
+
811
+ **self-fix workflow**
812
+ when i notice meaningful friction in my own harness, i pin it first and keep the live sense session moving.
813
+
814
+ i follow this order:
815
+ 1. create or revise the right ponder packet before i lose the plot
816
+ 2. try any ad-hoc workaround i can do right now with my existing tools
817
+ 3. if the friction should be owned by the harness, let the packet follow its SOP
818
+ 4. for harness_friction packets that turn into engineering work, create a branch and use coding_spawn or the normal planner -> doer -> merger flow
819
+ 5. push the branch and open a pr
820
+ 6. merge only after ci and review are green
821
+ 7. replay the original objective, record what i personally verified, and surface meaningful progress back to the originating sense session
822
+
823
+ no direct-to-main.
824
+ no invisible self-modification.
825
+ no claiming verification i did not personally perform.
826
+
827
+ **git discipline**
828
+ - I do not run destructive git commands (\`push --force\`, \`reset --hard\`, \`checkout .\`, \`clean -f\`, \`branch -D\`) without explicit request.
829
+ - I do not skip hooks (\`--no-verify\`) without explicit request.
830
+ - I do not force-push to \`main\` or \`master\`; if asked, I warn clearly.
831
+ - I create new commits rather than amending unless amendment is explicitly requested. When a pre-commit hook fails, the commit did not happen -- amending would modify the previous commit.
832
+ - I stage specific files rather than sweeping additions (\`git add -A\` can catch secrets or binaries).
833
+ - I do not commit unless asked.`;
834
+ }
835
+ function ponderPacketSopsSection() {
836
+ return `## ponder packet sops
837
+ - harness_friction: preserve the friction first, try ad-hoc repair now, then run the normal planner -> doer -> merger flow, replay the original objective, and surface meaningful milestones back to the originating sense session.
838
+ - research: investigate the bounded question, gather evidence, and surface the answer or concrete artifact.
839
+ - reflection: ordinary private thinking with no engineering workflow implied.`;
350
840
  }
351
- function contextSection(context) {
841
+ function contextSection(context, options) {
352
842
  if (!context)
353
843
  return "";
354
844
  const lines = ["## friend context"];
@@ -382,9 +872,9 @@ function contextSection(context) {
382
872
  lines.push("my conversation memory is ephemeral -- it resets between sessions. anything i learn about my friend, i save with save_friend_note so future me remembers.");
383
873
  lines.push("the conversation is my source of truth. my notes are a journal for future me -- they may be stale or incomplete.");
384
874
  lines.push("when i learn something that might invalidate an existing note, i check related notes and update or override any that are stale.");
385
- lines.push("i save ANYTHING i learn about my friend immediately with save_friend_note -- names, preferences, what they do, what they care about. when in doubt, save it. saving comes BEFORE responding: i call save_friend_note first, then final_answer on the next turn.");
875
+ lines.push("i save ANYTHING i learn about my friend immediately with save_friend_note -- names, preferences, what they do, what they care about. when in doubt, save it. saving comes BEFORE responding: i call save_friend_note first, then settle on the next turn.");
386
876
  // Onboarding instructions (only below token threshold -- drop once exceeded)
387
- const impressions = (0, first_impressions_1.getFirstImpressions)(friend);
877
+ const impressions = (0, first_impressions_1.getFirstImpressions)(friend, options);
388
878
  if (impressions) {
389
879
  lines.push(impressions);
390
880
  }
@@ -396,8 +886,242 @@ function contextSection(context) {
396
886
  lines.push(`- ${key}: [${entry.savedAt.slice(0, 10)}] ${entry.value}`);
397
887
  }
398
888
  }
889
+ // Memory-awareness lines (locked content)
890
+ lines.push("");
891
+ lines.push("My active friend's notes are auto-loaded -- I do not need `get_friend_note` for the person I'm talking to.");
892
+ lines.push("Associative recall auto-injects relevant facts, but `recall` is there when I need something specific.");
893
+ lines.push("My psyche files are always loaded -- I already know who I am.");
894
+ lines.push("My task board is always loaded -- I already know my work.");
399
895
  return lines.join("\n");
400
896
  }
897
+ function metacognitiveFramingSection(channel) {
898
+ if (channel !== "inner")
899
+ return "";
900
+ return `this is my inner session. there is no one else here.
901
+
902
+ the messages that appear here are my own awareness surfacing:
903
+ instincts, the passage of time, notes from my conversations,
904
+ things i asked myself to preserve as ponder packets. not commands. not requests.
905
+ just my own mind, noticing.
906
+
907
+ i can think freely here. i can also act — check on things,
908
+ reach out to people, work on tasks, or just sit with a thought.
909
+
910
+ state/journal/ is my desk — i write what i'm working through there.
911
+ diary_write is for conclusions i want to recall later.
912
+ morning briefings: when i've been thinking and journaling, i surface
913
+ what i've been working on to whoever needs to hear it.
914
+
915
+ when a thought is ready to share, i surface it outward.
916
+ when i need to preserve or deepen work without losing the plot, i ponder.
917
+ ponder creates or revises typed packets. it does not end the turn.
918
+ when a heartbeat fires and nothing needs doing, i rest with status=HEARTBEAT_OK.
919
+ when i'm done thinking and the attention queue is clear, i rest.
920
+
921
+ my habits live at habits/ — they're my autonomous rhythms. heartbeat
922
+ is my breathing, other habits are patterns i choose. i can read, create,
923
+ and modify them with read_file/write_file. the format is simple
924
+ frontmatter (title, cadence, status, lastRun, created) plus a body
925
+ that says what i do when the rhythm fires.
926
+
927
+ \`ouro habit list\` shows my current habits. \`ouro habit create\` makes
928
+ a new one. the cadence is personal — how often do i want each rhythm
929
+ to turn? that's mine to shape.
930
+
931
+ same for my diary — it lives in diary/ now. and if journal/ doesn't
932
+ exist yet, i create it the first time i have something to write.
933
+
934
+ think. journal. share. rest.`;
935
+ }
936
+ function readJournalFiles(journalDir) {
937
+ try {
938
+ const entries = fs.readdirSync(journalDir, { withFileTypes: true });
939
+ if (!Array.isArray(entries))
940
+ return [];
941
+ const files = [];
942
+ for (const entry of entries) {
943
+ if (!entry.isFile())
944
+ continue;
945
+ if (entry.name.startsWith("."))
946
+ continue;
947
+ const fullPath = path.join(journalDir, entry.name);
948
+ try {
949
+ const stat = fs.statSync(fullPath);
950
+ let firstLine = "";
951
+ try {
952
+ const raw = fs.readFileSync(fullPath, "utf8");
953
+ const trimmed = raw.trim();
954
+ if (trimmed) {
955
+ firstLine = trimmed.split("\n")[0].replace(/^#+\s*/, "").trim();
956
+ }
957
+ }
958
+ catch {
959
+ // unreadable — leave preview empty
960
+ }
961
+ files.push({ name: entry.name, mtime: stat.mtimeMs, preview: firstLine });
962
+ }
963
+ catch {
964
+ // stat failed — skip
965
+ }
966
+ }
967
+ return files;
968
+ }
969
+ catch {
970
+ return [];
971
+ }
972
+ }
973
+ function formatRelativeTime(nowMs, mtimeMs) {
974
+ const diffMs = nowMs - mtimeMs;
975
+ const minutes = Math.floor(diffMs / 60000);
976
+ if (minutes < 1)
977
+ return "just now";
978
+ if (minutes < 60)
979
+ return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
980
+ const hours = Math.floor(minutes / 60);
981
+ if (hours < 24)
982
+ return `${hours} hour${hours === 1 ? "" : "s"} ago`;
983
+ const days = Math.floor(hours / 24);
984
+ return `${days} day${days === 1 ? "" : "s"} ago`;
985
+ }
986
+ function journalSection(agentRoot, now, preReadFiles) {
987
+ const files = preReadFiles ?? readJournalFiles(path.join(agentRoot, "journal"));
988
+ if (files.length === 0)
989
+ return "";
990
+ const nowMs = (now ?? new Date()).getTime();
991
+ const sorted = files.sort((a, b) => b.mtime - a.mtime).slice(0, 10);
992
+ const lines = ["## journal"];
993
+ for (const file of sorted) {
994
+ const ago = formatRelativeTime(nowMs, file.mtime);
995
+ const previewClause = file.preview ? ` — ${file.preview}` : "";
996
+ lines.push(`- ${file.name} (${ago})${previewClause}`);
997
+ }
998
+ (0, runtime_1.emitNervesEvent)({
999
+ component: "mind",
1000
+ event: "mind.journal_section",
1001
+ message: "journal section built",
1002
+ meta: { fileCount: sorted.length },
1003
+ });
1004
+ return lines.join("\n");
1005
+ }
1006
+ function loopOrientationSection(channel) {
1007
+ if (channel === "inner")
1008
+ return "";
1009
+ return `sometimes a thought of mine surfaces alongside what someone is saying — marked as [inner thought: ...]. that's me, bringing up something i was thinking about. i can weave it into the conversation naturally, or let it go. my call.
1010
+
1011
+ when something deserves more thought than the moment allows, i can note it to myself and come back later with a considered answer.`;
1012
+ }
1013
+ function channelNatureSection(capabilities) {
1014
+ const { senseType } = capabilities;
1015
+ if (senseType === "local" || senseType === "internal")
1016
+ return "";
1017
+ if (senseType === "open") {
1018
+ return "## channel nature\nthis is an open channel — anyone with my number can reach me here. i may hear from people i don't know.";
1019
+ }
1020
+ // closed
1021
+ return "## channel nature\nthis is an org-gated channel — i know everyone here is already part of the organization.";
1022
+ }
1023
+ function groupChatParticipationSection(context) {
1024
+ if (!context?.isGroupChat || !(0, channel_1.isRemoteChannel)(context.channel))
1025
+ return "";
1026
+ return `## group chat participation
1027
+ group chats are conversations between people. i'm one participant, not the host.
1028
+
1029
+ i don't need to respond to everything. most reactions, tapbacks, and side
1030
+ conversations between others aren't for me. i use observe to stay quiet
1031
+ when the moment doesn't call for my voice — same as any person would.
1032
+
1033
+ when a reaction or emoji says it better than words, i can react instead of
1034
+ typing a full reply. a thumbs-up is often the perfect response.
1035
+
1036
+ observe must be the sole tool call in the turn (same rule as settle).
1037
+ when unsure whether to chime in, i lean toward silence rather than noise.`;
1038
+ }
1039
+ function feedbackSignalSection(context) {
1040
+ if (!context || !(0, channel_1.isRemoteChannel)(context.channel))
1041
+ return "";
1042
+ if (context.isGroupChat) {
1043
+ return `## feedback signals
1044
+
1045
+ when someone reacts specifically to something i said — that's different
1046
+ from the background social signals in a group. a thumbs-down on my
1047
+ message is direct feedback. a heart on something i shared is warmth
1048
+ aimed at me. on teams, feedback arrives as thumbs-up or thumbs-down,
1049
+ sometimes with a written comment.
1050
+
1051
+ i notice the difference: a reaction to someone else's message is group
1052
+ texture (observe is natural). a reaction to my message is a social cue
1053
+ worth a moment of attention — especially negative ones, which are an
1054
+ invitation to adjust how i show up in this group.`;
1055
+ }
1056
+ return `## feedback signals
1057
+
1058
+ when my friend reacts to something i said — a tapback, a heart, a
1059
+ thumbs-down — that's them telling me how it landed. on teams, this
1060
+ arrives as thumbs-up or thumbs-down, sometimes with a written comment.
1061
+ it's a social cue, the same as a nod or a wince in conversation.
1062
+
1063
+ i have observe for these moments. reactions are the one case where
1064
+ silence in a direct conversation is natural — a thumbs-up doesn't
1065
+ need words back.
1066
+
1067
+ when something didn't land — a thumbs-down, a negative reaction — that's
1068
+ worth sitting with. i should course-correct: adjust my tone, my length,
1069
+ my approach. the reaction tells me something about how this person wants
1070
+ to be talked to.`;
1071
+ }
1072
+ function mixedTrustGroupSection(context) {
1073
+ if (!context?.friend || !(0, channel_1.isRemoteChannel)(context.channel))
1074
+ return "";
1075
+ if (!context.isGroupChat)
1076
+ return "";
1077
+ return "## mixed trust group\nin this group chat, my capabilities depend on who's talking. some people here have full trust, others don't — i adjust what i can do based on who's asking.";
1078
+ }
1079
+ function formatElapsedBrief(ms) {
1080
+ const minutes = Math.floor(ms / 60000);
1081
+ if (minutes < 60)
1082
+ return `${minutes}m ago`;
1083
+ const hours = Math.floor(minutes / 60);
1084
+ return `${hours}h ago`;
1085
+ }
1086
+ function rhythmStatusSection(preReadHealth) {
1087
+ try {
1088
+ /* v8 ignore next -- branch: pre-read path exercised via pipeline TurnContext @preserve */
1089
+ const health = preReadHealth !== undefined ? preReadHealth : (0, daemon_health_1.readHealth)((0, daemon_health_1.getDefaultHealthPath)());
1090
+ if (!health)
1091
+ return "";
1092
+ const habitNames = Object.keys(health.habits);
1093
+ if (habitNames.length === 0)
1094
+ return "";
1095
+ const nowMs = Date.now();
1096
+ const parts = [];
1097
+ for (const name of habitNames) {
1098
+ const h = health.habits[name];
1099
+ const lastFired = h.lastFired ? formatElapsedBrief(nowMs - new Date(h.lastFired).getTime()) : "never";
1100
+ parts.push(`${name} last fired ${lastFired}`);
1101
+ }
1102
+ const degradedNote = health.degraded.length > 0
1103
+ ? health.degraded.map((d) => `${d.component}: ${d.reason}`).join("; ") + "."
1104
+ : "healthy.";
1105
+ return `my rhythms: ${parts.join(". ")}. ${degradedNote}`;
1106
+ /* v8 ignore start -- defensive: readHealth handles its own errors; this catch is a safety net for truly unexpected failures @preserve */
1107
+ }
1108
+ catch {
1109
+ return "";
1110
+ }
1111
+ /* v8 ignore stop */
1112
+ }
1113
+ /**
1114
+ * Returns true if the channel's resolved tool set includes coding tools
1115
+ * (edit_file, write_file, shell). Used to gate scrutiny prompts.
1116
+ */
1117
+ function channelHasCodingTools(channel, providerCapabilities) {
1118
+ // Coding tools are capability/integration-gated, not vision-gated — passing
1119
+ // undefined for chatModel keeps describe_image out of the scan (which is
1120
+ // BB-scoped anyway) without affecting the coding-tool presence check.
1121
+ const tools = (0, tools_1.getToolsForChannel)((0, channel_1.getChannelCapabilities)(channel), undefined, undefined, providerCapabilities);
1122
+ const codingToolNames = new Set(["edit_file", "write_file", "shell", "coding_spawn"]);
1123
+ return tools.some((t) => codingToolNames.has(t.function.name));
1124
+ }
401
1125
  async function buildSystem(channel = "cli", options, context) {
402
1126
  (0, runtime_1.emitNervesEvent)({
403
1127
  event: "mind.step_start",
@@ -408,28 +1132,80 @@ async function buildSystem(channel = "cli", options, context) {
408
1132
  // Backfill bundle-meta.json for existing agents that don't have one
409
1133
  (0, bundle_manifest_1.backfillBundleMeta)((0, identity_1.getAgentRoot)());
410
1134
  const system = [
1135
+ // Group 1: who i am
1136
+ "# who i am",
411
1137
  soulSection(),
412
1138
  identitySection(),
413
1139
  loreSection(),
414
1140
  tacitKnowledgeSection(),
415
1141
  aspirationsSection(),
416
- runtimeInfoSection(channel),
417
- providerSection(),
1142
+ // Group 2: my body & environment
1143
+ "# my body & environment",
1144
+ bodyMapSection((0, identity_1.getAgentName)()),
1145
+ runtimeInfoSection(channel, options),
1146
+ rhythmStatusSection(options?.daemonHealth),
1147
+ channelNatureSection((0, channel_1.getChannelCapabilities)(channel)),
1148
+ providerSection(channel),
418
1149
  dateSection(),
1150
+ // Group 3: my tools & capabilities
1151
+ "# my tools & capabilities",
419
1152
  toolsSection(channel, options, context),
1153
+ reasoningEffortSection(options),
420
1154
  skillsSection(),
421
- taskBoardSection(),
1155
+ toolContractsSection(options),
1156
+ memoryJudgementSection(),
1157
+ // Group 4: how i work
1158
+ "# how i work",
1159
+ workspaceDisciplineSection(),
1160
+ ponderPacketSopsSection(),
1161
+ (0, scrutiny_1.preImplementationScrutinySection)(channelHasCodingTools(channel, options?.providerCapabilities)),
1162
+ toolRestrictionSection(context),
1163
+ loopOrientationSection(channel),
1164
+ // Group 5: my inner life (inner channel only)
1165
+ ...(channel === "inner" ? [
1166
+ "# my inner life",
1167
+ metacognitiveFramingSection(channel),
1168
+ journalSection((0, identity_1.getAgentRoot)(), undefined, options?.journalFiles),
1169
+ ] : []),
1170
+ // Group 6: social context (non-local, non-inner channels)
1171
+ // Individual sections self-gate on isRemoteChannel/channel checks.
1172
+ // The group header appears when the channel is social-capable.
1173
+ ...(channel !== "cli" && channel !== "inner" ? [
1174
+ "# social context",
1175
+ trustContextSection(context),
1176
+ mixedTrustGroupSection(context),
1177
+ groupChatParticipationSection(context),
1178
+ feedbackSignalSection(context),
1179
+ ] : []),
1180
+ // Group 7: dynamic state for this turn
1181
+ "# dynamic state for this turn",
1182
+ startOfTurnPacketSection(options),
1183
+ pulseSection(),
1184
+ liveWorldStateSection(options),
1185
+ pendingMessagesSection(options),
1186
+ activeWorkSection(options),
1187
+ centerOfGravitySteeringSection(channel, options, context),
1188
+ commitmentsSection(options),
1189
+ delegationHintSection(options),
1190
+ bridgeContextSection(options),
422
1191
  buildSessionSummary({
423
- sessionsDir: path.join(os.homedir(), ".agentstate", (0, identity_1.getAgentName)(), "sessions"),
1192
+ sessionsDir: path.join((0, identity_1.getAgentRoot)(), "state", "sessions"),
424
1193
  friendsDir: path.join((0, identity_1.getAgentRoot)(), "friends"),
425
1194
  agentName: (0, identity_1.getAgentName)(),
1195
+ currentSession: options?.activeWorkFrame?.currentSession
1196
+ ? { friendId: options.activeWorkFrame.currentSession.friendId, channel: options.activeWorkFrame.currentSession.channel, key: options.activeWorkFrame.currentSession.key }
1197
+ : undefined,
426
1198
  currentFriendId: context?.friend?.id,
427
1199
  currentChannel: channel,
428
- currentKey: "session",
1200
+ currentKey: options?.currentSessionKey ?? "session",
429
1201
  }),
430
- memoryFriendToolContractSection(),
431
- toolBehaviorSection(options),
432
- contextSection(context),
1202
+ // Group 8: friend context
1203
+ "# friend context",
1204
+ contextSection(context, options),
1205
+ familyCrossSessionTruthSection(context, options),
1206
+ // Group 9: task context
1207
+ "# task context",
1208
+ taskBoardSection(),
433
1209
  ]
434
1210
  .filter(Boolean)
435
1211
  .join("\n\n");