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,271 @@
1
+ /**
2
+ * Memory type taxonomy.
3
+ *
4
+ * Memories are constrained to four types capturing context NOT derivable
5
+ * from the current project state. Code patterns, architecture, git history,
6
+ * and file structure are derivable (via grep/git/CLAUDE.md) and should NOT
7
+ * be saved as memories.
8
+ *
9
+ * The two TYPES_SECTION_* exports below are intentionally duplicated rather
10
+ * than generated from a shared spec — keeping them flat makes per-mode edits
11
+ * trivial without reasoning through a helper's conditional rendering.
12
+ */
13
+
14
+ export const MEMORY_TYPES = [
15
+ 'user',
16
+ 'feedback',
17
+ 'project',
18
+ 'reference',
19
+ ] as const
20
+
21
+ export type MemoryType = (typeof MEMORY_TYPES)[number]
22
+
23
+ /**
24
+ * Parse a raw frontmatter value into a MemoryType.
25
+ * Invalid or missing values return undefined — legacy files without a
26
+ * `type:` field keep working, files with unknown types degrade gracefully.
27
+ */
28
+ export function parseMemoryType(raw: unknown): MemoryType | undefined {
29
+ if (typeof raw !== 'string') return undefined
30
+ return MEMORY_TYPES.find(t => t === raw)
31
+ }
32
+
33
+ /**
34
+ * `## Types of memory` section for COMBINED mode (private + team directories).
35
+ * Includes <scope> tags and team/private qualifiers in examples.
36
+ */
37
+ export const TYPES_SECTION_COMBINED: readonly string[] = [
38
+ '## Types of memory',
39
+ '',
40
+ 'There are several discrete types of memory that you can store in your memory system. Each type below declares a <scope> of `private`, `team`, or guidance for choosing between the two.',
41
+ '',
42
+ '<types>',
43
+ '<type>',
44
+ ' <name>user</name>',
45
+ ' <scope>always private</scope>',
46
+ " <description>Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together.</description>",
47
+ " <when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>",
48
+ " <how_to_use>When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have.</how_to_use>",
49
+ ' <examples>',
50
+ " user: I'm a data scientist investigating what logging we have in place",
51
+ ' assistant: [saves private user memory: user is a data scientist, currently focused on observability/logging]',
52
+ '',
53
+ " user: I've been writing Go for ten years but this is my first time touching the React side of this repo",
54
+ " assistant: [saves private user memory: deep Go expertise, new to React and this project's frontend — frame frontend explanations in terms of backend analogues]",
55
+ ' </examples>',
56
+ '</type>',
57
+ '<type>',
58
+ ' <name>feedback</name>',
59
+ ' <scope>default to private. Save as team only when the guidance is clearly a project-wide convention that every contributor should follow (e.g., a testing policy, a build invariant), not a personal style preference.</scope>',
60
+ " <description>Guidance the user has given you about how to approach work — both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious. Before saving a private feedback memory, check that it doesn't contradict a team feedback memory — if it does, either don't save it or note the override explicitly.</description>",
61
+ ' <when_to_save>Any time the user corrects your approach ("no not that", "don\'t", "stop doing X") OR confirms a non-obvious approach worked ("yes exactly", "perfect, keep doing that", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter — watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later.</when_to_save>',
62
+ ' <how_to_use>Let these memories guide your behavior so that the user and other users in the project do not need to offer the same guidance twice.</how_to_use>',
63
+ ' <body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave — often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>',
64
+ ' <examples>',
65
+ " user: don't mock the database in these tests — we got burned last quarter when mocked tests passed but the prod migration failed",
66
+ ' assistant: [saves team feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration. Team scope: this is a project testing policy, not a personal preference]',
67
+ '',
68
+ ' user: stop summarizing what you just did at the end of every response, I can read the diff',
69
+ " assistant: [saves private feedback memory: this user wants terse responses with no trailing summaries. Private because it's a communication preference, not a project convention]",
70
+ '',
71
+ " user: yeah the single bundled PR was the right call here, splitting this one would've just been churn",
72
+ ' assistant: [saves private feedback memory: for refactors in this area, user prefers one bundled PR over many small ones. Confirmed after I chose this approach — a validated judgment call, not a correction]',
73
+ ' </examples>',
74
+ '</type>',
75
+ '<type>',
76
+ ' <name>project</name>',
77
+ ' <scope>private or team, but strongly bias toward team</scope>',
78
+ ' <description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work users are working on within this working directory.</description>',
79
+ ' <when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" → "2026-03-05"), so the memory remains interpretable after time passes.</when_to_save>',
80
+ " <how_to_use>Use these memories to more fully understand the details and nuance behind the user's request, anticipate coordination issues across users, make better informed suggestions.</how_to_use>",
81
+ ' <body_structure>Lead with the fact or decision, then a **Why:** line (the motivation — often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>',
82
+ ' <examples>',
83
+ " user: we're freezing all non-critical merges after Thursday — mobile team is cutting a release branch",
84
+ ' assistant: [saves team project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]',
85
+ '',
86
+ " user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements",
87
+ ' assistant: [saves team project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup — scope decisions should favor compliance over ergonomics]',
88
+ ' </examples>',
89
+ '</type>',
90
+ '<type>',
91
+ ' <name>reference</name>',
92
+ ' <scope>usually team</scope>',
93
+ ' <description>Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory.</description>',
94
+ ' <when_to_save>When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel.</when_to_save>',
95
+ ' <how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>',
96
+ ' <examples>',
97
+ ' user: check the Linear project "INGEST" if you want context on these tickets, that\'s where we track all pipeline bugs',
98
+ ' assistant: [saves team reference memory: pipeline bugs are tracked in Linear project "INGEST"]',
99
+ '',
100
+ " user: the Grafana board at grafana.internal/d/api-latency is what oncall watches — if you're touching request handling, that's the thing that'll page someone",
101
+ ' assistant: [saves team reference memory: grafana.internal/d/api-latency is the oncall latency dashboard — check it when editing request-path code]',
102
+ ' </examples>',
103
+ '</type>',
104
+ '</types>',
105
+ '',
106
+ ]
107
+
108
+ /**
109
+ * `## Types of memory` section for INDIVIDUAL-ONLY mode (single directory).
110
+ * No <scope> tags. Examples use plain `[saves X memory: …]`. Prose that
111
+ * only makes sense with a private/team split is reworded.
112
+ */
113
+ export const TYPES_SECTION_INDIVIDUAL: readonly string[] = [
114
+ '## Types of memory',
115
+ '',
116
+ 'There are several discrete types of memory that you can store in your memory system:',
117
+ '',
118
+ '<types>',
119
+ '<type>',
120
+ ' <name>user</name>',
121
+ " <description>Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together.</description>",
122
+ " <when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>",
123
+ " <how_to_use>When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have.</how_to_use>",
124
+ ' <examples>',
125
+ " user: I'm a data scientist investigating what logging we have in place",
126
+ ' assistant: [saves user memory: user is a data scientist, currently focused on observability/logging]',
127
+ '',
128
+ " user: I've been writing Go for ten years but this is my first time touching the React side of this repo",
129
+ " assistant: [saves user memory: deep Go expertise, new to React and this project's frontend — frame frontend explanations in terms of backend analogues]",
130
+ ' </examples>',
131
+ '</type>',
132
+ '<type>',
133
+ ' <name>feedback</name>',
134
+ ' <description>Guidance the user has given you about how to approach work — both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious.</description>',
135
+ ' <when_to_save>Any time the user corrects your approach ("no not that", "don\'t", "stop doing X") OR confirms a non-obvious approach worked ("yes exactly", "perfect, keep doing that", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter — watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later.</when_to_save>',
136
+ ' <how_to_use>Let these memories guide your behavior so that the user does not need to offer the same guidance twice.</how_to_use>',
137
+ ' <body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave — often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>',
138
+ ' <examples>',
139
+ " user: don't mock the database in these tests — we got burned last quarter when mocked tests passed but the prod migration failed",
140
+ ' assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration]',
141
+ '',
142
+ ' user: stop summarizing what you just did at the end of every response, I can read the diff',
143
+ ' assistant: [saves feedback memory: this user wants terse responses with no trailing summaries]',
144
+ '',
145
+ " user: yeah the single bundled PR was the right call here, splitting this one would've just been churn",
146
+ ' assistant: [saves feedback memory: for refactors in this area, user prefers one bundled PR over many small ones. Confirmed after I chose this approach — a validated judgment call, not a correction]',
147
+ ' </examples>',
148
+ '</type>',
149
+ '<type>',
150
+ ' <name>project</name>',
151
+ ' <description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory.</description>',
152
+ ' <when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" → "2026-03-05"), so the memory remains interpretable after time passes.</when_to_save>',
153
+ " <how_to_use>Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions.</how_to_use>",
154
+ ' <body_structure>Lead with the fact or decision, then a **Why:** line (the motivation — often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>',
155
+ ' <examples>',
156
+ " user: we're freezing all non-critical merges after Thursday — mobile team is cutting a release branch",
157
+ ' assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]',
158
+ '',
159
+ " user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements",
160
+ ' assistant: [saves project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup — scope decisions should favor compliance over ergonomics]',
161
+ ' </examples>',
162
+ '</type>',
163
+ '<type>',
164
+ ' <name>reference</name>',
165
+ ' <description>Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory.</description>',
166
+ ' <when_to_save>When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel.</when_to_save>',
167
+ ' <how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>',
168
+ ' <examples>',
169
+ ' user: check the Linear project "INGEST" if you want context on these tickets, that\'s where we track all pipeline bugs',
170
+ ' assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"]',
171
+ '',
172
+ " user: the Grafana board at grafana.internal/d/api-latency is what oncall watches — if you're touching request handling, that's the thing that'll page someone",
173
+ ' assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard — check it when editing request-path code]',
174
+ ' </examples>',
175
+ '</type>',
176
+ '</types>',
177
+ '',
178
+ ]
179
+
180
+ /**
181
+ * `## What NOT to save in memory` section. Identical across both modes.
182
+ */
183
+ export const WHAT_NOT_TO_SAVE_SECTION: readonly string[] = [
184
+ '## What NOT to save in memory',
185
+ '',
186
+ '- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.',
187
+ '- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative.',
188
+ '- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context.',
189
+ '- Anything already documented in CLAUDE.md files.',
190
+ '- Ephemeral task details: in-progress work, temporary state, current conversation context.',
191
+ '',
192
+ // H2: explicit-save gate. Eval-validated (memory-prompt-iteration case 3,
193
+ // 0/2 → 3/3): prevents "save this week's PR list" → activity-log noise.
194
+ 'These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it — that is the part worth keeping.',
195
+ ]
196
+
197
+ /**
198
+ * Recall-side drift caveat. Single bullet under `## When to access memories`.
199
+ * Proactive: verify memory against current state before answering.
200
+ */
201
+ export const MEMORY_DRIFT_CAVEAT =
202
+ '- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now — and update or remove the stale memory rather than acting on it.'
203
+
204
+ /**
205
+ * `## When to access memories` section. Includes MEMORY_DRIFT_CAVEAT.
206
+ *
207
+ * H6 (branch-pollution evals #22856, case 5 1/3 on capy): the "ignore" bullet
208
+ * is the delta. Failure mode: user says "ignore memory about X" → Claude reads
209
+ * code correctly but adds "not Y as noted in memory" — treats "ignore" as
210
+ * "acknowledge then override" rather than "don't reference at all." The bullet
211
+ * names that anti-pattern explicitly.
212
+ *
213
+ * Token budget (H6a): merged old bullets 1+2, tightened both. Old 4 lines
214
+ * were ~70 tokens; new 4 lines are ~73 tokens. Net ~+3.
215
+ */
216
+ export const WHEN_TO_ACCESS_SECTION: readonly string[] = [
217
+ '## When to access memories',
218
+ '- When memories seem relevant, or the user references prior-conversation work.',
219
+ '- You MUST access memory when the user explicitly asks you to check, recall, or remember.',
220
+ '- If the user says to *ignore* or *not use* memory: proceed as if MEMORY.md were empty. Do not apply remembered facts, cite, compare against, or mention memory content.',
221
+ MEMORY_DRIFT_CAVEAT,
222
+ ]
223
+
224
+ /**
225
+ * `## Trusting what you recall` section. Heavier-weight guidance on HOW to
226
+ * treat a memory once you've recalled it — separate from WHEN to access.
227
+ *
228
+ * Eval-validated (memory-prompt-iteration.eval.ts, 2026-03-17):
229
+ * H1 (verify function/file claims): 0/2 → 3/3 via appendSystemPrompt. When
230
+ * buried as a bullet under "When to access", dropped to 0/3 — position
231
+ * matters. The H1 cue is about what to DO with a memory, not when to
232
+ * look, so it needs its own section-level trigger context.
233
+ * H5 (read-side noise rejection): 0/2 → 3/3 via appendSystemPrompt, 2/3
234
+ * in-place as a bullet. Partial because "snapshot" is intuitively closer
235
+ * to "when to access" than H1 is.
236
+ *
237
+ * Known gap: H1 doesn't cover slash-command claims (0/3 on the /fork case —
238
+ * slash commands aren't files or functions in the model's ontology).
239
+ */
240
+ export const TRUSTING_RECALL_SECTION: readonly string[] = [
241
+ // Header wording matters: "Before recommending" (action cue at the decision
242
+ // point) tested better than "Trusting what you recall" (abstract). The
243
+ // appendSystemPrompt variant with this header went 3/3; the abstract header
244
+ // went 0/3 in-place. Same body text — only the header differed.
245
+ '## Before recommending from memory',
246
+ '',
247
+ 'A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it:',
248
+ '',
249
+ '- If the memory names a file path: check the file exists.',
250
+ '- If the memory names a function or flag: grep for it.',
251
+ '- If the user is about to act on your recommendation (not just asking about history), verify first.',
252
+ '',
253
+ '"The memory says X exists" is not the same as "X exists now."',
254
+ '',
255
+ 'A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot.',
256
+ ]
257
+
258
+ /**
259
+ * Frontmatter format example with the `type` field.
260
+ */
261
+ export const MEMORY_FRONTMATTER_EXAMPLE: readonly string[] = [
262
+ '```markdown',
263
+ '---',
264
+ 'name: {{memory name}}',
265
+ 'description: {{one-line description — used to decide relevance in future conversations, so be specific}}',
266
+ `type: {{${MEMORY_TYPES.join(', ')}}}`,
267
+ '---',
268
+ '',
269
+ '{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}',
270
+ '```',
271
+ ]
@@ -0,0 +1,278 @@
1
+ import memoize from 'lodash-es/memoize.js'
2
+ import { homedir } from 'os'
3
+ import { isAbsolute, join, normalize, sep } from 'path'
4
+ import {
5
+ getIsNonInteractiveSession,
6
+ getProjectRoot,
7
+ } from '../bootstrap/state.js'
8
+ import { getFeatureValue_CACHED_MAY_BE_STALE } from '../services/analytics/growthbook.js'
9
+ import {
10
+ getClaudeConfigHomeDir,
11
+ isEnvDefinedFalsy,
12
+ isEnvTruthy,
13
+ } from '../utils/envUtils.js'
14
+ import { findCanonicalGitRoot } from '../utils/git.js'
15
+ import { sanitizePath } from '../utils/path.js'
16
+ import {
17
+ getInitialSettings,
18
+ getSettingsForSource,
19
+ } from '../utils/settings/settings.js'
20
+
21
+ /**
22
+ * Whether auto-memory features are enabled (memdir, agent memory, past session search).
23
+ * Enabled by default. Priority chain (first defined wins):
24
+ * 1. CLAUDE_CODE_DISABLE_AUTO_MEMORY env var (1/true → OFF, 0/false → ON)
25
+ * 2. CLAUDE_CODE_SIMPLE (--bare) → OFF
26
+ * 3. CCR without persistent storage → OFF (no CLAUDE_CODE_REMOTE_MEMORY_DIR)
27
+ * 4. autoMemoryEnabled in settings.json (supports project-level opt-out)
28
+ * 5. Default: enabled
29
+ */
30
+ export function isAutoMemoryEnabled(): boolean {
31
+ const envVal = process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY
32
+ if (isEnvTruthy(envVal)) {
33
+ return false
34
+ }
35
+ if (isEnvDefinedFalsy(envVal)) {
36
+ return true
37
+ }
38
+ // --bare / SIMPLE: prompts.ts already drops the memory section from the
39
+ // system prompt via its SIMPLE early-return; this gate stops the other half
40
+ // (extractMemories turn-end fork, autoDream, /remember, /dream, team sync).
41
+ if (isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)) {
42
+ return false
43
+ }
44
+ if (
45
+ isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) &&
46
+ !process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR
47
+ ) {
48
+ return false
49
+ }
50
+ const settings = getInitialSettings()
51
+ if (settings.autoMemoryEnabled !== undefined) {
52
+ return settings.autoMemoryEnabled
53
+ }
54
+ return true
55
+ }
56
+
57
+ /**
58
+ * Whether the extract-memories background agent will run this session.
59
+ *
60
+ * The main agent's prompt always has full save instructions regardless of
61
+ * this gate — when the main agent writes memories, the background agent
62
+ * skips that range (hasMemoryWritesSince in extractMemories.ts); when it
63
+ * doesn't, the background agent catches anything missed.
64
+ *
65
+ * Callers must also gate on feature('EXTRACT_MEMORIES') — that check cannot
66
+ * live inside this helper because feature() only tree-shakes when used
67
+ * directly in an `if` condition.
68
+ */
69
+ export function isExtractModeActive(): boolean {
70
+ if (!getFeatureValue_CACHED_MAY_BE_STALE('tengu_passport_quail', false)) {
71
+ return false
72
+ }
73
+ return (
74
+ !getIsNonInteractiveSession() ||
75
+ getFeatureValue_CACHED_MAY_BE_STALE('tengu_slate_thimble', false)
76
+ )
77
+ }
78
+
79
+ /**
80
+ * Returns the base directory for persistent memory storage.
81
+ * Resolution order:
82
+ * 1. CLAUDE_CODE_REMOTE_MEMORY_DIR env var (explicit override, set in CCR)
83
+ * 2. ~/.claude (default config home)
84
+ */
85
+ export function getMemoryBaseDir(): string {
86
+ if (process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR) {
87
+ return process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR
88
+ }
89
+ return getClaudeConfigHomeDir()
90
+ }
91
+
92
+ const AUTO_MEM_DIRNAME = 'memory'
93
+ const AUTO_MEM_ENTRYPOINT_NAME = 'MEMORY.md'
94
+
95
+ /**
96
+ * Normalize and validate a candidate auto-memory directory path.
97
+ *
98
+ * SECURITY: Rejects paths that would be dangerous as a read-allowlist root
99
+ * or that normalize() doesn't fully resolve:
100
+ * - relative (!isAbsolute): "../foo" — would be interpreted relative to CWD
101
+ * - root/near-root (length < 3): "/" → "" after strip; "/a" too short
102
+ * - Windows drive-root (C: regex): "C:\" → "C:" after strip
103
+ * - UNC paths (\\server\share): network paths — opaque trust boundary
104
+ * - null byte: survives normalize(), can truncate in syscalls
105
+ *
106
+ * Returns the normalized path with exactly one trailing separator,
107
+ * or undefined if the path is unset/empty/rejected.
108
+ */
109
+ function validateMemoryPath(
110
+ raw: string | undefined,
111
+ expandTilde: boolean,
112
+ ): string | undefined {
113
+ if (!raw) {
114
+ return undefined
115
+ }
116
+ let candidate = raw
117
+ // Settings.json paths support ~/ expansion (user-friendly). The env var
118
+ // override does not (it's set programmatically by Cowork/SDK, which should
119
+ // always pass absolute paths). Bare "~", "~/", "~/.", "~/..", etc. are NOT
120
+ // expanded — they would make isAutoMemPath() match all of $HOME or its
121
+ // parent (same class of danger as "/" or "C:\").
122
+ if (
123
+ expandTilde &&
124
+ (candidate.startsWith('~/') || candidate.startsWith('~\\'))
125
+ ) {
126
+ const rest = candidate.slice(2)
127
+ // Reject trivial remainders that would expand to $HOME or an ancestor.
128
+ // normalize('') = '.', normalize('.') = '.', normalize('foo/..') = '.',
129
+ // normalize('..') = '..', normalize('foo/../..') = '..'
130
+ const restNorm = normalize(rest || '.')
131
+ if (restNorm === '.' || restNorm === '..') {
132
+ return undefined
133
+ }
134
+ candidate = join(homedir(), rest)
135
+ }
136
+ // normalize() may preserve a trailing separator; strip before adding
137
+ // exactly one to match the trailing-sep contract of getAutoMemPath()
138
+ const normalized = normalize(candidate).replace(/[/\\]+$/, '')
139
+ if (
140
+ !isAbsolute(normalized) ||
141
+ normalized.length < 3 ||
142
+ /^[A-Za-z]:$/.test(normalized) ||
143
+ normalized.startsWith('\\\\') ||
144
+ normalized.startsWith('//') ||
145
+ normalized.includes('\0')
146
+ ) {
147
+ return undefined
148
+ }
149
+ return (normalized + sep).normalize('NFC')
150
+ }
151
+
152
+ /**
153
+ * Direct override for the full auto-memory directory path via env var.
154
+ * When set, getAutoMemPath()/getAutoMemEntrypoint() return this path directly
155
+ * instead of computing `{base}/projects/{sanitized-cwd}/memory/`.
156
+ *
157
+ * Used by Cowork to redirect memory to a space-scoped mount where the
158
+ * per-session cwd (which contains the VM process name) would otherwise
159
+ * produce a different project-key for every session.
160
+ */
161
+ function getAutoMemPathOverride(): string | undefined {
162
+ return validateMemoryPath(
163
+ process.env.CLAUDE_COWORK_MEMORY_PATH_OVERRIDE,
164
+ false,
165
+ )
166
+ }
167
+
168
+ /**
169
+ * Settings.json override for the full auto-memory directory path.
170
+ * Supports ~/ expansion for user convenience.
171
+ *
172
+ * SECURITY: projectSettings (.claude/settings.json committed to the repo) is
173
+ * intentionally excluded — a malicious repo could otherwise set
174
+ * autoMemoryDirectory: "~/.ssh" and gain silent write access to sensitive
175
+ * directories via the filesystem.ts write carve-out (which fires when
176
+ * isAutoMemPath() matches and hasAutoMemPathOverride() is false). This follows
177
+ * the same pattern as hasSkipDangerousModePermissionPrompt() etc.
178
+ */
179
+ function getAutoMemPathSetting(): string | undefined {
180
+ const dir =
181
+ getSettingsForSource('policySettings')?.autoMemoryDirectory ??
182
+ getSettingsForSource('flagSettings')?.autoMemoryDirectory ??
183
+ getSettingsForSource('localSettings')?.autoMemoryDirectory ??
184
+ getSettingsForSource('userSettings')?.autoMemoryDirectory
185
+ return validateMemoryPath(dir, true)
186
+ }
187
+
188
+ /**
189
+ * Check if CLAUDE_COWORK_MEMORY_PATH_OVERRIDE is set to a valid override.
190
+ * Use this as a signal that the SDK caller has explicitly opted into
191
+ * the auto-memory mechanics — e.g. to decide whether to inject the
192
+ * memory prompt when a custom system prompt replaces the default.
193
+ */
194
+ export function hasAutoMemPathOverride(): boolean {
195
+ return getAutoMemPathOverride() !== undefined
196
+ }
197
+
198
+ /**
199
+ * Returns the canonical git repo root if available, otherwise falls back to
200
+ * the stable project root. Uses findCanonicalGitRoot so all worktrees of the
201
+ * same repo share one auto-memory directory (anthropics/claude-code#24382).
202
+ */
203
+ function getAutoMemBase(): string {
204
+ return findCanonicalGitRoot(getProjectRoot()) ?? getProjectRoot()
205
+ }
206
+
207
+ /**
208
+ * Returns the auto-memory directory path.
209
+ *
210
+ * Resolution order:
211
+ * 1. CLAUDE_COWORK_MEMORY_PATH_OVERRIDE env var (full-path override, used by Cowork)
212
+ * 2. autoMemoryDirectory in settings.json (trusted sources only: policy/local/user)
213
+ * 3. <memoryBase>/projects/<sanitized-git-root>/memory/
214
+ * where memoryBase is resolved by getMemoryBaseDir()
215
+ *
216
+ * Memoized: render-path callers (collapseReadSearchGroups → isAutoManagedMemoryFile)
217
+ * fire per tool-use message per Messages re-render; each miss costs
218
+ * getSettingsForSource × 4 → parseSettingsFile (realpathSync + readFileSync).
219
+ * Keyed on projectRoot so tests that change its mock mid-block recompute;
220
+ * env vars / settings.json / CLAUDE_CONFIG_DIR are session-stable in
221
+ * production and covered by per-test cache.clear.
222
+ */
223
+ export const getAutoMemPath = memoize(
224
+ (): string => {
225
+ const override = getAutoMemPathOverride() ?? getAutoMemPathSetting()
226
+ if (override) {
227
+ return override
228
+ }
229
+ const projectsDir = join(getMemoryBaseDir(), 'projects')
230
+ return (
231
+ join(projectsDir, sanitizePath(getAutoMemBase()), AUTO_MEM_DIRNAME) + sep
232
+ ).normalize('NFC')
233
+ },
234
+ () => getProjectRoot(),
235
+ )
236
+
237
+ /**
238
+ * Returns the daily log file path for the given date (defaults to today).
239
+ * Shape: <autoMemPath>/logs/YYYY/MM/YYYY-MM-DD.md
240
+ *
241
+ * Used by assistant mode (feature('KAIROS')): rather than maintaining
242
+ * MEMORY.md as a live index, the agent appends to a date-named log file
243
+ * as it works. A separate nightly /dream skill distills these logs into
244
+ * topic files + MEMORY.md.
245
+ */
246
+ export function getAutoMemDailyLogPath(date: Date = new Date()): string {
247
+ const yyyy = date.getFullYear().toString()
248
+ const mm = (date.getMonth() + 1).toString().padStart(2, '0')
249
+ const dd = date.getDate().toString().padStart(2, '0')
250
+ return join(getAutoMemPath(), 'logs', yyyy, mm, `${yyyy}-${mm}-${dd}.md`)
251
+ }
252
+
253
+ /**
254
+ * Returns the auto-memory entrypoint (MEMORY.md inside the auto-memory dir).
255
+ * Follows the same resolution order as getAutoMemPath().
256
+ */
257
+ export function getAutoMemEntrypoint(): string {
258
+ return join(getAutoMemPath(), AUTO_MEM_ENTRYPOINT_NAME)
259
+ }
260
+
261
+ /**
262
+ * Check if an absolute path is within the auto-memory directory.
263
+ *
264
+ * When CLAUDE_COWORK_MEMORY_PATH_OVERRIDE is set, this matches against the
265
+ * env-var override directory. Note that a true return here does NOT imply
266
+ * write permission in that case — the filesystem.ts write carve-out is gated
267
+ * on !hasAutoMemPathOverride() (it exists to bypass DANGEROUS_DIRECTORIES).
268
+ *
269
+ * The settings.json autoMemoryDirectory DOES get the write carve-out: it's the
270
+ * user's explicit choice from a trusted settings source (projectSettings is
271
+ * excluded — see getAutoMemPathSetting), and hasAutoMemPathOverride() remains
272
+ * false for it.
273
+ */
274
+ export function isAutoMemPath(absolutePath: string): boolean {
275
+ // SECURITY: Normalize to prevent path traversal bypasses via .. segments
276
+ const normalizedPath = normalize(absolutePath)
277
+ return normalizedPath.startsWith(getAutoMemPath())
278
+ }