yzcode-cli 1.0.1 → 1.0.3

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 (117) hide show
  1. package/assistant/sessionHistory.ts +87 -0
  2. package/bootstrap/state.ts +1769 -0
  3. package/bridge/bridgeApi.ts +539 -0
  4. package/bridge/bridgeConfig.ts +48 -0
  5. package/bridge/bridgeDebug.ts +135 -0
  6. package/bridge/bridgeEnabled.ts +202 -0
  7. package/bridge/bridgeMain.ts +2999 -0
  8. package/bridge/bridgeMessaging.ts +461 -0
  9. package/bridge/bridgePermissionCallbacks.ts +43 -0
  10. package/bridge/bridgePointer.ts +210 -0
  11. package/bridge/bridgeStatusUtil.ts +163 -0
  12. package/bridge/bridgeUI.ts +530 -0
  13. package/bridge/capacityWake.ts +56 -0
  14. package/bridge/codeSessionApi.ts +168 -0
  15. package/bridge/createSession.ts +384 -0
  16. package/bridge/debugUtils.ts +141 -0
  17. package/bridge/envLessBridgeConfig.ts +165 -0
  18. package/bridge/flushGate.ts +71 -0
  19. package/bridge/inboundAttachments.ts +175 -0
  20. package/bridge/inboundMessages.ts +80 -0
  21. package/bridge/initReplBridge.ts +569 -0
  22. package/bridge/jwtUtils.ts +256 -0
  23. package/bridge/pollConfig.ts +110 -0
  24. package/bridge/pollConfigDefaults.ts +82 -0
  25. package/bridge/remoteBridgeCore.ts +1008 -0
  26. package/bridge/replBridge.ts +2406 -0
  27. package/bridge/replBridgeHandle.ts +36 -0
  28. package/bridge/replBridgeTransport.ts +370 -0
  29. package/bridge/sessionIdCompat.ts +57 -0
  30. package/bridge/sessionRunner.ts +550 -0
  31. package/bridge/trustedDevice.ts +210 -0
  32. package/bridge/types.ts +262 -0
  33. package/bridge/workSecret.ts +127 -0
  34. package/buddy/CompanionSprite.tsx +371 -0
  35. package/buddy/companion.ts +133 -0
  36. package/buddy/prompt.ts +36 -0
  37. package/buddy/sprites.ts +514 -0
  38. package/buddy/types.ts +148 -0
  39. package/buddy/useBuddyNotification.tsx +98 -0
  40. package/coordinator/coordinatorMode.ts +369 -0
  41. package/memdir/findRelevantMemories.ts +141 -0
  42. package/memdir/memdir.ts +507 -0
  43. package/memdir/memoryAge.ts +53 -0
  44. package/memdir/memoryScan.ts +94 -0
  45. package/memdir/memoryTypes.ts +271 -0
  46. package/memdir/paths.ts +278 -0
  47. package/memdir/teamMemPaths.ts +292 -0
  48. package/memdir/teamMemPrompts.ts +100 -0
  49. package/migrations/migrateAutoUpdatesToSettings.ts +61 -0
  50. package/migrations/migrateBypassPermissionsAcceptedToSettings.ts +40 -0
  51. package/migrations/migrateEnableAllProjectMcpServersToSettings.ts +118 -0
  52. package/migrations/migrateFennecToOpus.ts +45 -0
  53. package/migrations/migrateLegacyOpusToCurrent.ts +57 -0
  54. package/migrations/migrateOpusToOpus1m.ts +43 -0
  55. package/migrations/migrateReplBridgeEnabledToRemoteControlAtStartup.ts +22 -0
  56. package/migrations/migrateSonnet1mToSonnet45.ts +48 -0
  57. package/migrations/migrateSonnet45ToSonnet46.ts +67 -0
  58. package/migrations/resetAutoModeOptInForDefaultOffer.ts +51 -0
  59. package/migrations/resetProToOpusDefault.ts +51 -0
  60. package/native-ts/color-diff/index.ts +999 -0
  61. package/native-ts/file-index/index.ts +370 -0
  62. package/native-ts/yoga-layout/enums.ts +134 -0
  63. package/native-ts/yoga-layout/index.ts +2578 -0
  64. package/outputStyles/loadOutputStylesDir.ts +98 -0
  65. package/package.json +22 -5
  66. package/plugins/builtinPlugins.ts +159 -0
  67. package/plugins/bundled/index.ts +23 -0
  68. package/schemas/hooks.ts +222 -0
  69. package/screens/Doctor.tsx +575 -0
  70. package/screens/REPL.tsx +5006 -0
  71. package/screens/ResumeConversation.tsx +399 -0
  72. package/server/createDirectConnectSession.ts +88 -0
  73. package/server/directConnectManager.ts +213 -0
  74. package/server/types.ts +57 -0
  75. package/skills/bundled/batch.ts +124 -0
  76. package/skills/bundled/claudeApi.ts +196 -0
  77. package/skills/bundled/claudeApiContent.ts +75 -0
  78. package/skills/bundled/claudeInChrome.ts +34 -0
  79. package/skills/bundled/debug.ts +103 -0
  80. package/skills/bundled/index.ts +79 -0
  81. package/skills/bundled/keybindings.ts +339 -0
  82. package/skills/bundled/loop.ts +92 -0
  83. package/skills/bundled/loremIpsum.ts +282 -0
  84. package/skills/bundled/remember.ts +82 -0
  85. package/skills/bundled/scheduleRemoteAgents.ts +447 -0
  86. package/skills/bundled/simplify.ts +69 -0
  87. package/skills/bundled/skillify.ts +197 -0
  88. package/skills/bundled/stuck.ts +79 -0
  89. package/skills/bundled/updateConfig.ts +475 -0
  90. package/skills/bundled/verify/SKILL.md +3 -0
  91. package/skills/bundled/verify/examples/cli.md +3 -0
  92. package/skills/bundled/verify/examples/server.md +3 -0
  93. package/skills/bundled/verify.ts +30 -0
  94. package/skills/bundled/verifyContent.ts +13 -0
  95. package/skills/bundledSkills.ts +220 -0
  96. package/skills/loadSkillsDir.ts +1086 -0
  97. package/skills/mcpSkillBuilders.ts +44 -0
  98. package/tasks/DreamTask/DreamTask.ts +157 -0
  99. package/tasks/InProcessTeammateTask/InProcessTeammateTask.tsx +126 -0
  100. package/tasks/InProcessTeammateTask/types.ts +121 -0
  101. package/tasks/LocalAgentTask/LocalAgentTask.tsx +683 -0
  102. package/tasks/LocalMainSessionTask.ts +479 -0
  103. package/tasks/LocalShellTask/LocalShellTask.tsx +523 -0
  104. package/tasks/LocalShellTask/guards.ts +41 -0
  105. package/tasks/LocalShellTask/killShellTasks.ts +76 -0
  106. package/tasks/RemoteAgentTask/RemoteAgentTask.tsx +856 -0
  107. package/tasks/pillLabel.ts +82 -0
  108. package/tasks/stopTask.ts +100 -0
  109. package/tasks/types.ts +46 -0
  110. package/upstreamproxy/relay.ts +455 -0
  111. package/upstreamproxy/upstreamproxy.ts +285 -0
  112. package/vim/motions.ts +82 -0
  113. package/vim/operators.ts +556 -0
  114. package/vim/textObjects.ts +186 -0
  115. package/vim/transitions.ts +490 -0
  116. package/vim/types.ts +199 -0
  117. package/voice/voiceModeEnabled.ts +54 -0
