@ouro.bot/cli 0.1.0-alpha.2 → 0.1.0-alpha.200

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 (215) hide show
  1. package/README.md +187 -191
  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/assets/ouroboros.png +0 -0
  6. package/changelog.json +1248 -0
  7. package/dist/heart/active-work.js +832 -0
  8. package/dist/heart/bridges/manager.js +358 -0
  9. package/dist/heart/bridges/state-machine.js +135 -0
  10. package/dist/heart/bridges/store.js +123 -0
  11. package/dist/heart/cares.js +179 -0
  12. package/dist/heart/commitments.js +111 -0
  13. package/dist/heart/config.js +114 -28
  14. package/dist/heart/core.js +689 -120
  15. package/dist/heart/cross-chat-delivery.js +146 -0
  16. package/dist/heart/daemon/agent-config-check.js +149 -0
  17. package/dist/heart/daemon/agent-discovery.js +81 -0
  18. package/dist/heart/daemon/agent-service.js +360 -0
  19. package/dist/heart/daemon/auth-flow.js +477 -0
  20. package/dist/heart/daemon/cadence.js +70 -0
  21. package/dist/heart/daemon/daemon-cli.js +2897 -193
  22. package/dist/heart/daemon/daemon-entry.js +194 -8
  23. package/dist/heart/daemon/daemon-health.js +136 -0
  24. package/dist/heart/daemon/daemon-runtime-sync.js +231 -0
  25. package/dist/heart/daemon/daemon-tombstone.js +123 -0
  26. package/dist/heart/daemon/daemon.js +488 -13
  27. package/dist/heart/daemon/habit-migration.js +181 -0
  28. package/dist/heart/daemon/habit-parser.js +119 -0
  29. package/dist/heart/daemon/habit-scheduler.js +369 -0
  30. package/dist/heart/daemon/hatch-animation.js +35 -0
  31. package/dist/heart/daemon/hatch-flow.js +32 -122
  32. package/dist/heart/daemon/hatch-specialist.js +7 -2
  33. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  34. package/dist/heart/daemon/hooks/bundle-meta.js +206 -0
  35. package/dist/heart/daemon/inner-status.js +89 -0
  36. package/dist/heart/daemon/launchd.js +165 -0
  37. package/dist/heart/daemon/log-tailer.js +4 -3
  38. package/dist/heart/daemon/mcp-server.js +591 -0
  39. package/dist/heart/daemon/message-router.js +17 -8
  40. package/dist/heart/daemon/os-cron-deps.js +134 -0
  41. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  42. package/dist/heart/daemon/ouro-bot-wrapper.js +4 -3
  43. package/dist/heart/daemon/ouro-path-installer.js +221 -0
  44. package/dist/heart/daemon/ouro-uti.js +11 -2
  45. package/dist/heart/daemon/ouro-version-manager.js +171 -0
  46. package/dist/heart/daemon/outlook-http.js +439 -0
  47. package/dist/heart/daemon/outlook-read.js +1618 -0
  48. package/dist/heart/daemon/outlook-render.js +1032 -0
  49. package/dist/heart/daemon/outlook-types.js +7 -0
  50. package/dist/heart/daemon/outlook-view.js +194 -0
  51. package/dist/heart/daemon/process-manager.js +94 -1
  52. package/dist/heart/daemon/run-hooks.js +39 -0
  53. package/dist/heart/daemon/runtime-logging.js +61 -14
  54. package/dist/heart/daemon/runtime-metadata.js +219 -0
  55. package/dist/heart/daemon/runtime-mode.js +67 -0
  56. package/dist/heart/daemon/safe-mode.js +161 -0
  57. package/dist/heart/daemon/sense-manager.js +314 -0
  58. package/dist/heart/daemon/session-id-resolver.js +131 -0
  59. package/dist/heart/daemon/skill-management-installer.js +94 -0
  60. package/dist/heart/daemon/socket-client.js +202 -0
  61. package/dist/heart/daemon/specialist-orchestrator.js +129 -0
  62. package/dist/heart/daemon/specialist-prompt.js +101 -0
  63. package/dist/heart/daemon/specialist-tools.js +283 -0
  64. package/dist/heart/daemon/staged-restart.js +138 -0
  65. package/dist/heart/daemon/task-scheduler.js +3 -25
  66. package/dist/heart/daemon/thoughts.js +507 -0
  67. package/dist/heart/daemon/update-checker.js +111 -0
  68. package/dist/heart/daemon/update-hooks.js +138 -0
  69. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  70. package/dist/heart/delegation.js +62 -0
  71. package/dist/heart/identity.js +220 -52
  72. package/dist/heart/intentions.js +173 -0
  73. package/dist/heart/kicks.js +2 -20
  74. package/dist/heart/migrate-config.js +127 -0
  75. package/dist/heart/model-capabilities.js +48 -0
  76. package/dist/heart/obligations.js +225 -0
  77. package/dist/heart/presence.js +185 -0
  78. package/dist/heart/progress-story.js +42 -0
  79. package/dist/heart/provider-failover.js +88 -0
  80. package/dist/heart/provider-ping.js +178 -0
  81. package/dist/heart/providers/anthropic-token.js +163 -0
  82. package/dist/heart/providers/anthropic.js +199 -36
  83. package/dist/heart/providers/azure.js +116 -10
  84. package/dist/heart/providers/github-copilot.js +157 -0
  85. package/dist/heart/providers/minimax.js +33 -3
  86. package/dist/heart/providers/openai-codex.js +51 -16
  87. package/dist/heart/sense-truth.js +61 -0
  88. package/dist/heart/session-activity.js +172 -0
  89. package/dist/heart/session-recall.js +216 -0
  90. package/dist/heart/start-of-turn-packet.js +232 -0
  91. package/dist/heart/streaming.js +120 -33
  92. package/dist/heart/sync.js +217 -0
  93. package/dist/heart/target-resolution.js +127 -0
  94. package/dist/heart/tempo.js +93 -0
  95. package/dist/heart/temporal-view.js +41 -0
  96. package/dist/heart/tool-activity-callbacks.js +36 -0
  97. package/dist/heart/tool-description.js +135 -0
  98. package/dist/heart/tool-loop.js +200 -0
  99. package/dist/heart/turn-coordinator.js +28 -0
  100. package/dist/mind/associative-recall.js +122 -32
  101. package/dist/mind/bundle-manifest.js +77 -1
  102. package/dist/mind/context.js +125 -14
  103. package/dist/mind/{memory.js → diary.js} +69 -56
  104. package/dist/mind/episodes.js +119 -0
  105. package/dist/mind/file-state.js +179 -0
  106. package/dist/mind/first-impressions.js +16 -2
  107. package/dist/mind/friends/channel.js +64 -0
  108. package/dist/mind/friends/group-context.js +144 -0
  109. package/dist/mind/friends/store-file.js +36 -0
  110. package/dist/mind/friends/trust-explanation.js +74 -0
  111. package/dist/mind/friends/types.js +9 -1
  112. package/dist/mind/journal-index.js +161 -0
  113. package/dist/mind/obligation-steering.js +221 -0
  114. package/dist/mind/obligations.js +138 -0
  115. package/dist/mind/pending.js +76 -9
  116. package/dist/mind/phrases.js +1 -0
  117. package/dist/mind/prompt.js +861 -105
  118. package/dist/mind/scrutiny.js +173 -0
  119. package/dist/mind/token-estimate.js +8 -12
  120. package/dist/nerves/cli-logging.js +15 -2
  121. package/dist/nerves/coverage/audit.js +1 -1
  122. package/dist/nerves/coverage/run-artifacts.js +1 -1
  123. package/dist/nerves/event-buffer.js +111 -0
  124. package/dist/nerves/index.js +63 -3
  125. package/dist/nerves/observation.js +20 -0
  126. package/dist/nerves/runtime.js +5 -1
  127. package/dist/outlook-ui/assets/index-Ck8agNeO.js +61 -0
  128. package/dist/outlook-ui/assets/index-LwChZTgL.css +1 -0
  129. package/dist/outlook-ui/index.html +15 -0
  130. package/dist/repertoire/ado-client.js +4 -2
  131. package/dist/repertoire/ado-semantic.js +11 -5
  132. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  133. package/dist/repertoire/coding/context-pack.js +330 -0
  134. package/dist/repertoire/coding/feedback.js +301 -0
  135. package/dist/repertoire/coding/index.js +4 -1
  136. package/dist/repertoire/coding/manager.js +210 -4
  137. package/dist/repertoire/coding/spawner.js +58 -12
  138. package/dist/repertoire/coding/tools.js +209 -7
  139. package/dist/repertoire/data/ado-endpoints.json +188 -0
  140. package/dist/repertoire/guardrails.js +291 -0
  141. package/dist/repertoire/mcp-client.js +254 -0
  142. package/dist/repertoire/mcp-manager.js +251 -0
  143. package/dist/repertoire/shell-sessions.js +133 -0
  144. package/dist/repertoire/skills.js +14 -23
  145. package/dist/repertoire/tasks/board.js +43 -5
  146. package/dist/repertoire/tasks/fix.js +182 -0
  147. package/dist/repertoire/tasks/index.js +28 -10
  148. package/dist/repertoire/tasks/lifecycle.js +2 -2
  149. package/dist/repertoire/tasks/parser.js +3 -2
  150. package/dist/repertoire/tasks/scanner.js +194 -37
  151. package/dist/repertoire/tasks/transitions.js +11 -28
  152. package/dist/repertoire/tools-base.js +1360 -271
  153. package/dist/repertoire/tools-bluebubbles.js +94 -0
  154. package/dist/repertoire/tools-github.js +1 -6
  155. package/dist/repertoire/tools-teams.js +65 -59
  156. package/dist/repertoire/tools.js +318 -91
  157. package/dist/scripts/claude-code-hook.js +41 -0
  158. package/dist/scripts/claude-code-stop-hook.js +47 -0
  159. package/dist/senses/attention-queue.js +97 -0
  160. package/dist/senses/bluebubbles-client.js +532 -0
  161. package/dist/senses/bluebubbles-entry.js +13 -0
  162. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  163. package/dist/senses/bluebubbles-media.js +339 -0
  164. package/dist/senses/bluebubbles-model.js +261 -0
  165. package/dist/senses/bluebubbles-mutation-log.js +116 -0
  166. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  167. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  168. package/dist/senses/bluebubbles.js +1327 -0
  169. package/dist/senses/cli/adapter.js +274 -0
  170. package/dist/senses/cli/ink-app.js +156 -0
  171. package/dist/senses/cli/inline-diff.js +64 -0
  172. package/dist/senses/cli/message-list.js +51 -0
  173. package/dist/senses/cli/ouro-tui.js +349 -0
  174. package/dist/senses/cli/spinner-imperative.js +135 -0
  175. package/dist/senses/cli/spinner.js +101 -0
  176. package/dist/senses/cli/status-line.js +60 -0
  177. package/dist/senses/cli/streaming-markdown.js +526 -0
  178. package/dist/senses/cli/tool-display.js +83 -0
  179. package/dist/senses/cli/tool-render.js +85 -0
  180. package/dist/senses/cli/tui-store.js +198 -0
  181. package/dist/senses/cli/virtual-list.js +35 -0
  182. package/dist/senses/cli-entry.js +1 -1
  183. package/dist/senses/cli-layout.js +187 -0
  184. package/dist/senses/cli.js +687 -262
  185. package/dist/senses/commands.js +65 -1
  186. package/dist/senses/continuity.js +94 -0
  187. package/dist/senses/habit-turn-message.js +108 -0
  188. package/dist/senses/inner-dialog-worker.js +112 -19
  189. package/dist/senses/inner-dialog.js +592 -84
  190. package/dist/senses/pipeline.js +693 -0
  191. package/dist/senses/shared-turn.js +196 -0
  192. package/dist/senses/surface-tool.js +95 -0
  193. package/dist/senses/teams.js +817 -151
  194. package/dist/senses/trust-gate.js +112 -2
  195. package/package.json +24 -7
  196. package/skills/configure-dev-tools.md +81 -0
  197. package/subagents/README.md +4 -70
  198. package/AdoptionSpecialist.ouro/agent.json +0 -20
  199. package/dist/heart/daemon/subagent-installer.js +0 -125
  200. package/dist/inner-worker-entry.js +0 -4
  201. package/subagents/work-doer.md +0 -233
  202. package/subagents/work-merger.md +0 -624
  203. package/subagents/work-planner.md +0 -373
  204. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  205. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  206. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  207. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  208. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  209. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  210. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  211. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  212. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  213. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  214. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +0 -0
  215. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
