@ouro.bot/cli 0.1.0-alpha.3 → 0.1.0-alpha.300

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