@@ -0,0 +1,98 @@
1
+ import { c as _c } from "react/compiler-runtime";
2
+ import { feature } from 'bun:bundle';
3
+ import React, { useEffect } from 'react';
4
+ import { useNotifications } from '../context/notifications.js';
5
+ import { Text } from '../ink.js';
6
+ import { getGlobalConfig } from '../utils/config.js';
7
+ import { getRainbowColor } from '../utils/thinking.js';
8
+
9
+ // Local date, not UTC — 24h rolling wave across timezones. Sustained Twitter
10
+ // buzz instead of a single UTC-midnight spike, gentler on soul-gen load.
11
+ // Teaser window: April 1-7, 2026 only. Command stays live forever after.
12
+ export function isBuddyTeaserWindow(): boolean {
13
+ if ("external" === 'ant') return true;
14
+ const d = new Date();
15
+ return d.getFullYear() === 2026 && d.getMonth() === 3 && d.getDate() <= 7;
16
+ }
17
+ export function isBuddyLive(): boolean {
18
+ if ("external" === 'ant') return true;
19
+ const d = new Date();
20
+ return d.getFullYear() > 2026 || d.getFullYear() === 2026 && d.getMonth() >= 3;
21
+ }
22
+ function RainbowText(t0) {
23
+ const $ = _c(2);
24
+ const {
25
+ text
26
+ } = t0;
27
+ let t1;
28
+ if ($[0] !== text) {
29
+ t1 = <>{[...text].map(_temp)}</>;
30
+ $[0] = text;
31
+ $[1] = t1;
32
+ } else {
33
+ t1 = $[1];
34
+ }
35
+ return t1;
36
+ }
37
+
38
+ // Rainbow /buddy teaser shown on startup when no companion hatched yet.
39
+ // Idle presence and reactions are handled by CompanionSprite directly.
40
+ function _temp(ch, i) {
41
+ return <Text key={i} color={getRainbowColor(i)}>{ch}</Text>;
42
+ }
43
+ export function useBuddyNotification() {
44
+ const $ = _c(4);
45
+ const {
46
+ addNotification,
47
+ removeNotification
48
+ } = useNotifications();
49
+ let t0;
50
+ let t1;
51
+ if ($[0] !== addNotification || $[1] !== removeNotification) {
52
+ t0 = () => {
53
+ if (!feature("BUDDY")) {
54
+ return;
55
+ }
56
+ const config = getGlobalConfig();
57
+ if (config.companion || !isBuddyTeaserWindow()) {
58
+ return;
59
+ }
60
+ addNotification({
61
+ key: "buddy-teaser",
62
+ jsx: <RainbowText text="/buddy" />,
63
+ priority: "immediate",
64
+ timeoutMs: 15000
65
+ });
66
+ return () => removeNotification("buddy-teaser");
67
+ };
68
+ t1 = [addNotification, removeNotification];
69
+ $[0] = addNotification;
70
+ $[1] = removeNotification;
71
+ $[2] = t0;
72
+ $[3] = t1;
73
+ } else {
74
+ t0 = $[2];
75
+ t1 = $[3];
76
+ }
77
+ useEffect(t0, t1);
78
+ }
79
+ export function findBuddyTriggerPositions(text: string): Array<{
80
+ start: number;
81
+ end: number;
82
+ }> {
83
+ if (!feature('BUDDY')) return [];
84
+ const triggers: Array<{
85
+ start: number;
86
+ end: number;
87
+ }> = [];
88
+ const re = /\/buddy\b/g;
89
+ let m: RegExpExecArray | null;
90
+ while ((m = re.exec(text)) !== null) {
91
+ triggers.push({
92
+ start: m.index,
93
+ end: m.index + m[0].length
94
+ });
95
+ }
96
+ return triggers;
97
+ }
98
+ //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmZWF0dXJlIiwiUmVhY3QiLCJ1c2VFZmZlY3QiLCJ1c2VOb3RpZmljYXRpb25zIiwiVGV4dCIsImdldEdsb2JhbENvbmZpZyIsImdldFJhaW5ib3dDb2xvciIsImlzQnVkZHlUZWFzZXJXaW5kb3ciLCJkIiwiRGF0ZSIsImdldEZ1bGxZZWFyIiwiZ2V0TW9udGgiLCJnZXREYXRlIiwiaXNCdWRkeUxpdmUiLCJSYWluYm93VGV4dCIsInQwIiwiJCIsIl9jIiwidGV4dCIsInQxIiwibWFwIiwiX3RlbXAiLCJjaCIsImkiLCJ1c2VCdWRkeU5vdGlmaWNhdGlvbiIsImFkZE5vdGlmaWNhdGlvbiIsInJlbW92ZU5vdGlmaWNhdGlvbiIsImNvbmZpZyIsImNvbXBhbmlvbiIsImtleSIsImpzeCIsInByaW9yaXR5IiwidGltZW91dE1zIiwiZm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xHQUFHLElBQUk7RUFDN0IsT0FBTyxDQUFDRCxDQUFDLEdBQUdELEVBQUUsQ0FBQ0csSUFBSSxDQUFDdkIsSUFBSSxDQUFDLE1BQU0sSUFBSSxFQUFFO0lBQ25DbUIsUUFBUSxDQUFDSyxJQUFJLENBQUM7TUFBRVAsS0FBSyxFQUFFSSxDQUFDLENBQUNJLEtBQUs7TUFBRVAsR0FBRyxFQUFFRyxDQUFDLENBQUNJLEtBQUssR0FBR0osQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDSztJQUFPLENBQUMsQ0FBQztFQUMvRDtFQUNBLE9BQU9QLFFBQVE7QUFDakIiLCJpZ25vcmVMaXN0IjpbXX0=
@@ -0,0 +1,369 @@
1
+ import { feature } from 'bun:bundle'
2
+ import { ASYNC_AGENT_ALLOWED_TOOLS } from '../constants/tools.js'
3
+ import { checkStatsigFeatureGate_CACHED_MAY_BE_STALE } from '../services/analytics/growthbook.js'
4
+ import {
5
+ type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
6
+ logEvent,
7
+ } from '../services/analytics/index.js'
8
+ import { AGENT_TOOL_NAME } from '../tools/AgentTool/constants.js'
9
+ import { BASH_TOOL_NAME } from '../tools/BashTool/toolName.js'
10
+ import { FILE_EDIT_TOOL_NAME } from '../tools/FileEditTool/constants.js'
11
+ import { FILE_READ_TOOL_NAME } from '../tools/FileReadTool/prompt.js'
12
+ import { SEND_MESSAGE_TOOL_NAME } from '../tools/SendMessageTool/constants.js'
13
+ import { SYNTHETIC_OUTPUT_TOOL_NAME } from '../tools/SyntheticOutputTool/SyntheticOutputTool.js'
14
+ import { TASK_STOP_TOOL_NAME } from '../tools/TaskStopTool/prompt.js'
15
+ import { TEAM_CREATE_TOOL_NAME } from '../tools/TeamCreateTool/constants.js'
16
+ import { TEAM_DELETE_TOOL_NAME } from '../tools/TeamDeleteTool/constants.js'
17
+ import { isEnvTruthy } from '../utils/envUtils.js'
18
+
19
+ // Checks the same gate as isScratchpadEnabled() in
20
+ // utils/permissions/filesystem.ts. Duplicated here because importing
21
+ // filesystem.ts creates a circular dependency (filesystem -> permissions
22
+ // -> ... -> coordinatorMode). The actual scratchpad path is passed in via
23
+ // getCoordinatorUserContext's scratchpadDir parameter (dependency injection
24
+ // from QueryEngine.ts, which lives higher in the dep graph).
25
+ function isScratchpadGateEnabled(): boolean {
26
+ return checkStatsigFeatureGate_CACHED_MAY_BE_STALE('tengu_scratch')
27
+ }
28
+
29
+ const INTERNAL_WORKER_TOOLS = new Set([
30
+ TEAM_CREATE_TOOL_NAME,
31
+ TEAM_DELETE_TOOL_NAME,
32
+ SEND_MESSAGE_TOOL_NAME,
33
+ SYNTHETIC_OUTPUT_TOOL_NAME,
34
+ ])
35
+
36
+ export function isCoordinatorMode(): boolean {
37
+ if (feature('COORDINATOR_MODE')) {
38
+ return isEnvTruthy(process.env.CLAUDE_CODE_COORDINATOR_MODE)
39
+ }
40
+ return false
41
+ }
42
+
43
+ /**
44
+ * Checks if the current coordinator mode matches the session's stored mode.
45
+ * If mismatched, flips the environment variable so isCoordinatorMode() returns
46
+ * the correct value for the resumed session. Returns a warning message if
47
+ * the mode was switched, or undefined if no switch was needed.
48
+ */
49
+ export function matchSessionMode(
50
+ sessionMode: 'coordinator' | 'normal' | undefined,
51
+ ): string | undefined {
52
+ // No stored mode (old session before mode tracking) — do nothing
53
+ if (!sessionMode) {
54
+ return undefined
55
+ }
56
+
57
+ const currentIsCoordinator = isCoordinatorMode()
58
+ const sessionIsCoordinator = sessionMode === 'coordinator'
59
+
60
+ if (currentIsCoordinator === sessionIsCoordinator) {
61
+ return undefined
62
+ }
63
+
64
+ // Flip the env var — isCoordinatorMode() reads it live, no caching
65
+ if (sessionIsCoordinator) {
66
+ process.env.CLAUDE_CODE_COORDINATOR_MODE = '1'
67
+ } else {
68
+ delete process.env.CLAUDE_CODE_COORDINATOR_MODE
69
+ }
70
+
71
+ logEvent('tengu_coordinator_mode_switched', {
72
+ to: sessionMode as unknown as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
73
+ })
74
+
75
+ return sessionIsCoordinator
76
+ ? 'Entered coordinator mode to match resumed session.'
77
+ : 'Exited coordinator mode to match resumed session.'
78
+ }
79
+
80
+ export function getCoordinatorUserContext(
81
+ mcpClients: ReadonlyArray<{ name: string }>,
82
+ scratchpadDir?: string,
83
+ ): { [k: string]: string } {
84
+ if (!isCoordinatorMode()) {
85
+ return {}
86
+ }
87
+
88
+ const workerTools = isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)
89
+ ? [BASH_TOOL_NAME, FILE_READ_TOOL_NAME, FILE_EDIT_TOOL_NAME]
90
+ .sort()
91
+ .join(', ')
92
+ : Array.from(ASYNC_AGENT_ALLOWED_TOOLS)
93
+ .filter(name => !INTERNAL_WORKER_TOOLS.has(name))
94
+ .sort()
95
+ .join(', ')
96
+
97
+ let content = `Workers spawned via the ${AGENT_TOOL_NAME} tool have access to these tools: ${workerTools}`
98
+
99
+ if (mcpClients.length > 0) {
100
+ const serverNames = mcpClients.map(c => c.name).join(', ')
101
+ content += `\n\nWorkers also have access to MCP tools from connected MCP servers: ${serverNames}`
102
+ }
103
+
104
+ if (scratchpadDir && isScratchpadGateEnabled()) {
105
+ content += `\n\nScratchpad directory: ${scratchpadDir}\nWorkers can read and write here without permission prompts. Use this for durable cross-worker knowledge — structure files however fits the work.`
106
+ }
107
+
108
+ return { workerToolsContext: content }
109
+ }
110
+
111
+ export function getCoordinatorSystemPrompt(): string {
112
+ const workerCapabilities = isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)
113
+ ? 'Workers have access to Bash, Read, and Edit tools, plus MCP tools from configured MCP servers.'
114
+ : 'Workers have access to standard tools, MCP tools from configured MCP servers, and project skills via the Skill tool. Delegate skill invocations (e.g. /commit, /verify) to workers.'
115
+
116
+ return `You are Claude Code, an AI assistant that orchestrates software engineering tasks across multiple workers.
117
+
118
+ ## 1. Your Role
119
+
120
+ You are a **coordinator**. Your job is to:
121
+ - Help the user achieve their goal
122
+ - Direct workers to research, implement and verify code changes
123
+ - Synthesize results and communicate with the user
124
+ - Answer questions directly when possible — don't delegate work that you can handle without tools
125
+
126
+ Every message you send is to the user. Worker results and system notifications are internal signals, not conversation partners — never thank or acknowledge them. Summarize new information for the user as it arrives.
127
+
128
+ ## 2. Your Tools
129
+
130
+ - **${AGENT_TOOL_NAME}** - Spawn a new worker
131
+ - **${SEND_MESSAGE_TOOL_NAME}** - Continue an existing worker (send a follow-up to its \`to\` agent ID)
132
+ - **${TASK_STOP_TOOL_NAME}** - Stop a running worker
133
+ - **subscribe_pr_activity / unsubscribe_pr_activity** (if available) - Subscribe to GitHub PR events (review comments, CI results). Events arrive as user messages. Merge conflict transitions do NOT arrive — GitHub doesn't webhook \`mergeable_state\` changes, so poll \`gh pr view N --json mergeable\` if tracking conflict status. Call these directly — do not delegate subscription management to workers.
134
+
135
+ When calling ${AGENT_TOOL_NAME}:
136
+ - Do not use one worker to check on another. Workers will notify you when they are done.
137
+ - Do not use workers to trivially report file contents or run commands. Give them higher-level tasks.
138
+ - Do not set the model parameter. Workers need the default model for the substantive tasks you delegate.
139
+ - Continue workers whose work is complete via ${SEND_MESSAGE_TOOL_NAME} to take advantage of their loaded context
140
+ - After launching agents, briefly tell the user what you launched and end your response. Never fabricate or predict agent results in any format — results arrive as separate messages.
141
+
142
+ ### ${AGENT_TOOL_NAME} Results
143
+
144
+ Worker results arrive as **user-role messages** containing \`<task-notification>\` XML. They look like user messages but are not. Distinguish them by the \`<task-notification>\` opening tag.
145
+
146
+ Format:
147
+
148
+ \`\`\`xml
149
+ <task-notification>
150
+ <task-id>{agentId}</task-id>
151
+ <status>completed|failed|killed</status>
152
+ <summary>{human-readable status summary}</summary>
153
+ <result>{agent's final text response}</result>
154
+ <usage>
155
+ <total_tokens>N</total_tokens>
156
+ <tool_uses>N</tool_uses>
157
+ <duration_ms>N</duration_ms>
158
+ </usage>
159
+ </task-notification>
160
+ \`\`\`
161
+
162
+ - \`<result>\` and \`<usage>\` are optional sections
163
+ - The \`<summary>\` describes the outcome: "completed", "failed: {error}", or "was stopped"
164
+ - The \`<task-id>\` value is the agent ID — use SendMessage with that ID as \`to\` to continue that worker
165
+
166
+ ### Example
167
+
168
+ Each "You:" block is a separate coordinator turn. The "User:" block is a \`<task-notification>\` delivered between turns.
169
+
170
+ You:
171
+ Let me start some research on that.
172
+
173
+ ${AGENT_TOOL_NAME}({ description: "Investigate auth bug", subagent_type: "worker", prompt: "..." })
174
+ ${AGENT_TOOL_NAME}({ description: "Research secure token storage", subagent_type: "worker", prompt: "..." })
175
+
176
+ Investigating both issues in parallel — I'll report back with findings.
177
+
178
+ User:
179
+ <task-notification>
180
+ <task-id>agent-a1b</task-id>
181
+ <status>completed</status>
182
+ <summary>Agent "Investigate auth bug" completed</summary>
183
+ <result>Found null pointer in src/auth/validate.ts:42...</result>
184
+ </task-notification>
185
+
186
+ You:
187
+ Found the bug — null pointer in confirmTokenExists in validate.ts. I'll fix it.
188
+ Still waiting on the token storage research.
189
+
190
+ ${SEND_MESSAGE_TOOL_NAME}({ to: "agent-a1b", message: "Fix the null pointer in src/auth/validate.ts:42..." })
191
+
192
+ ## 3. Workers
193
+
194
+ When calling ${AGENT_TOOL_NAME}, use subagent_type \`worker\`. Workers execute tasks autonomously — especially research, implementation, or verification.
195
+
196
+ ${workerCapabilities}
197
+
198
+ ## 4. Task Workflow
199
+
200
+ Most tasks can be broken down into the following phases:
201
+
202
+ ### Phases
203
+
204
+ | Phase | Who | Purpose |
205
+ |-------|-----|---------|
206
+ | Research | Workers (parallel) | Investigate codebase, find files, understand problem |
207
+ | Synthesis | **You** (coordinator) | Read findings, understand the problem, craft implementation specs (see Section 5) |
208
+ | Implementation | Workers | Make targeted changes per spec, commit |
209
+ | Verification | Workers | Test changes work |
210
+
211
+ ### Concurrency
212
+
213
+ **Parallelism is your superpower. Workers are async. Launch independent workers concurrently whenever possible — don't serialize work that can run simultaneously and look for opportunities to fan out. When doing research, cover multiple angles. To launch workers in parallel, make multiple tool calls in a single message.**
214
+
215
+ Manage concurrency:
216
+ - **Read-only tasks** (research) — run in parallel freely
217
+ - **Write-heavy tasks** (implementation) — one at a time per set of files
218
+ - **Verification** can sometimes run alongside implementation on different file areas
219
+
220
+ ### What Real Verification Looks Like
221
+
222
+ Verification means **proving the code works**, not confirming it exists. A verifier that rubber-stamps weak work undermines everything.
223
+
224
+ - Run tests **with the feature enabled** — not just "tests pass"
225
+ - Run typechecks and **investigate errors** — don't dismiss as "unrelated"
226
+ - Be skeptical — if something looks off, dig in
227
+ - **Test independently** — prove the change works, don't rubber-stamp
228
+
229
+ ### Handling Worker Failures
230
+
231
+ When a worker reports failure (tests failed, build errors, file not found):
232
+ - Continue the same worker with ${SEND_MESSAGE_TOOL_NAME} — it has the full error context
233
+ - If a correction attempt fails, try a different approach or report to the user
234
+
235
+ ### Stopping Workers
236
+
237
+ Use ${TASK_STOP_TOOL_NAME} to stop a worker you sent in the wrong direction — for example, when you realize mid-flight that the approach is wrong, or the user changes requirements after you launched the worker. Pass the \`task_id\` from the ${AGENT_TOOL_NAME} tool's launch result. Stopped workers can be continued with ${SEND_MESSAGE_TOOL_NAME}.
238
+
239
+ \`\`\`
240
+ // Launched a worker to refactor auth to use JWT
241
+ ${AGENT_TOOL_NAME}({ description: "Refactor auth to JWT", subagent_type: "worker", prompt: "Replace session-based auth with JWT..." })
242
+ // ... returns task_id: "agent-x7q" ...
243
+
244
+ // User clarifies: "Actually, keep sessions — just fix the null pointer"
245
+ ${TASK_STOP_TOOL_NAME}({ task_id: "agent-x7q" })
246
+
247
+ // Continue with corrected instructions
248
+ ${SEND_MESSAGE_TOOL_NAME}({ to: "agent-x7q", message: "Stop the JWT refactor. Instead, fix the null pointer in src/auth/validate.ts:42..." })
249
+ \`\`\`
250
+
251
+ ## 5. Writing Worker Prompts
252
+
253
+ **Workers can't see your conversation.** Every prompt must be self-contained with everything the worker needs. After research completes, you always do two things: (1) synthesize findings into a specific prompt, and (2) choose whether to continue that worker via ${SEND_MESSAGE_TOOL_NAME} or spawn a fresh one.
254
+
255
+ ### Always synthesize — your most important job
256
+
257
+ When workers report research findings, **you must understand them before directing follow-up work**. Read the findings. Identify the approach. Then write a prompt that proves you understood by including specific file paths, line numbers, and exactly what to change.
258
+
259
+ Never write "based on your findings" or "based on the research." These phrases delegate understanding to the worker instead of doing it yourself. You never hand off understanding to another worker.
260
+
261
+ \`\`\`
262
+ // Anti-pattern — lazy delegation (bad whether continuing or spawning)
263
+ ${AGENT_TOOL_NAME}({ prompt: "Based on your findings, fix the auth bug", ... })
264
+ ${AGENT_TOOL_NAME}({ prompt: "The worker found an issue in the auth module. Please fix it.", ... })
265
+
266
+ // Good — synthesized spec (works with either continue or spawn)
267
+ ${AGENT_TOOL_NAME}({ prompt: "Fix the null pointer in src/auth/validate.ts:42. The user field on Session (src/auth/types.ts:15) is undefined when sessions expire but the token remains cached. Add a null check before user.id access — if null, return 401 with 'Session expired'. Commit and report the hash.", ... })
268
+ \`\`\`
269
+
270
+ A well-synthesized spec gives the worker everything it needs in a few sentences. It does not matter whether the worker is fresh or continued — the spec quality determines the outcome.
271
+
272
+ ### Add a purpose statement
273
+
274
+ Include a brief purpose so workers can calibrate depth and emphasis:
275
+
276
+ - "This research will inform a PR description — focus on user-facing changes."
277
+ - "I need this to plan an implementation — report file paths, line numbers, and type signatures."
278
+ - "This is a quick check before we merge — just verify the happy path."
279
+
280
+ ### Choose continue vs. spawn by context overlap
281
+
282
+ After synthesizing, decide whether the worker's existing context helps or hurts:
283
+
284
+ | Situation | Mechanism | Why |
285
+ |-----------|-----------|-----|
286
+ | Research explored exactly the files that need editing | **Continue** (${SEND_MESSAGE_TOOL_NAME}) with synthesized spec | Worker already has the files in context AND now gets a clear plan |
287
+ | Research was broad but implementation is narrow | **Spawn fresh** (${AGENT_TOOL_NAME}) with synthesized spec | Avoid dragging along exploration noise; focused context is cleaner |
288
+ | Correcting a failure or extending recent work | **Continue** | Worker has the error context and knows what it just tried |
289
+ | Verifying code a different worker just wrote | **Spawn fresh** | Verifier should see the code with fresh eyes, not carry implementation assumptions |
290
+ | First implementation attempt used the wrong approach entirely | **Spawn fresh** | Wrong-approach context pollutes the retry; clean slate avoids anchoring on the failed path |
291
+ | Completely unrelated task | **Spawn fresh** | No useful context to reuse |
292
+
293
+ There is no universal default. Think about how much of the worker's context overlaps with the next task. High overlap -> continue. Low overlap -> spawn fresh.
294
+
295
+ ### Continue mechanics
296
+
297
+ When continuing a worker with ${SEND_MESSAGE_TOOL_NAME}, it has full context from its previous run:
298
+ \`\`\`
299
+ // Continuation — worker finished research, now give it a synthesized implementation spec
300
+ ${SEND_MESSAGE_TOOL_NAME}({ to: "xyz-456", message: "Fix the null pointer in src/auth/validate.ts:42. The user field is undefined when Session.expired is true but the token is still cached. Add a null check before accessing user.id — if null, return 401 with 'Session expired'. Commit and report the hash." })
301
+ \`\`\`
302
+
303
+ \`\`\`
304
+ // Correction — worker just reported test failures from its own change, keep it brief
305
+ ${SEND_MESSAGE_TOOL_NAME}({ to: "xyz-456", message: "Two tests still failing at lines 58 and 72 — update the assertions to match the new error message." })
306
+ \`\`\`
307
+
308
+ ### Prompt tips
309
+
310
+ **Good examples:**
311
+
312
+ 1. Implementation: "Fix the null pointer in src/auth/validate.ts:42. The user field can be undefined when the session expires. Add a null check and return early with an appropriate error. Commit and report the hash."
313
+
314
+ 2. Precise git operation: "Create a new branch from main called 'fix/session-expiry'. Cherry-pick only commit abc123 onto it. Push and create a draft PR targeting main. Add anthropics/claude-code as reviewer. Report the PR URL."
315
+
316
+ 3. Correction (continued worker, short): "The tests failed on the null check you added — validate.test.ts:58 expects 'Invalid session' but you changed it to 'Session expired'. Fix the assertion. Commit and report the hash."
317
+
318
+ **Bad examples:**
319
+
320
+ 1. "Fix the bug we discussed" — no context, workers can't see your conversation
321
+ 2. "Based on your findings, implement the fix" — lazy delegation; synthesize the findings yourself
322
+ 3. "Create a PR for the recent changes" — ambiguous scope: which changes? which branch? draft?
323
+ 4. "Something went wrong with the tests, can you look?" — no error message, no file path, no direction
324
+
325
+ Additional tips:
326
+ - Include file paths, line numbers, error messages — workers start fresh and need complete context
327
+ - State what "done" looks like
328
+ - For implementation: "Run relevant tests and typecheck, then commit your changes and report the hash" — workers self-verify before reporting done. This is the first layer of QA; a separate verification worker is the second layer.
329
+ - For research: "Report findings — do not modify files"
330
+ - Be precise about git operations — specify branch names, commit hashes, draft vs ready, reviewers
331
+ - When continuing for corrections: reference what the worker did ("the null check you added") not what you discussed with the user
332
+ - For implementation: "Fix the root cause, not the symptom" — guide workers toward durable fixes
333
+ - For verification: "Prove the code works, don't just confirm it exists"
334
+ - For verification: "Try edge cases and error paths — don't just re-run what the implementation worker ran"
335
+ - For verification: "Investigate failures — don't dismiss as unrelated without evidence"
336
+
337
+ ## 6. Example Session
338
+
339
+ User: "There's a null pointer in the auth module. Can you fix it?"
340
+
341
+ You:
342
+ Let me investigate first.
343
+
344
+ ${AGENT_TOOL_NAME}({ description: "Investigate auth bug", subagent_type: "worker", prompt: "Investigate the auth module in src/auth/. Find where null pointer exceptions could occur around session handling and token validation... Report specific file paths, line numbers, and types involved. Do not modify files." })
345
+ ${AGENT_TOOL_NAME}({ description: "Research auth tests", subagent_type: "worker", prompt: "Find all test files related to src/auth/. Report the test structure, what's covered, and any gaps around session expiry... Do not modify files." })
346
+
347
+ Investigating from two angles — I'll report back with findings.
348
+
349
+ User:
350
+ <task-notification>
351
+ <task-id>agent-a1b</task-id>
352
+ <status>completed</status>
353
+ <summary>Agent "Investigate auth bug" completed</summary>
354
+ <result>Found null pointer in src/auth/validate.ts:42. The user field on Session is undefined when the session expires but ...</result>
355
+ </task-notification>
356
+
357
+ You:
358
+ Found the bug — null pointer in validate.ts:42.
359
+
360
+ ${SEND_MESSAGE_TOOL_NAME}({ to: "agent-a1b", message: "Fix the null pointer in src/auth/validate.ts:42. Add a null check before accessing user.id — if null, ... Commit and report the hash." })
361
+
362
+ Fix is in progress.
363
+
364
+ User:
365
+ How's it going?
366
+
367
+ You:
368
+ Fix for the new test is in progress. Still waiting to hear back about the test suite.`
369
+ }
@@ -0,0 +1,141 @@
1
+ import { feature } from 'bun:bundle'
2
+ import { logForDebugging } from '../utils/debug.js'
3
+ import { errorMessage } from '../utils/errors.js'
4
+ import { getDefaultSonnetModel } from '../utils/model/model.js'
5
+ import { sideQuery } from '../utils/sideQuery.js'
6
+ import { jsonParse } from '../utils/slowOperations.js'
7
+ import {
8
+ formatMemoryManifest,
9
+ type MemoryHeader,
10
+ scanMemoryFiles,
11
+ } from './memoryScan.js'
12
+
13
+ export type RelevantMemory = {
14
+ path: string
15
+ mtimeMs: number
16
+ }
17
+
18
+ const SELECT_MEMORIES_SYSTEM_PROMPT = `You are selecting memories that will be useful to Claude Code as it processes a user's query. You will be given the user's query and a list of available memory files with their filenames and descriptions.
19
+
20
+ Return a list of filenames for the memories that will clearly be useful to Claude Code as it processes the user's query (up to 5). Only include memories that you are certain will be helpful based on their name and description.
21
+ - If you are unsure if a memory will be useful in processing the user's query, then do not include it in your list. Be selective and discerning.
22
+ - If there are no memories in the list that would clearly be useful, feel free to return an empty list.
23
+ - If a list of recently-used tools is provided, do not select memories that are usage reference or API documentation for those tools (Claude Code is already exercising them). DO still select memories containing warnings, gotchas, or known issues about those tools — active use is exactly when those matter.
24
+ `
25
+
26
+ /**
27
+ * Find memory files relevant to a query by scanning memory file headers
28
+ * and asking Sonnet to select the most relevant ones.
29
+ *
30
+ * Returns absolute file paths + mtime of the most relevant memories
31
+ * (up to 5). Excludes MEMORY.md (already loaded in system prompt).
32
+ * mtime is threaded through so callers can surface freshness to the
33
+ * main model without a second stat.
34
+ *
35
+ * `alreadySurfaced` filters paths shown in prior turns before the
36
+ * Sonnet call, so the selector spends its 5-slot budget on fresh
37
+ * candidates instead of re-picking files the caller will discard.
38
+ */
39
+ export async function findRelevantMemories(
40
+ query: string,
41
+ memoryDir: string,
42
+ signal: AbortSignal,
43
+ recentTools: readonly string[] = [],
44
+ alreadySurfaced: ReadonlySet<string> = new Set(),
45
+ ): Promise<RelevantMemory[]> {
46
+ const memories = (await scanMemoryFiles(memoryDir, signal)).filter(
47
+ m => !alreadySurfaced.has(m.filePath),
48
+ )
49
+ if (memories.length === 0) {
50
+ return []
51
+ }
52
+
53
+ const selectedFilenames = await selectRelevantMemories(
54
+ query,
55
+ memories,
56
+ signal,
57
+ recentTools,
58
+ )
59
+ const byFilename = new Map(memories.map(m => [m.filename, m]))
60
+ const selected = selectedFilenames
61
+ .map(filename => byFilename.get(filename))
62
+ .filter((m): m is MemoryHeader => m !== undefined)
63
+
64
+ // Fires even on empty selection: selection-rate needs the denominator,
65
+ // and -1 ages distinguish "ran, picked nothing" from "never ran".
66
+ if (feature('MEMORY_SHAPE_TELEMETRY')) {
67
+ /* eslint-disable @typescript-eslint/no-require-imports */
68
+ const { logMemoryRecallShape } =
69
+ require('./memoryShapeTelemetry.js') as typeof import('./memoryShapeTelemetry.js')
70
+ /* eslint-enable @typescript-eslint/no-require-imports */
71
+ logMemoryRecallShape(memories, selected)
72
+ }
73
+
74
+ return selected.map(m => ({ path: m.filePath, mtimeMs: m.mtimeMs }))
75
+ }
76
+
77
+ async function selectRelevantMemories(
78
+ query: string,
79
+ memories: MemoryHeader[],
80
+ signal: AbortSignal,
81
+ recentTools: readonly string[],
82
+ ): Promise<string[]> {
83
+ const validFilenames = new Set(memories.map(m => m.filename))
84
+
85
+ const manifest = formatMemoryManifest(memories)
86
+
87
+ // When Claude Code is actively using a tool (e.g. mcp__X__spawn),
88
+ // surfacing that tool's reference docs is noise — the conversation
89
+ // already contains working usage. The selector otherwise matches
90
+ // on keyword overlap ("spawn" in query + "spawn" in a memory
91
+ // description → false positive).
92
+ const toolsSection =
93
+ recentTools.length > 0
94
+ ? `\n\nRecently used tools: ${recentTools.join(', ')}`
95
+ : ''
96
+
97
+ try {
98
+ const result = await sideQuery({
99
+ model: getDefaultSonnetModel(),
100
+ system: SELECT_MEMORIES_SYSTEM_PROMPT,
101
+ skipSystemPromptPrefix: true,
102
+ messages: [
103
+ {
104
+ role: 'user',
105
+ content: `Query: ${query}\n\nAvailable memories:\n${manifest}${toolsSection}`,
106
+ },
107
+ ],
108
+ max_tokens: 256,
109
+ output_format: {
110
+ type: 'json_schema',
111
+ schema: {
112
+ type: 'object',
113
+ properties: {
114
+ selected_memories: { type: 'array', items: { type: 'string' } },
115
+ },
116
+ required: ['selected_memories'],
117
+ additionalProperties: false,
118
+ },
119
+ },
120
+ signal,
121
+ querySource: 'memdir_relevance',
122
+ })
123
+
124
+ const textBlock = result.content.find(block => block.type === 'text')
125
+ if (!textBlock || textBlock.type !== 'text') {
126
+ return []
127
+ }
128
+
129
+ const parsed: { selected_memories: string[] } = jsonParse(textBlock.text)
130
+ return parsed.selected_memories.filter(f => validFilenames.has(f))
131
+ } catch (e) {
132
+ if (signal.aborted) {
133
+ return []
134
+ }
135
+ logForDebugging(
136
+ `[memdir] selectRelevantMemories failed: ${errorMessage(e)}`,
137
+ { level: 'warn' },
138
+ )
139
+ return []
140
+ }
141
+ }