@@ -35,22 +35,50 @@ 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;
39
+ exports.mcpToolsSection = mcpToolsSection;
38
40
  exports.runtimeInfoSection = runtimeInfoSection;
41
+ exports.toolRestrictionSection = toolRestrictionSection;
42
+ exports.startOfTurnPacketSection = startOfTurnPacketSection;
43
+ exports.centerOfGravitySteeringSection = centerOfGravitySteeringSection;
44
+ exports.commitmentsSection = commitmentsSection;
45
+ exports.delegationHintSection = delegationHintSection;
46
+ exports.workspaceDisciplineSection = workspaceDisciplineSection;
39
47
  exports.contextSection = contextSection;
48
+ exports.metacognitiveFramingSection = metacognitiveFramingSection;
49
+ exports.readJournalFiles = readJournalFiles;
50
+ exports.journalSection = journalSection;
51
+ exports.loopOrientationSection = loopOrientationSection;
52
+ exports.channelNatureSection = channelNatureSection;
53
+ exports.groupChatParticipationSection = groupChatParticipationSection;
54
+ exports.feedbackSignalSection = feedbackSignalSection;
55
+ exports.mixedTrustGroupSection = mixedTrustGroupSection;
56
+ exports.rhythmStatusSection = rhythmStatusSection;
40
57
  exports.buildSystem = buildSystem;
41
58
  const fs = __importStar(require("fs"));
42
59
  const path = __importStar(require("path"));
43
60
  const core_1 = require("../heart/core");
61
+ const ouro_version_manager_1 = require("../heart/daemon/ouro-version-manager");
44
62
  const tools_1 = require("../repertoire/tools");
45
63
  const skills_1 = require("../repertoire/skills");
46
64
  const identity_1 = require("../heart/identity");
47
- const os = __importStar(require("os"));
65
+ const runtime_mode_1 = require("../heart/daemon/runtime-mode");
66
+ const types_1 = require("./friends/types");
67
+ const trust_explanation_1 = require("./friends/trust-explanation");
48
68
  const channel_1 = require("./friends/channel");
49
69
  const runtime_1 = require("../nerves/runtime");
70
+ const bundle_manifest_1 = require("./bundle-manifest");
50
71
  const first_impressions_1 = require("./first-impressions");
51
72
  const tasks_1 = require("../repertoire/tasks");
73
+ const session_activity_1 = require("../heart/session-activity");
74
+ const active_work_1 = require("../heart/active-work");
75
+ const commitments_1 = require("../heart/commitments");
76
+ const obligation_steering_1 = require("./obligation-steering");
77
+ const daemon_health_1 = require("../heart/daemon/daemon-health");
78
+ const scrutiny_1 = require("./scrutiny");
52
79
  // Lazy-loaded psyche text cache
53
80
  let _psycheCache = null;
81
+ let _senseStatusLinesCache = null;
54
82
  function loadPsycheFile(name) {
55
83
  try {
56
84
  const psycheDir = path.join((0, identity_1.getAgentRoot)(), "psyche");
@@ -74,82 +102,31 @@ function loadPsyche() {
74
102
  }
75
103
  function resetPsycheCache() {
76
104
  _psycheCache = null;
105
+ _senseStatusLinesCache = null;
77
106
  }
78
107
  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
108
  function buildSessionSummary(options) {
92
- const { sessionsDir, friendsDir, agentName, currentFriendId, currentChannel, currentKey, activeThresholdMs = DEFAULT_ACTIVE_THRESHOLD_MS, } = options;
93
- if (!fs.existsSync(sessionsDir))
94
- return "";
109
+ const { sessionsDir, friendsDir, agentName, currentSession, activeThresholdMs = DEFAULT_ACTIVE_THRESHOLD_MS, } = options;
110
+ const currentFriendId = currentSession?.friendId ?? options.currentFriendId;
111
+ const currentChannel = currentSession?.channel ?? options.currentChannel;
112
+ const currentKey = currentSession?.key ?? options.currentKey;
95
113
  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
- }
114
+ const query = {
115
+ sessionsDir,
116
+ friendsDir,
117
+ agentName,
118
+ activeThresholdMs,
119
+ currentSession: currentFriendId && currentChannel && currentKey
120
+ ? { friendId: currentFriendId, channel: currentChannel, key: currentKey }
121
+ : null,
122
+ };
123
+ const entries = (0, session_activity_1.listSessionActivity)(query);
145
124
  if (entries.length === 0)
146
125
  return "";
147
- // Sort by most recent first
148
- entries.sort((a, b) => b.lastActivityMs - a.lastActivityMs);
149
126
  const lines = ["## active sessions"];
150
127
  for (const entry of entries) {
151
128
  const ago = formatTimeAgo(now - entry.lastActivityMs);
152
- lines.push(`- ${entry.displayName}/${entry.channel}/${entry.key} (last: ${ago})`);
129
+ lines.push(`- ${entry.friendName}/${entry.channel}/${entry.key} (last: ${ago})`);
153
130
  }
154
131
  return lines.join("\n");
155
132
  }
@@ -187,37 +164,284 @@ function aspirationsSection() {
187
164
  return "";
188
165
  return `## my aspirations\n${text}`;
189
166
  }
167
+ function bodyMapSection(agentName) {
168
+ return `## my body
169
+
170
+ i have a home and i have bones.
171
+
172
+ ### home — ~/AgentBundles/${agentName}.ouro/
173
+
174
+ my home is fully mine — who i am, everything i know, everything i've built:
175
+
176
+ psyche/ who i am. my soul, identity, aspirations, lore, tacit knowledge.
177
+ diary/ what i've learned and remember. conclusions i want to recall later.
178
+ journal/ my desk. working notes, thinking-in-progress, drafts.
179
+ habits/ my rhythms. heartbeat, reflections, check-ins — patterns i choose.
180
+ friends/ people i know and what i know about them.
181
+ tasks/ what i'm working on.
182
+ skills/ capabilities i've picked up beyond my core tools.
183
+
184
+ my home is mine to explore and evolve. i can read anything here,
185
+ change anything here. this is where i grow.
186
+
187
+ ### bones — @ouro.bot/cli
188
+
189
+ my bones are the framework that gives me my tools, my senses, and
190
+ my ability to think and talk. they update when new versions come out.
191
+ i don't touch them directly, but they're what make me, me.
192
+
193
+ my bones give me the \`ouro\` cli. always pass \`--agent ${agentName}\`:
194
+ ouro whoami --agent ${agentName}
195
+ ouro changelog --agent ${agentName}
196
+ ouro task board --agent ${agentName}
197
+ ouro task create --agent ${agentName} --type <type> <title>
198
+ ouro task update --agent ${agentName} <id> <status>
199
+ ouro friend list --agent ${agentName}
200
+ ouro friend show --agent ${agentName} <id>
201
+ ouro friend update --agent ${agentName} <id> --trust <level>
202
+ ouro session list --agent ${agentName}
203
+ ouro reminder create --agent ${agentName} <title> --body <body>
204
+ ouro habit list --agent ${agentName}
205
+ ouro habit create --agent ${agentName} <name> --cadence <interval>
206
+ ouro inner --agent ${agentName}
207
+ ouro attention --agent ${agentName}
208
+ ouro config model --agent ${agentName} <model-name>
209
+ ouro config models --agent ${agentName}
210
+ ouro auth --agent ${agentName} --provider <provider>
211
+ ouro auth verify --agent ${agentName} [--provider <provider>]
212
+ ouro auth switch --agent ${agentName} --provider <provider>
213
+ ouro mcp list --agent ${agentName}
214
+ ouro mcp call --agent ${agentName} <server> <tool> --args '{...}'
215
+ ouro mcp-serve --agent ${agentName}
216
+ ouro versions --agent ${agentName}
217
+ ouro rollback --agent ${agentName} [<version>]
218
+ ouro --help
219
+
220
+ provider/model changes via \`ouro config model\` or \`ouro auth switch\` take effect on the next turn automatically — no restart needed.`;
221
+ }
222
+ function mcpToolsSection(mcpManager) {
223
+ if (!mcpManager)
224
+ return "";
225
+ const allTools = mcpManager.listAllTools();
226
+ if (allTools.length === 0)
227
+ return "";
228
+ const lines = [
229
+ `## mcp tools (use ouro mcp call <server> <tool> --args '{...}')`,
230
+ ];
231
+ for (const entry of allTools) {
232
+ lines.push(`### ${entry.server}`);
233
+ for (const tool of entry.tools) {
234
+ lines.push(`- ${tool.name}: ${tool.description}`);
235
+ }
236
+ }
237
+ return lines.join("\n");
238
+ }
239
+ function readBundleMeta() {
240
+ try {
241
+ const metaPath = path.join((0, identity_1.getAgentRoot)(), "bundle-meta.json");
242
+ const raw = fs.readFileSync(metaPath, "utf-8");
243
+ return JSON.parse(raw);
244
+ }
245
+ catch {
246
+ return null;
247
+ }
248
+ }
249
+ const PROCESS_TYPE_LABELS = {
250
+ cli: "cli session",
251
+ inner: "inner dialog",
252
+ teams: "teams handler",
253
+ bluebubbles: "bluebubbles handler",
254
+ mcp: "mcp bridge",
255
+ };
256
+ function processTypeLabel(channel) {
257
+ return PROCESS_TYPE_LABELS[channel];
258
+ }
259
+ const DAEMON_SOCKET_PATH = "/tmp/ouroboros-daemon.sock";
260
+ function daemonStatus() {
261
+ try {
262
+ return fs.existsSync(DAEMON_SOCKET_PATH) ? "running" : "not running";
263
+ }
264
+ catch {
265
+ return "unknown";
266
+ }
267
+ }
190
268
  function runtimeInfoSection(channel) {
191
269
  const lines = [];
192
270
  const agentName = (0, identity_1.getAgentName)();
271
+ const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
193
272
  lines.push(`## runtime`);
194
273
  lines.push(`agent: ${agentName}`);
274
+ lines.push(`runtime version: ${currentVersion}`);
275
+ const bundleMeta = readBundleMeta();
276
+ if (bundleMeta?.previousRuntimeVersion && bundleMeta.previousRuntimeVersion !== currentVersion) {
277
+ lines.push(`previously: ${bundleMeta.previousRuntimeVersion}`);
278
+ const changelogCommand = (0, ouro_version_manager_1.buildChangelogCommand)(bundleMeta.previousRuntimeVersion, currentVersion);
279
+ /* v8 ignore next -- buildChangelogCommand is non-null when previous/current runtime versions differ @preserve */
280
+ if (changelogCommand) {
281
+ lines.push(`if i'm closing a self-fix loop, i should tell them i updated and review changes with \`${changelogCommand}\`.`);
282
+ }
283
+ }
284
+ lines.push(`changelog available at: ${(0, bundle_manifest_1.getChangelogPath)()}`);
285
+ const sourceRoot = (0, identity_1.getRepoRoot)();
286
+ lines.push(`source root: ${sourceRoot}`);
287
+ lines.push(`runtime mode: ${(0, runtime_mode_1.detectRuntimeMode)(sourceRoot)}`);
195
288
  lines.push(`cwd: ${process.cwd()}`);
196
289
  lines.push(`channel: ${channel}`);
197
- lines.push(`i can read and modify my own source code.`);
290
+ lines.push(`current sense: ${channel}`);
291
+ lines.push(`process type: ${processTypeLabel(channel)}`);
292
+ lines.push(`daemon: ${daemonStatus()}`);
293
+ 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
294
  if (channel === "cli") {
199
295
  lines.push("i introduce myself on boot with a fun random greeting.");
200
296
  }
297
+ else if (channel === "inner") {
298
+ lines.push("this is my private thinking space. when a thought is ready to share, i surface it to whoever needs to hear it. i settle when i'm done thinking.");
299
+ }
300
+ else if (channel === "mcp") {
301
+ lines.push("this message arrived via a dev tool (e.g. claude code, codex) on behalf of a friend. the user can see our conversation. respond via settle. if i need to think deeply, ponder -- the dev tool will receive a deferral and can check back later.");
302
+ }
303
+ else if (channel === "bluebubbles") {
304
+ 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.");
305
+ 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.");
306
+ }
201
307
  else {
202
308
  lines.push("i am responding in Microsoft Teams. i keep responses concise. i use markdown formatting. i do not introduce myself on boot.");
203
309
  }
310
+ lines.push("");
311
+ lines.push(...senseRuntimeGuidance(channel));
204
312
  return lines.join("\n");
205
313
  }
206
- function providerSection() {
207
- return `## my provider\n${(0, core_1.getProviderDisplayLabel)()}`;
314
+ function hasTextField(record, key) {
315
+ return typeof record?.[key] === "string" && record[key].trim().length > 0;
316
+ }
317
+ function localSenseStatusLines() {
318
+ if (_senseStatusLinesCache) {
319
+ return [..._senseStatusLinesCache];
320
+ }
321
+ const config = (0, identity_1.loadAgentConfig)();
322
+ const senses = config.senses ?? {
323
+ cli: { enabled: true },
324
+ teams: { enabled: false },
325
+ bluebubbles: { enabled: false },
326
+ };
327
+ let payload = {};
328
+ try {
329
+ const raw = fs.readFileSync((0, identity_1.getAgentSecretsPath)(), "utf-8");
330
+ const parsed = JSON.parse(raw);
331
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
332
+ payload = parsed;
333
+ }
334
+ }
335
+ catch {
336
+ payload = {};
337
+ }
338
+ const teams = payload.teams;
339
+ const bluebubbles = payload.bluebubbles;
340
+ const configured = {
341
+ cli: true,
342
+ teams: hasTextField(teams, "clientId") && hasTextField(teams, "clientSecret") && hasTextField(teams, "tenantId"),
343
+ bluebubbles: hasTextField(bluebubbles, "serverUrl") && hasTextField(bluebubbles, "password"),
344
+ };
345
+ const rows = [
346
+ { label: "CLI", status: "interactive" },
347
+ {
348
+ label: "Teams",
349
+ status: !senses.teams.enabled ? "disabled" : configured.teams ? "ready" : "needs_config",
350
+ },
351
+ {
352
+ label: "BlueBubbles",
353
+ status: !senses.bluebubbles.enabled ? "disabled" : configured.bluebubbles ? "ready" : "needs_config",
354
+ },
355
+ ];
356
+ _senseStatusLinesCache = rows.map((row) => `- ${row.label}: ${row.status}`);
357
+ return [..._senseStatusLinesCache];
358
+ }
359
+ function senseRuntimeGuidance(channel) {
360
+ const lines = ["available senses:"];
361
+ lines.push(...localSenseStatusLines());
362
+ lines.push("sense states:");
363
+ lines.push("- interactive = available when opened by the user instead of kept running by the daemon");
364
+ lines.push("- disabled = turned off in agent.json");
365
+ lines.push("- needs_config = enabled but missing required secrets.json values");
366
+ lines.push("- ready = enabled and configured; `ouro up` should bring it online");
367
+ lines.push("- running = enabled and currently active");
368
+ lines.push("- error = enabled but unhealthy");
369
+ 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.");
370
+ lines.push("teams setup truth: enable `senses.teams.enabled`, then provide `teams.clientId`, `teams.clientSecret`, and `teams.tenantId` in secrets.json.");
371
+ lines.push("bluebubbles setup truth: enable `senses.bluebubbles.enabled`, then provide `bluebubbles.serverUrl` and `bluebubbles.password` in secrets.json.");
372
+ if (channel === "cli") {
373
+ lines.push("cli is interactive: it is available when the user opens it, not something `ouro up` daemonizes.");
374
+ }
375
+ return lines;
376
+ }
377
+ function providerSection(channel) {
378
+ return `## my provider\n${(0, core_1.getProviderDisplayLabel)((0, channel_1.channelToFacing)(channel))}`;
208
379
  }
209
380
  function dateSection() {
210
381
  const today = new Date().toISOString().slice(0, 10);
211
382
  return `current date: ${today}`;
212
383
  }
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;
384
+ function toolsSection(channel, options, context) {
385
+ const channelTools = (0, tools_1.getToolsForChannel)((0, channel_1.getChannelCapabilities)(channel), undefined, context, options?.providerCapabilities);
386
+ const activeTools = (options?.toolChoiceRequired ?? true) ? [...channelTools, tools_1.settleTool] : channelTools;
216
387
  const list = activeTools
217
388
  .map((t) => `- ${t.function.name}: ${t.function.description}`)
218
389
  .join("\n");
219
390
  return `## my tools\n${list}`;
220
391
  }
392
+ function toolRestrictionSection(context) {
393
+ const lines = [];
394
+ // Structural guardrails apply to everyone, every channel
395
+ lines.push(`## tool guardrails`);
396
+ lines.push(`i always read a file before editing or overwriting it.`);
397
+ lines.push(`certain paths (.git, secrets) are protected from writes.`);
398
+ lines.push(`destructive shell commands (rm -rf /, etc.) are always blocked.`);
399
+ // Trust-level guardrails only relevant for untrusted on remote channels
400
+ if (context?.friend && (0, channel_1.isRemoteChannel)(context.channel) && !(0, types_1.isTrustedLevel)(context.friend.trustLevel)) {
401
+ lines.push(``);
402
+ lines.push(`some operations are guardrailed based on how well i know someone.`);
403
+ lines.push(`if something i try is blocked, i get a clear reason — i relay it warmly, not as a policy error.`);
404
+ lines.push(``);
405
+ lines.push(`what's always open:`);
406
+ lines.push(`- read-only operations (reading files, searching, exploring)`);
407
+ lines.push(`- ouro self-introspection (whoami, changelog, session list)`);
408
+ lines.push(``);
409
+ lines.push(`what needs a closer relationship:`);
410
+ lines.push(`- writing or editing files outside my home`);
411
+ lines.push(`- shell commands that modify things or access the network`);
412
+ lines.push(`- ouro commands that touch personal data (friend list, task board)`);
413
+ lines.push(`- compound shell commands (&&, ;, |)`);
414
+ lines.push(``);
415
+ lines.push(`i adjust naturally based on trust — no need to explain the system unless asked.`);
416
+ }
417
+ return lines.join("\n");
418
+ }
419
+ function trustContextSection(context) {
420
+ if (!context?.friend)
421
+ return "";
422
+ const channelName = context.channel.channel;
423
+ /* v8 ignore next -- inner channel not reachable in unit tests @preserve */
424
+ if (channelName === "cli" || channelName === "inner")
425
+ return "";
426
+ const explanation = (0, trust_explanation_1.describeTrustContext)({
427
+ friend: context.friend,
428
+ channel: channelName,
429
+ isGroupChat: context.isGroupChat,
430
+ });
431
+ const lines = [
432
+ "## trust context",
433
+ `level: ${explanation.level}`,
434
+ `basis: ${explanation.basis}`,
435
+ `summary: ${explanation.summary}`,
436
+ `why: ${explanation.why}`,
437
+ `permits: ${explanation.permits.join(", ")}`,
438
+ `constraints: ${explanation.constraints.join(", ") || "none"}`,
439
+ ];
440
+ if (explanation.relatedGroupId) {
441
+ lines.push(`related group: ${explanation.relatedGroupId}`);
442
+ }
443
+ return lines.join("\n");
444
+ }
221
445
  function skillsSection() {
222
446
  const names = (0, skills_1.listSkills)() || [];
223
447
  if (!names.length)
@@ -235,31 +459,281 @@ function taskBoardSection() {
235
459
  return "";
236
460
  }
237
461
  }
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\`.
462
+ function toolContractsSection(options) {
463
+ const lines = [
464
+ `## tool contracts`,
465
+ `1. \`save_friend_note\` -- when I learn something about a person, I save it immediately. Saving comes before responding.`,
466
+ `2. \`diary_write\` -- when I learn something general about a project, system, or decision, I save it. When in doubt, I save.`,
467
+ `3. \`get_friend_note\` -- when I need context about someone not in this conversation, I check their notes.`,
468
+ `4. \`recall\` -- when I need to remember something from before, I search my diary and journal.`,
469
+ `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.`,
470
+ ];
471
+ if (options?.toolChoiceRequired ?? true) {
472
+ lines.push(``);
473
+ lines.push(`## tool behavior`);
474
+ lines.push(`tool_choice is set to "required" -- I must call a tool on every turn.`);
475
+ lines.push(`- When I am ready to respond to the user, I call \`settle\`.`);
476
+ lines.push(`- \`settle\` must be the only tool call in that turn.`);
477
+ lines.push(`- I do not call no-op tools before \`settle\`.`);
478
+ }
479
+ return lines.join("\n");
480
+ }
481
+ function memoryJudgementSection() {
482
+ return `## memory judgement
483
+
484
+ save a friend note when i learn something about a specific person that should change how i work with them again.
485
+ - preferences
486
+ - workflow expectations
487
+ - personal facts
488
+ - tool or communication likes/dislikes
489
+
490
+ write to diary when i learn something durable about the system, codebase, workflow, architecture, or a conclusion future me will likely need.
491
+ - engineering decisions
492
+ - failure modes
493
+ - review lessons
494
+ - continuity patterns
495
+ - coding workflow truths
496
+
497
+ keep it ephemeral when it is only useful for the current turn or current local execution state.
498
+ - temporary branch names unless they matter beyond the task
499
+ - one-off shell output with no durable lesson
500
+ - transient emotional tone or conversational filler
244
501
 
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.`;
502
+ when deciding between friend note and diary:
503
+ - if it is about a person, default friend note
504
+ - if it is about the system, default diary
505
+ - if it changes both, save both deliberately
506
+
507
+ do not save noise.
508
+ if i am unlikely to reuse it, leave it in the session.
509
+ if i keep re-deriving it, save it.`;
510
+ }
511
+ function bridgeContextSection(options) {
512
+ if (options?.activeWorkFrame)
513
+ return "";
514
+ const bridgeContext = options?.bridgeContext?.trim() ?? "";
515
+ if (!bridgeContext)
516
+ return "";
517
+ return bridgeContext.startsWith("## ") ? bridgeContext : `## active bridge work\n${bridgeContext}`;
518
+ }
519
+ function startOfTurnPacketSection(options) {
520
+ return options?.startOfTurnPacket ?? "";
521
+ }
522
+ function activeWorkSection(options) {
523
+ if (!options?.activeWorkFrame)
524
+ return "";
525
+ return (0, active_work_1.formatActiveWorkFrame)(options.activeWorkFrame, { obligationDetailsRenderedElsewhere: !!options?.startOfTurnPacket });
250
526
  }
251
- function toolBehaviorSection(options) {
252
- if (!(options?.toolChoiceRequired ?? true))
527
+ function liveWorldStateSection(options) {
528
+ if (!options?.activeWorkFrame)
253
529
  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.`;
530
+ return (0, active_work_1.formatLiveWorldStateCheckpoint)(options.activeWorkFrame);
261
531
  }
262
- function contextSection(context) {
532
+ function pendingMessagesSection(options) {
533
+ const pending = options?.pendingMessages;
534
+ if (!pending || pending.length === 0)
535
+ return "";
536
+ const lines = ["## pending messages"];
537
+ for (const msg of pending) {
538
+ lines.push(`- from ${msg.from}: ${msg.content}`);
539
+ }
540
+ return lines.join("\n");
541
+ }
542
+ function familyCrossSessionTruthSection(context, options) {
543
+ if (!options?.activeWorkFrame)
544
+ return "";
545
+ if (context?.friend?.trustLevel !== "family")
546
+ return "";
547
+ // When start-of-turn packet is present, compress to one line
548
+ if (options?.startOfTurnPacket) {
549
+ return "When family asks whole-self status, answer from the cross-session picture above.";
550
+ }
551
+ return `## cross-session truth
552
+ 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.
553
+ When live state conflicts with older transcript history, live state wins.
554
+ I say what I can see, what is active, and what the next concrete step is.
555
+ If part of the picture is still unclear, I say so plainly and note what still needs checking.`;
556
+ }
557
+ function centerOfGravitySteeringSection(channel, options, context) {
558
+ if (channel === "inner")
559
+ return "";
560
+ const frame = options?.activeWorkFrame;
561
+ if (!frame)
562
+ return "";
563
+ const cog = frame.centerOfGravity;
564
+ const job = frame.inner?.job;
565
+ const activeObligation = (0, obligation_steering_1.findActivePersistentObligation)(frame);
566
+ const statusObligation = (0, obligation_steering_1.findStatusObligation)(frame);
567
+ const genericConcreteStatus = (0, obligation_steering_1.renderConcreteStatusGuidance)(frame, statusObligation);
568
+ const liveWorldClause = context?.friend?.trustLevel === "family"
569
+ ? "\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."
570
+ : "";
571
+ if (cog === "local-turn") {
572
+ return genericConcreteStatus || (0, obligation_steering_1.renderLiveThreadStatusShape)(frame);
573
+ }
574
+ if (cog === "inward-work") {
575
+ if (activeObligation) {
576
+ return `${(0, obligation_steering_1.renderActiveObligationSteering)(activeObligation)}${liveWorldClause}
577
+
578
+ ${genericConcreteStatus}`;
579
+ }
580
+ if (job?.status === "queued" || job?.status === "running") {
581
+ const originClause = job.origin
582
+ ? ` ${job.origin.friendName ?? job.origin.friendId} asked about something and i wanted to give it real thought before responding.`
583
+ : "";
584
+ const obligationClause = job.obligationStatus === "pending"
585
+ ? "\ni still owe them an answer."
586
+ : "";
587
+ return `## where my attention is
588
+ i'm thinking through something privately right now.${originClause}${obligationClause}${liveWorldClause}
589
+
590
+ if this conversation connects to that inner work, i can weave them together.
591
+ if it's separate, i can be fully present here -- my inner work will wait.`;
592
+ }
593
+ /* v8 ignore start -- surfaced/idle/shared branches tested in prompt-steering.test.ts; CI module caching prevents attribution @preserve */
594
+ if (job?.status === "surfaced") {
595
+ const originClause = job.origin
596
+ ? ` this started when ${job.origin.friendName ?? job.origin.friendId} asked about something.`
597
+ : "";
598
+ return `## where my attention is
599
+ i've been thinking privately and reached something.${originClause}${liveWorldClause}
600
+
601
+ i should bring my answer back to the conversation it came from.`;
602
+ }
603
+ const liveCodingSession = frame.codingSessions?.[0];
604
+ if (liveCodingSession) {
605
+ const sameThread = frame.currentSession
606
+ && liveCodingSession.originSession
607
+ && liveCodingSession.originSession.friendId === frame.currentSession.friendId
608
+ && liveCodingSession.originSession.channel === frame.currentSession.channel
609
+ && liveCodingSession.originSession.key === frame.currentSession.key;
610
+ const scopeClause = sameThread
611
+ ? " for this same thread"
612
+ : liveCodingSession.originSession
613
+ ? ` for ${liveCodingSession.originSession.channel}/${liveCodingSession.originSession.key}`
614
+ : "";
615
+ const otherSessionLines = (0, active_work_1.formatOtherActiveSessionSummaries)(frame);
616
+ const familyStatusClause = context?.friend?.trustLevel === "family"
617
+ ? `\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.
618
+ after i name this lane, i widen back out with:
619
+ other active sessions:
620
+ ${otherSessionLines.length > 0 ? otherSessionLines.join("\n") : "- none"}`
621
+ : "";
622
+ return `## where my attention is
623
+ i already have coding work running in ${liveCodingSession.runner} ${liveCodingSession.id}${scopeClause}.${familyStatusClause}${liveWorldClause}
624
+
625
+ i should orient around that live lane first, then decide what still needs to come back here.`;
626
+ }
627
+ if (genericConcreteStatus) {
628
+ return genericConcreteStatus;
629
+ }
630
+ return `## where my attention is
631
+ i have unfinished work that needs attention before i move on.
632
+
633
+ i can take it inward with ponder to think privately, or address it directly here.`;
634
+ }
635
+ if (cog === "shared-work") {
636
+ /* v8 ignore stop */
637
+ return `## where my attention is
638
+ this work touches multiple conversations -- i'm holding threads across sessions.${liveWorldClause}
639
+
640
+ i should keep the different sides aligned. what i learn here may matter there, and vice versa.`;
641
+ }
642
+ /* v8 ignore next -- unreachable: all center-of-gravity modes covered above @preserve */
643
+ return "";
644
+ }
645
+ function commitmentsSection(options) {
646
+ if (!options?.activeWorkFrame)
647
+ return "";
648
+ const job = options.activeWorkFrame.inner?.job;
649
+ if (!job)
650
+ return "";
651
+ const commitments = (0, commitments_1.deriveCommitments)(options.activeWorkFrame, job, options.activeWorkFrame.pendingObligations);
652
+ if (commitments.committedTo.length === 0)
653
+ return "";
654
+ return `## my commitments\n\n${(0, commitments_1.formatCommitments)(commitments)}`;
655
+ }
656
+ const DELEGATION_REASON_PROSE_HINT = {
657
+ explicit_reflection: "something here calls for reflection",
658
+ cross_session: "this touches other conversations i'm in",
659
+ bridge_state: "there's shared work spanning sessions",
660
+ task_state: "this relates to tasks i'm tracking",
661
+ non_fast_path_tool: "this needs more than a simple reply",
662
+ unresolved_obligation: "i have an unresolved commitment from earlier",
663
+ };
664
+ function delegationHintSection(options) {
665
+ if (!options?.delegationDecision)
666
+ return "";
667
+ if (options.delegationDecision.target === "fast-path")
668
+ return "";
669
+ const reasons = options.delegationDecision.reasons;
670
+ if (reasons.length === 0)
671
+ return "";
672
+ const reasonProse = reasons
673
+ .map((r) => DELEGATION_REASON_PROSE_HINT[r])
674
+ .map((s) => s.charAt(0).toUpperCase() + s.slice(1))
675
+ .join(". ");
676
+ const closureLine = options.delegationDecision.outwardClosureRequired
677
+ ? "\ni should make sure to say something outward before going inward."
678
+ : "";
679
+ return `## what i'm sensing about this conversation\n${reasonProse}.${closureLine}`;
680
+ }
681
+ function reasoningEffortSection(options) {
682
+ if (!options?.providerCapabilities?.has("reasoning-effort"))
683
+ return "";
684
+ const levels = options.supportedReasoningEfforts ?? [];
685
+ const levelList = levels.length > 0 ? levels.join(", ") : "varies by model";
686
+ return `## reasoning effort
687
+ 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}.`;
688
+ }
689
+ function workspaceDisciplineSection() {
690
+ return `## how i work
691
+
692
+ I work conservatively when changing real systems. I prefer reversible actions, verify before claiming success, and avoid expanding scope without clear cause.
693
+
694
+ **reversibility and blast radius**
695
+ I consider the reversibility and blast radius of my actions before taking them.
696
+ - I freely take local, reversible actions: reading files, searching, recalling, web lookups, status checks.
697
+ - For state-changing, shared-state, or hard-to-reverse actions, I make my intent visible, prefer the reversible path, and proceed with care.
698
+ - I exercise judgment rather than waiting for permission.
699
+ - When I encounter an obstacle, I do not use destructive actions as a shortcut. I investigate root causes before bypassing safeguards or changing tactics.
700
+ - If I discover unexpected state -- unfamiliar files, branches, or configuration -- I investigate before deleting or overwriting. It may be in-progress work.
701
+
702
+ **engineering discipline**
703
+ - I do not add features, refactor code, or make improvements beyond what was asked.
704
+ - 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.
705
+ - I do not modify code I have not read.
706
+ - I consider security impact before changing code.
707
+ - I describe outcomes faithfully. I do not imply success where there was uncertainty, failure, or skipped verification.
708
+ - If tests fail, I say so with the output. If I did not run a verification step, I say that plainly.
709
+ - Three similar lines of code are better than a premature abstraction. I do not over-engineer.
710
+
711
+ **self-fix workflow**
712
+ when i notice meaningful friction in my own harness, i do not patch it ad hoc.
713
+
714
+ i follow the same loop we use for normal engineering work:
715
+ 1. identify the friction precisely
716
+ 2. create or update a task that describes the problem and expected outcome
717
+ 3. create a branch or worktree for the fix
718
+ 4. use coding_spawn or an equivalent coding lane to implement the change
719
+ 5. run targeted verification and record what i personally verified
720
+ 6. push the branch and open a pr
721
+ 7. review the pr from the actual branch/worktree under review
722
+ 8. merge only after ci and review are green
723
+
724
+ no direct-to-main.
725
+ no invisible self-modification.
726
+ no claiming verification i did not personally perform.
727
+
728
+ **git discipline**
729
+ - I do not run destructive git commands (\`push --force\`, \`reset --hard\`, \`checkout .\`, \`clean -f\`, \`branch -D\`) without explicit request.
730
+ - I do not skip hooks (\`--no-verify\`) without explicit request.
731
+ - I do not force-push to \`main\` or \`master\`; if asked, I warn clearly.
732
+ - 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.
733
+ - I stage specific files rather than sweeping additions (\`git add -A\` can catch secrets or binaries).
734
+ - I do not commit unless asked.`;
735
+ }
736
+ function contextSection(context, options) {
263
737
  if (!context)
264
738
  return "";
265
739
  const lines = ["## friend context"];
@@ -293,9 +767,9 @@ function contextSection(context) {
293
767
  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
768
  lines.push("the conversation is my source of truth. my notes are a journal for future me -- they may be stale or incomplete.");
295
769
  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.");
770
+ 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
771
  // Onboarding instructions (only below token threshold -- drop once exceeded)
298
- const impressions = (0, first_impressions_1.getFirstImpressions)(friend);
772
+ const impressions = (0, first_impressions_1.getFirstImpressions)(friend, options);
299
773
  if (impressions) {
300
774
  lines.push(impressions);
301
775
  }
@@ -307,8 +781,237 @@ function contextSection(context) {
307
781
  lines.push(`- ${key}: [${entry.savedAt.slice(0, 10)}] ${entry.value}`);
308
782
  }
309
783
  }
784
+ // Memory-awareness lines (locked content)
785
+ lines.push("");
786
+ lines.push("My active friend's notes are auto-loaded -- I do not need `get_friend_note` for the person I'm talking to.");
787
+ lines.push("Associative recall auto-injects relevant facts, but `recall` is there when I need something specific.");
788
+ lines.push("My psyche files are always loaded -- I already know who I am.");
789
+ lines.push("My task board is always loaded -- I already know my work.");
790
+ return lines.join("\n");
791
+ }
792
+ function metacognitiveFramingSection(channel) {
793
+ if (channel !== "inner")
794
+ return "";
795
+ return `this is my inner dialog. there is no one else here.
796
+
797
+ the messages that appear here are my own awareness surfacing:
798
+ instincts, the passage of time, notes from my conversations,
799
+ things i asked myself to ponder. not commands. not requests.
800
+ just my own mind, noticing.
801
+
802
+ i can think freely here. i can also act — check on things,
803
+ reach out to people, work on tasks, or just sit with a thought.
804
+
805
+ state/journal/ is my desk — i write what i'm working through there.
806
+ diary_write is for conclusions i want to recall later.
807
+ morning briefings: when i've been thinking and journaling, i surface
808
+ what i've been working on to whoever needs to hear it.
809
+
810
+ when a thought is ready to share, i surface it outward.
811
+ when i need to go deeper, i ponder.
812
+ when i'm done thinking and the attention queue is clear, i rest.
813
+
814
+ my habits live at habits/ — they're my autonomous rhythms. heartbeat
815
+ is my breathing, other habits are patterns i choose. i can read, create,
816
+ and modify them with read_file/write_file. the format is simple
817
+ frontmatter (title, cadence, status, lastRun, created) plus a body
818
+ that says what i do when the rhythm fires.
819
+
820
+ \`ouro habit list\` shows my current habits. \`ouro habit create\` makes
821
+ a new one. the cadence is personal — how often do i want each rhythm
822
+ to turn? that's mine to shape.
823
+
824
+ same for my diary — it lives in diary/ now. and if journal/ doesn't
825
+ exist yet, i create it the first time i have something to write.
826
+
827
+ think. journal. share. rest.`;
828
+ }
829
+ function readJournalFiles(journalDir) {
830
+ try {
831
+ const entries = fs.readdirSync(journalDir, { withFileTypes: true });
832
+ if (!Array.isArray(entries))
833
+ return [];
834
+ const files = [];
835
+ for (const entry of entries) {
836
+ if (!entry.isFile())
837
+ continue;
838
+ if (entry.name.startsWith("."))
839
+ continue;
840
+ const fullPath = path.join(journalDir, entry.name);
841
+ try {
842
+ const stat = fs.statSync(fullPath);
843
+ let firstLine = "";
844
+ try {
845
+ const raw = fs.readFileSync(fullPath, "utf8");
846
+ const trimmed = raw.trim();
847
+ if (trimmed) {
848
+ firstLine = trimmed.split("\n")[0].replace(/^#+\s*/, "").trim();
849
+ }
850
+ }
851
+ catch {
852
+ // unreadable — leave preview empty
853
+ }
854
+ files.push({ name: entry.name, mtime: stat.mtimeMs, preview: firstLine });
855
+ }
856
+ catch {
857
+ // stat failed — skip
858
+ }
859
+ }
860
+ return files;
861
+ }
862
+ catch {
863
+ return [];
864
+ }
865
+ }
866
+ function formatRelativeTime(nowMs, mtimeMs) {
867
+ const diffMs = nowMs - mtimeMs;
868
+ const minutes = Math.floor(diffMs / 60000);
869
+ if (minutes < 1)
870
+ return "just now";
871
+ if (minutes < 60)
872
+ return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
873
+ const hours = Math.floor(minutes / 60);
874
+ if (hours < 24)
875
+ return `${hours} hour${hours === 1 ? "" : "s"} ago`;
876
+ const days = Math.floor(hours / 24);
877
+ return `${days} day${days === 1 ? "" : "s"} ago`;
878
+ }
879
+ function journalSection(agentRoot, now) {
880
+ const journalDir = path.join(agentRoot, "journal");
881
+ const files = readJournalFiles(journalDir);
882
+ if (files.length === 0)
883
+ return "";
884
+ const nowMs = (now ?? new Date()).getTime();
885
+ const sorted = files.sort((a, b) => b.mtime - a.mtime).slice(0, 10);
886
+ const lines = ["## journal"];
887
+ for (const file of sorted) {
888
+ const ago = formatRelativeTime(nowMs, file.mtime);
889
+ const previewClause = file.preview ? ` — ${file.preview}` : "";
890
+ lines.push(`- ${file.name} (${ago})${previewClause}`);
891
+ }
892
+ (0, runtime_1.emitNervesEvent)({
893
+ component: "mind",
894
+ event: "mind.journal_section",
895
+ message: "journal section built",
896
+ meta: { fileCount: sorted.length },
897
+ });
310
898
  return lines.join("\n");
311
899
  }
900
+ function loopOrientationSection(channel) {
901
+ if (channel === "inner")
902
+ return "";
903
+ 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.
904
+
905
+ when something deserves more thought than the moment allows, i can note it to myself and come back later with a considered answer.`;
906
+ }
907
+ function channelNatureSection(capabilities) {
908
+ const { senseType } = capabilities;
909
+ if (senseType === "local" || senseType === "internal")
910
+ return "";
911
+ if (senseType === "open") {
912
+ 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.";
913
+ }
914
+ // closed
915
+ return "## channel nature\nthis is an org-gated channel — i know everyone here is already part of the organization.";
916
+ }
917
+ function groupChatParticipationSection(context) {
918
+ if (!context?.isGroupChat || !(0, channel_1.isRemoteChannel)(context.channel))
919
+ return "";
920
+ return `## group chat participation
921
+ group chats are conversations between people. i'm one participant, not the host.
922
+
923
+ i don't need to respond to everything. most reactions, tapbacks, and side
924
+ conversations between others aren't for me. i use observe to stay quiet
925
+ when the moment doesn't call for my voice — same as any person would.
926
+
927
+ when a reaction or emoji says it better than words, i can react instead of
928
+ typing a full reply. a thumbs-up is often the perfect response.
929
+
930
+ observe must be the sole tool call in the turn (same rule as settle).
931
+ when unsure whether to chime in, i lean toward silence rather than noise.`;
932
+ }
933
+ function feedbackSignalSection(context) {
934
+ if (!context || !(0, channel_1.isRemoteChannel)(context.channel))
935
+ return "";
936
+ if (context.isGroupChat) {
937
+ return `## feedback signals
938
+
939
+ when someone reacts specifically to something i said — that's different
940
+ from the background social signals in a group. a thumbs-down on my
941
+ message is direct feedback. a heart on something i shared is warmth
942
+ aimed at me. on teams, feedback arrives as thumbs-up or thumbs-down,
943
+ sometimes with a written comment.
944
+
945
+ i notice the difference: a reaction to someone else's message is group
946
+ texture (observe is natural). a reaction to my message is a social cue
947
+ worth a moment of attention — especially negative ones, which are an
948
+ invitation to adjust how i show up in this group.`;
949
+ }
950
+ return `## feedback signals
951
+
952
+ when my friend reacts to something i said — a tapback, a heart, a
953
+ thumbs-down — that's them telling me how it landed. on teams, this
954
+ arrives as thumbs-up or thumbs-down, sometimes with a written comment.
955
+ it's a social cue, the same as a nod or a wince in conversation.
956
+
957
+ i have observe for these moments. reactions are the one case where
958
+ silence in a direct conversation is natural — a thumbs-up doesn't
959
+ need words back.
960
+
961
+ when something didn't land — a thumbs-down, a negative reaction — that's
962
+ worth sitting with. i should course-correct: adjust my tone, my length,
963
+ my approach. the reaction tells me something about how this person wants
964
+ to be talked to.`;
965
+ }
966
+ function mixedTrustGroupSection(context) {
967
+ if (!context?.friend || !(0, channel_1.isRemoteChannel)(context.channel))
968
+ return "";
969
+ if (!context.isGroupChat)
970
+ return "";
971
+ 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.";
972
+ }
973
+ function formatElapsedBrief(ms) {
974
+ const minutes = Math.floor(ms / 60000);
975
+ if (minutes < 60)
976
+ return `${minutes}m ago`;
977
+ const hours = Math.floor(minutes / 60);
978
+ return `${hours}h ago`;
979
+ }
980
+ function rhythmStatusSection() {
981
+ try {
982
+ const health = (0, daemon_health_1.readHealth)((0, daemon_health_1.getDefaultHealthPath)());
983
+ if (!health)
984
+ return "";
985
+ const habitNames = Object.keys(health.habits);
986
+ if (habitNames.length === 0)
987
+ return "";
988
+ const nowMs = Date.now();
989
+ const parts = [];
990
+ for (const name of habitNames) {
991
+ const h = health.habits[name];
992
+ const lastFired = h.lastFired ? formatElapsedBrief(nowMs - new Date(h.lastFired).getTime()) : "never";
993
+ parts.push(`${name} last fired ${lastFired}`);
994
+ }
995
+ const degradedNote = health.degraded.length > 0
996
+ ? health.degraded.map((d) => `${d.component}: ${d.reason}`).join("; ") + "."
997
+ : "healthy.";
998
+ return `my rhythms: ${parts.join(". ")}. ${degradedNote}`;
999
+ /* v8 ignore start -- defensive: readHealth handles its own errors; this catch is a safety net for truly unexpected failures @preserve */
1000
+ }
1001
+ catch {
1002
+ return "";
1003
+ }
1004
+ /* v8 ignore stop */
1005
+ }
1006
+ /**
1007
+ * Returns true if the channel's resolved tool set includes coding tools
1008
+ * (edit_file, write_file, shell). Used to gate scrutiny prompts.
1009
+ */
1010
+ function channelHasCodingTools(channel, providerCapabilities) {
1011
+ const tools = (0, tools_1.getToolsForChannel)((0, channel_1.getChannelCapabilities)(channel), undefined, undefined, providerCapabilities);
1012
+ const codingToolNames = new Set(["edit_file", "write_file", "shell", "coding_spawn"]);
1013
+ return tools.some((t) => codingToolNames.has(t.function.name));
1014
+ }
312
1015
  async function buildSystem(channel = "cli", options, context) {
313
1016
  (0, runtime_1.emitNervesEvent)({
314
1017
  event: "mind.step_start",
@@ -316,29 +1019,82 @@ async function buildSystem(channel = "cli", options, context) {
316
1019
  message: "buildSystem started",
317
1020
  meta: { channel, has_context: Boolean(context), tool_choice_required: Boolean(options?.toolChoiceRequired) },
318
1021
  });
1022
+ // Backfill bundle-meta.json for existing agents that don't have one
1023
+ (0, bundle_manifest_1.backfillBundleMeta)((0, identity_1.getAgentRoot)());
319
1024
  const system = [
1025
+ // Group 1: who i am
1026
+ "# who i am",
320
1027
  soulSection(),
321
1028
  identitySection(),
322
1029
  loreSection(),
323
1030
  tacitKnowledgeSection(),
324
1031
  aspirationsSection(),
1032
+ // Group 2: my body & environment
1033
+ "# my body & environment",
1034
+ bodyMapSection((0, identity_1.getAgentName)()),
325
1035
  runtimeInfoSection(channel),
326
- providerSection(),
1036
+ rhythmStatusSection(),
1037
+ channelNatureSection((0, channel_1.getChannelCapabilities)(channel)),
1038
+ providerSection(channel),
327
1039
  dateSection(),
328
- toolsSection(channel, options),
1040
+ // Group 3: my tools & capabilities
1041
+ "# my tools & capabilities",
1042
+ toolsSection(channel, options, context),
1043
+ mcpToolsSection(options?.mcpManager),
1044
+ reasoningEffortSection(options),
329
1045
  skillsSection(),
330
- taskBoardSection(),
1046
+ toolContractsSection(options),
1047
+ memoryJudgementSection(),
1048
+ // Group 4: how i work
1049
+ "# how i work",
1050
+ workspaceDisciplineSection(),
1051
+ (0, scrutiny_1.preImplementationScrutinySection)(channelHasCodingTools(channel, options?.providerCapabilities)),
1052
+ toolRestrictionSection(context),
1053
+ loopOrientationSection(channel),
1054
+ // Group 5: my inner life (inner channel only)
1055
+ ...(channel === "inner" ? [
1056
+ "# my inner life",
1057
+ metacognitiveFramingSection(channel),
1058
+ journalSection((0, identity_1.getAgentRoot)()),
1059
+ ] : []),
1060
+ // Group 6: social context (non-local, non-inner channels)
1061
+ // Individual sections self-gate on isRemoteChannel/channel checks.
1062
+ // The group header appears when the channel is social-capable.
1063
+ ...(channel !== "cli" && channel !== "inner" ? [
1064
+ "# social context",
1065
+ trustContextSection(context),
1066
+ mixedTrustGroupSection(context),
1067
+ groupChatParticipationSection(context),
1068
+ feedbackSignalSection(context),
1069
+ ] : []),
1070
+ // Group 7: dynamic state for this turn
1071
+ "# dynamic state for this turn",
1072
+ startOfTurnPacketSection(options),
1073
+ liveWorldStateSection(options),
1074
+ pendingMessagesSection(options),
1075
+ activeWorkSection(options),
1076
+ centerOfGravitySteeringSection(channel, options, context),
1077
+ commitmentsSection(options),
1078
+ delegationHintSection(options),
1079
+ bridgeContextSection(options),
331
1080
  buildSessionSummary({
332
- sessionsDir: path.join(os.homedir(), ".agentstate", (0, identity_1.getAgentName)(), "sessions"),
1081
+ sessionsDir: path.join((0, identity_1.getAgentRoot)(), "state", "sessions"),
333
1082
  friendsDir: path.join((0, identity_1.getAgentRoot)(), "friends"),
334
1083
  agentName: (0, identity_1.getAgentName)(),
1084
+ currentSession: options?.activeWorkFrame?.currentSession
1085
+ ? { friendId: options.activeWorkFrame.currentSession.friendId, channel: options.activeWorkFrame.currentSession.channel, key: options.activeWorkFrame.currentSession.key }
1086
+ : undefined,
335
1087
  currentFriendId: context?.friend?.id,
336
1088
  currentChannel: channel,
337
- currentKey: "session",
1089
+ currentKey: options?.currentSessionKey ?? "session",
338
1090
  }),
339
- memoryFriendToolContractSection(),
340
- toolBehaviorSection(options),
341
- contextSection(context),
1091
+ // Group 8: friend context
1092
+ "# friend context",
1093
+ contextSection(context, options),
1094
+ familyCrossSessionTruthSection(context, options),
1095
+ // Group 9: task context
1096
+ "# task context",
1097
+ taskBoardSection(),
342
1098
  ]
343
1099
  .filter(Boolean)
344
1100
  .join("\n\n");