@picassohq/cli 0.0.0-stage → 1.0.2

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 (232) hide show
  1. package/agents/browser_agent.yaml +53 -0
  2. package/agents/code_reviewer.yaml +49 -0
  3. package/agents/codebase_investigator.yaml +70 -0
  4. package/agents/design_auditor.yaml +50 -0
  5. package/agents/devex_auditor.yaml +50 -0
  6. package/agents/doc_writer.yaml +54 -0
  7. package/agents/engineering_architect.yaml +51 -0
  8. package/agents/generalist.yaml +55 -0
  9. package/agents/migration_planner.yaml +51 -0
  10. package/agents/product_reviewer.yaml +48 -0
  11. package/agents/qa_operator.yaml +52 -0
  12. package/agents/release_engineer.yaml +50 -0
  13. package/agents/security_auditor.yaml +62 -0
  14. package/agents/test_writer.yaml +52 -0
  15. package/assets/first-light-lockup.png +0 -0
  16. package/assets/first-light-tagline.png +0 -0
  17. package/assets/house/README.md +26 -0
  18. package/assets/house/auraone-banner.png +0 -0
  19. package/assets/house/auraone-logo.png +0 -0
  20. package/assets/house/kiro-prism-banner.png +0 -0
  21. package/assets/house/kiro-prism-logo.png +0 -0
  22. package/assets/house/picasso-banner.png +0 -0
  23. package/assets/house/picasso-logo.png +0 -0
  24. package/assets/wordmark-app.png +0 -0
  25. package/assets/wordmark-tight.png +0 -0
  26. package/assets/wordmark.png +0 -0
  27. package/design/styles.css +1042 -0
  28. package/dist/build-info.json +37 -0
  29. package/dist/index.js +3062 -0
  30. package/goals/cli-hardening.yaml +40 -0
  31. package/goals/repo-maintenance.yaml +40 -0
  32. package/package.json +49 -4
  33. package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
  34. package/runtime/dsh/picasso-ecosystem.community.json +185 -0
  35. package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
  36. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
  37. package/runtime/dsh/picasso-isolation.patch.yml +25 -0
  38. package/runtime/dsh/picasso-providers.patch.yml +373 -0
  39. package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
  40. package/runtime/dsh/picasso-sdk.patch.yml +204 -0
  41. package/runtime/engine-manifest.json +215 -0
  42. package/runtime/package.json +6 -0
  43. package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
  44. package/runtime/packages/picasso-cache-probe/index.js +477 -0
  45. package/runtime/packages/picasso-cache-probe/package.json +38 -0
  46. package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
  47. package/runtime/packages/picasso-commands/fresh-review.js +573 -0
  48. package/runtime/packages/picasso-commands/index.js +497 -0
  49. package/runtime/packages/picasso-commands/package.json +28 -0
  50. package/runtime/packages/picasso-instructions/conflicts.js +115 -0
  51. package/runtime/packages/picasso-instructions/formats.js +145 -0
  52. package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
  53. package/runtime/packages/picasso-instructions/glob.js +114 -0
  54. package/runtime/packages/picasso-instructions/globals.js +90 -0
  55. package/runtime/packages/picasso-instructions/imports.js +123 -0
  56. package/runtime/packages/picasso-instructions/index.js +326 -0
  57. package/runtime/packages/picasso-instructions/modes.js +64 -0
  58. package/runtime/packages/picasso-instructions/package.json +30 -0
  59. package/runtime/packages/picasso-instructions/parse.js +134 -0
  60. package/runtime/packages/picasso-instructions/report.js +161 -0
  61. package/runtime/packages/picasso-instructions/resolve.js +939 -0
  62. package/runtime/packages/picasso-instructions/scan.js +181 -0
  63. package/runtime/packages/picasso-instructions/settings.js +150 -0
  64. package/runtime/packages/picasso-instructions/skills.js +345 -0
  65. package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
  66. package/runtime/packages/picasso-lean-context/index.js +6280 -0
  67. package/runtime/packages/picasso-lean-context/package.json +26 -0
  68. package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
  69. package/runtime/packages/picasso-lean-context/timeline.js +418 -0
  70. package/runtime/packages/picasso-librarian/classify.js +146 -0
  71. package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
  72. package/runtime/packages/picasso-librarian/index.js +878 -0
  73. package/runtime/packages/picasso-librarian/notes.js +159 -0
  74. package/runtime/packages/picasso-librarian/package.json +34 -0
  75. package/runtime/packages/picasso-librarian/state.js +478 -0
  76. package/runtime/packages/picasso-memory/index.js +1184 -0
  77. package/runtime/packages/picasso-memory/package.json +21 -0
  78. package/runtime/packages/picasso-model-router/connections.js +912 -0
  79. package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
  80. package/runtime/packages/picasso-model-router/index.js +1083 -0
  81. package/runtime/packages/picasso-model-router/package.json +30 -0
  82. package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
  83. package/runtime/packages/picasso-options/index.js +263 -0
  84. package/runtime/packages/picasso-options/package.json +28 -0
  85. package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
  86. package/runtime/packages/picasso-progress-reports/index.js +267 -0
  87. package/runtime/packages/picasso-progress-reports/package.json +30 -0
  88. package/runtime/packages/picasso-progress-reports/report.js +235 -0
  89. package/runtime/packages/picasso-sdk-server/aside.js +142 -0
  90. package/runtime/packages/picasso-sdk-server/connections.js +38 -0
  91. package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
  92. package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
  93. package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
  94. package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
  95. package/runtime/packages/picasso-sdk-server/goal.js +131 -0
  96. package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
  97. package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
  98. package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
  99. package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
  100. package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
  101. package/runtime/packages/picasso-sdk-server/index.js +891 -0
  102. package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
  103. package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
  104. package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
  105. package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
  106. package/runtime/packages/picasso-sdk-server/package.json +50 -0
  107. package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
  108. package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
  109. package/runtime/packages/picasso-sdk-server/queue.js +322 -0
  110. package/runtime/packages/picasso-sdk-server/requester.js +43 -0
  111. package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
  112. package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
  113. package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
  114. package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
  115. package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
  116. package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
  117. package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
  118. package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
  119. package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
  120. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
  121. package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
  122. package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
  123. package/runtime/packages/picasso-web-search/backends.js +412 -0
  124. package/runtime/packages/picasso-web-search/config.js +121 -0
  125. package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
  126. package/runtime/packages/picasso-web-search/failure.js +116 -0
  127. package/runtime/packages/picasso-web-search/format.js +42 -0
  128. package/runtime/packages/picasso-web-search/index.js +71 -0
  129. package/runtime/packages/picasso-web-search/package.json +38 -0
  130. package/runtime/packages/picasso-web-search/router.js +156 -0
  131. package/runtime/packages/picasso-x-reader/circle.js +324 -0
  132. package/runtime/packages/picasso-x-reader/command.js +169 -0
  133. package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
  134. package/runtime/packages/picasso-x-reader/index.js +170 -0
  135. package/runtime/packages/picasso-x-reader/package.json +39 -0
  136. package/runtime/packages/picasso-x-reader/read.js +370 -0
  137. package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
  138. package/runtime/packages/picasso-x-reader/settings.js +131 -0
  139. package/runtime/packages/picasso-x-reader/urls.js +154 -0
  140. package/runtime/packages/picasso-x-reader/xmd.js +512 -0
  141. package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
  142. package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
  143. package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
  144. package/runtime/plugins/picasso-auto-approve/package.json +28 -0
  145. package/runtime/plugins/picasso-browser/index.js +424 -0
  146. package/runtime/plugins/picasso-browser/package.json +28 -0
  147. package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
  148. package/runtime/plugins/picasso-checkpoints/index.js +885 -0
  149. package/runtime/plugins/picasso-checkpoints/package.json +29 -0
  150. package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
  151. package/runtime/plugins/picasso-commands/index.js +497 -0
  152. package/runtime/plugins/picasso-commands/package.json +28 -0
  153. package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
  154. package/runtime/plugins/picasso-instructions/formats.js +145 -0
  155. package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
  156. package/runtime/plugins/picasso-instructions/glob.js +114 -0
  157. package/runtime/plugins/picasso-instructions/globals.js +90 -0
  158. package/runtime/plugins/picasso-instructions/imports.js +123 -0
  159. package/runtime/plugins/picasso-instructions/index.js +326 -0
  160. package/runtime/plugins/picasso-instructions/modes.js +64 -0
  161. package/runtime/plugins/picasso-instructions/package.json +30 -0
  162. package/runtime/plugins/picasso-instructions/parse.js +134 -0
  163. package/runtime/plugins/picasso-instructions/report.js +161 -0
  164. package/runtime/plugins/picasso-instructions/resolve.js +939 -0
  165. package/runtime/plugins/picasso-instructions/scan.js +181 -0
  166. package/runtime/plugins/picasso-instructions/settings.js +150 -0
  167. package/runtime/plugins/picasso-instructions/skills.js +345 -0
  168. package/runtime/plugins/picasso-lean-context/index.js +6280 -0
  169. package/runtime/plugins/picasso-lean-context/package.json +26 -0
  170. package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
  171. package/runtime/plugins/picasso-lean-context/timeline.js +418 -0
  172. package/runtime/plugins/picasso-librarian/classify.js +146 -0
  173. package/runtime/plugins/picasso-librarian/index.js +878 -0
  174. package/runtime/plugins/picasso-librarian/notes.js +159 -0
  175. package/runtime/plugins/picasso-librarian/package.json +34 -0
  176. package/runtime/plugins/picasso-librarian/state.js +478 -0
  177. package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
  178. package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
  179. package/runtime/plugins/picasso-mail/inbox.js +207 -0
  180. package/runtime/plugins/picasso-mail/index.js +293 -0
  181. package/runtime/plugins/picasso-mail/package.json +22 -0
  182. package/runtime/plugins/picasso-memory/index.js +1184 -0
  183. package/runtime/plugins/picasso-memory/package.json +21 -0
  184. package/runtime/plugins/picasso-model-router/connections.js +912 -0
  185. package/runtime/plugins/picasso-model-router/index.js +1083 -0
  186. package/runtime/plugins/picasso-model-router/package.json +30 -0
  187. package/runtime/plugins/picasso-options/index.js +263 -0
  188. package/runtime/plugins/picasso-options/package.json +28 -0
  189. package/runtime/plugins/picasso-progress-reports/index.js +267 -0
  190. package/runtime/plugins/picasso-progress-reports/package.json +30 -0
  191. package/runtime/plugins/picasso-progress-reports/report.js +235 -0
  192. package/runtime/plugins/picasso-provider-models/index.js +436 -0
  193. package/runtime/plugins/picasso-provider-models/package.json +28 -0
  194. package/runtime/plugins/picasso-repo-index/index.js +1850 -0
  195. package/runtime/plugins/picasso-repo-index/package.json +28 -0
  196. package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
  197. package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
  198. package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
  199. package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
  200. package/runtime/plugins/picasso-trackers/index.js +895 -0
  201. package/runtime/plugins/picasso-trackers/package.json +28 -0
  202. package/runtime/plugins/picasso-web-search/backends.js +412 -0
  203. package/runtime/plugins/picasso-web-search/config.js +121 -0
  204. package/runtime/plugins/picasso-web-search/failure.js +116 -0
  205. package/runtime/plugins/picasso-web-search/format.js +42 -0
  206. package/runtime/plugins/picasso-web-search/index.js +71 -0
  207. package/runtime/plugins/picasso-web-search/package.json +38 -0
  208. package/runtime/plugins/picasso-web-search/router.js +156 -0
  209. package/runtime/plugins/picasso-x-reader/circle.js +324 -0
  210. package/runtime/plugins/picasso-x-reader/command.js +169 -0
  211. package/runtime/plugins/picasso-x-reader/index.js +170 -0
  212. package/runtime/plugins/picasso-x-reader/package.json +39 -0
  213. package/runtime/plugins/picasso-x-reader/read.js +370 -0
  214. package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
  215. package/runtime/plugins/picasso-x-reader/settings.js +131 -0
  216. package/runtime/plugins/picasso-x-reader/urls.js +154 -0
  217. package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
  218. package/runtime/relay/attachment-text.mjs +737 -0
  219. package/runtime/relay/companion/companion.css +126 -0
  220. package/runtime/relay/companion/companion.js +648 -0
  221. package/runtime/relay/companion/icon.svg +5 -0
  222. package/runtime/relay/companion/index.html +25 -0
  223. package/runtime/relay/companion/manifest.json +13 -0
  224. package/runtime/relay/companion/sw.js +41 -0
  225. package/runtime/relay/main.mjs +38580 -0
  226. package/runtime/relay/model-listing.mjs +614 -0
  227. package/runtime/relay/versions-routes.mjs +1400 -0
  228. package/runtime/verify-plugins.mjs +205 -0
  229. package/runtime-lock/package-lock.json +10779 -0
  230. package/runtime-lock/package.json +7 -0
  231. package/scripts/install-runtime.mjs +400 -0
  232. package/README.md +0 -3
@@ -0,0 +1,1184 @@
1
+ // @picasso/memory-recall — Two-tier on-demand memory for Picasso › Memory in dsh threads.
2
+ //
3
+ // Tier 1 (`agent/pre-step`, strict `MAX_TIER1_BYTES = 1024` budget):
4
+ // - Pinned memories and short `style`/`workflow` preferences (`isInlineAlways(record)`) are rendered inline
5
+ // (`- [<class>] <body>`) and marked as shown-in-full in the session.
6
+ // - Other relevant memories (`fact`, `decision`, etc.) are listed as compact index lines only:
7
+ // `- <id> · <class> · <title|snippet> · <scope>` up to `MAX_RECALL` lines within 1024 bytes,
8
+ // with a footer instructing the model to call `recall({ ids })` or `recall({ query })`.
9
+ //
10
+ // Tier 2 (`recall` tool next to `remember`):
11
+ // - Loads full memory bodies on demand by `ids` or `query`, deduplicating any memory already shown in full
12
+ // during the current session.
13
+ //
14
+ // Zero runtime dependencies on purpose (mounted by absolute path beside the relay, like picasso-session-lifecycle).
15
+ //
16
+ // File format (Sync D5): the shared `~/.picasso/memory.json` is schema v2, `{ schemaVersion: 2, records: VectorRecord[] }`,
17
+ // with the Mac fields (`scope`, `source`, `stale`, `tags`, `title`, `lastUsedAt`) in `metadata.attributes` and deleted
18
+ // records kept as tombstones (`attributes.deletedAt`). This plugin still reads v0 (a bare `MemoryRecord[]`, the Mac's
19
+ // legacy file) and v1 (`{ version: 1, records }`, the CLI's old file). A v0 file is written back as v0 so the Mac's
20
+ // own decoder keeps working until it reads through the relay; v1 and a missing file are written as v2. A file from a
21
+ // newer Picasso (`schemaVersion > 2`) injects nothing and makes `recall`/`remember` fail with `memory/newer-schema`;
22
+ // a malformed file fails with `memory/invalid`. Neither is ever read as "no memories" (C1).
23
+ //
24
+ // Every write holds `<file>.lock`, the same O_EXCL lockfile protocol (`{pid, token, acquiredAt, host}`, stale after
25
+ // 30 s or a dead pid, ABA-safe rename-aside break) as `@picasso/shared-home/lock`, so the CLI and this plugin exclude
26
+ // each other. Files are written tmp(0600) + fsync + rename.
27
+ import { createHash, randomUUID } from 'node:crypto';
28
+ import {
29
+ chmodSync,
30
+ closeSync,
31
+ constants as fsConstants,
32
+ copyFileSync,
33
+ fsyncSync,
34
+ linkSync,
35
+ mkdirSync,
36
+ openSync,
37
+ readdirSync,
38
+ readFileSync,
39
+ renameSync,
40
+ rmSync,
41
+ statSync,
42
+ writeSync,
43
+ } from 'node:fs';
44
+ import { hostname } from 'node:os';
45
+ import { basename, dirname, join } from 'node:path';
46
+
47
+ export const name = 'picasso-memory';
48
+ /** The dsh release this plugin is written and tested against (Picasso pins the engine to it). */
49
+ export const dshTarget = '0.2.2-rc.3';
50
+ export const SOURCE_KIND = 'picasso-memory';
51
+ export const FILE_ENV = 'PICASSO_MEMORY_FILE';
52
+ export const DEFAULT_MAX_ITEMS = 12;
53
+ export const MAX_RECALL = DEFAULT_MAX_ITEMS;
54
+ export const MAX_TIER1_BYTES = 1024;
55
+ export const DEFAULT_MAX_BYTES = 4096;
56
+ /** The model's write path into the same file the Mac owns (`remember` tool, N9). */
57
+ export const REMEMBER_TOOL = 'remember';
58
+ /** The model's Tier 2 read path for on-demand memory bodies (`recall` tool, Pillar 4). */
59
+ export const RECALL_TOOL = 'recall';
60
+ export const SERVICE_KEY = 'memory';
61
+ const REMOTE_METHOD_DESCRIPTOR = '@deepseek-ai/dsh-typert-protocol/remote-methods';
62
+ /** Memory classes the Mac's `MemoryClass` enum stores verbatim. */
63
+ export const MEMORY_CLASSES = ['fact', 'decision', 'style', 'workflow', 'repo-rule', 'failure', 'model-performance'];
64
+ const REMEMBER_MAX_BODY = 4000;
65
+ const INLINE_PREFERENCE_MAX_CHARS = 240;
66
+ /** Scopes the Mac writes for "All projects" (`MemoryView.projectLabel`). */
67
+ const GLOBAL_SCOPES = new Set(['', 'workspace', 'global', 'all projects']);
68
+ /** Memory classes the Mac files under Preferences (`MemoryGroup.preferences`): they apply to every prompt. */
69
+ const PREFERENCE_CLASSES = new Set(['style', 'workflow', 'preference']);
70
+ const STOPWORDS = new Set(
71
+ 'the and for with that this from have what when where which will would should could your you are was were been about into than then them they their there here also just like make made use using please can not but all any our out its it’s'.split(' '),
72
+ );
73
+
74
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
75
+ const oneLine = (text) => String(text ?? '').trim().replace(/\s+/g, ' ');
76
+ const classOf = (record) => String(record?.class ?? record?.memoryClass ?? 'fact').trim() || 'fact';
77
+ const words = (text) => new Set(String(text).toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter((word) => word.length >= 3 && !STOPWORDS.has(word)));
78
+
79
+ /**
80
+ * Determines whether a memory record is injected inline in Tier 1 (`true`) or listed as an index line
81
+ * and recalled on demand via `recall` in Tier 2 (`false`).
82
+ */
83
+ export function isInlineAlways(record) {
84
+ if (!isRecord(record)) return false;
85
+ if (record.pinned === true) return true;
86
+ const bodyLen = String(record.body ?? '').trim().length;
87
+ if (bodyLen > INLINE_PREFERENCE_MAX_CHARS) return false;
88
+ const cls = classOf(record).toLowerCase();
89
+ if (cls === 'style' || cls === 'workflow') {
90
+ return true;
91
+ }
92
+ if (cls === 'preference') {
93
+ const tags = Array.isArray(record.tags) ? record.tags.map((tag) => String(tag).trim().toLowerCase()) : [];
94
+ return tags.length === 0 || tags.includes('style') || tags.includes('workflow');
95
+ }
96
+ return false;
97
+ }
98
+
99
+ /** Reads the memory file (v0, v1 or v2). A missing file is no memories; a newer or malformed file throws. */
100
+ export function readMemories(file) {
101
+ if (!file) return [];
102
+ return listMemories(loadMemoryFile(file).records);
103
+ }
104
+
105
+ /** Lists memories from a file path or record array with `delivery: 'inline' | 'on-demand'` attached. */
106
+ export function listMemories(fileOrRecords) {
107
+ const records = Array.isArray(fileOrRecords) ? fileOrRecords : readMemories(fileOrRecords);
108
+ return records
109
+ .filter((record) => isRecord(record) && typeof record.id === 'string' && typeof record.body === 'string' && record.body.trim() && record.stale !== true)
110
+ .map((record) => ({
111
+ ...record,
112
+ delivery: isInlineAlways(record) ? 'inline' : 'on-demand',
113
+ }));
114
+ }
115
+
116
+ /** True when a memory's scope covers the folder: an all-projects scope, or the folder's (or an ancestor's) name. */
117
+ export function scopeCovers(scope, cwd) {
118
+ const normalized = String(scope ?? '').trim().toLowerCase();
119
+ if (GLOBAL_SCOPES.has(normalized)) return true;
120
+ if (!cwd) return false;
121
+ const parts = String(cwd).toLowerCase().split('/').filter(Boolean);
122
+ return parts.includes(normalized) || basename(String(cwd)).toLowerCase() === normalized;
123
+ }
124
+
125
+ function scoreRecords(records, { prompt = '', cwd, seen = new Set() } = {}) {
126
+ const promptWords = words(prompt);
127
+ const scored = [];
128
+ for (const record of records ?? []) {
129
+ if (!isRecord(record) || seen.has(record.id) || !scopeCovers(record.scope, cwd)) continue;
130
+ const global = GLOBAL_SCOPES.has(String(record.scope ?? '').trim().toLowerCase());
131
+ const searchable = [record.title, record.body, ...(Array.isArray(record.tags) ? record.tags : [])].filter(Boolean).join(' ');
132
+ let overlap = 0;
133
+ for (const word of words(searchable)) if (promptWords.has(word)) overlap += 1;
134
+ const cls = classOf(record).toLowerCase();
135
+ const isPref = PREFERENCE_CLASSES.has(cls) || isInlineAlways(record);
136
+ const score = (record.pinned === true ? 100 : 0) + (global ? 0 : 20) + (record.pinned !== true && isPref ? 10 : 0) + overlap * 5;
137
+ if (score > 0) scored.push({ record, score });
138
+ }
139
+ scored.sort((a, b) => b.score - a.score || String(b.record.updatedAt ?? '').localeCompare(String(a.record.updatedAt ?? '')));
140
+ return scored.map((entry) => entry.record);
141
+ }
142
+
143
+ /**
144
+ * The memories to recall for one prompt in one folder, best first, minus `seen` ids. Each scores for being pinned,
145
+ * scoped to this folder, a preference, and for every word it shares with the prompt; a zero score is left out.
146
+ */
147
+ export function selectMemories(records, { prompt = '', cwd, seen = new Set(), maxItems = DEFAULT_MAX_ITEMS, maxBytes = DEFAULT_MAX_BYTES } = {}) {
148
+ const scored = scoreRecords(records, { prompt, cwd, seen });
149
+ const chosen = [];
150
+ let bytes = 0;
151
+ for (const record of scored) {
152
+ if (chosen.length >= maxItems) break;
153
+ const size = Buffer.byteLength(record.body.trim(), 'utf8');
154
+ if (bytes + size > maxBytes) continue;
155
+ bytes += size;
156
+ chosen.push(record);
157
+ }
158
+ return chosen;
159
+ }
160
+
161
+ const LABELS = {
162
+ style: 'Preference',
163
+ workflow: 'Preference',
164
+ preference: 'Preference',
165
+ decision: 'Decision',
166
+ fact: 'Project fact',
167
+ 'repo-rule': 'Project fact',
168
+ failure: 'Project fact',
169
+ 'model-performance': 'Project fact',
170
+ };
171
+
172
+ function escapeSystemReminder(text) {
173
+ return `${text.slice(0, -'</system-reminder>'.length).replaceAll('</system-reminder>', '<\\/system-reminder>')}</system-reminder>`;
174
+ }
175
+
176
+ /** The model-visible reminder for a set of memories (literal `</system-reminder>` in a memory is escaped). */
177
+ export function renderRecall(memories) {
178
+ const lines = memories.map((memory) => {
179
+ const cls = classOf(memory);
180
+ const label = LABELS[cls] ?? 'Note';
181
+ const scope = GLOBAL_SCOPES.has(String(memory.scope ?? '').trim().toLowerCase()) ? '' : ` · ${memory.scope}`;
182
+ return `- [${label}${scope}] ${oneLine(memory.body)}`;
183
+ });
184
+ const text = [
185
+ '<system-reminder>',
186
+ 'Picasso memory: things the user saved for you to remember. Follow them as the user\'s standing preferences and facts; when the current request conflicts, the request wins. Do not mention this note unless asked.',
187
+ ...lines,
188
+ '</system-reminder>',
189
+ ].join('\n');
190
+ return escapeSystemReminder(text);
191
+ }
192
+
193
+ /** A frozen user-role message shaped like dsh-llm's `createUserMessage` output. */
194
+ export function recallMessage(memories) {
195
+ return Object.freeze({
196
+ role: 'user',
197
+ content: Object.freeze([Object.freeze({ type: 'text', text: renderRecall(memories) })]),
198
+ source: Object.freeze({ kind: SOURCE_KIND, form: 'recall', ids: Object.freeze(memories.map((memory) => memory.id)) }),
199
+ id: randomUUID(),
200
+ });
201
+ }
202
+
203
+ function formatInlineLine(record) {
204
+ return `- [${classOf(record)}] ${oneLine(record.body)}`;
205
+ }
206
+
207
+ function formatIndexLine(record) {
208
+ const titleOrPreview = oneLine(record.title || oneLine(record.body).slice(0, 60));
209
+ const scope = String(record.scope ?? '').trim() || 'global';
210
+ return `- ${record.id} · ${classOf(record)} · ${titleOrPreview} · ${scope}`;
211
+ }
212
+
213
+ const TIER1_FOOTER = 'Use recall({ ids: ["<id>"] }) or recall({ query: "<topic>" }) to load full memory bodies on demand.';
214
+
215
+ /** Renders the Two-Tier Tier 1 `<system-reminder>` text from partitioned `inlineRecords` and `indexRecords`. */
216
+ export function renderTier1Recall(inlineRecords = [], indexRecords = []) {
217
+ const lines = [
218
+ '<system-reminder>',
219
+ 'Picasso memory:',
220
+ ...inlineRecords.map(formatInlineLine),
221
+ ...indexRecords.map(formatIndexLine),
222
+ ];
223
+ if (indexRecords.length > 0) {
224
+ lines.push(TIER1_FOOTER);
225
+ }
226
+ lines.push('</system-reminder>');
227
+ return escapeSystemReminder(lines.join('\n'));
228
+ }
229
+
230
+ /**
231
+ * Selects and partitions relevant memories for a turn into `inlineRecords` (`isInlineAlways(r)`) and
232
+ * `indexRecords` (`!isInlineAlways(r)`), strictly enforcing `maxItems` (`MAX_RECALL = 12`) and
233
+ * `maxBytes` (`MAX_TIER1_BYTES = 1024`) on the rendered Tier 1 reminder.
234
+ */
235
+ export function selectForTurn(
236
+ records,
237
+ {
238
+ prompt = '',
239
+ cwd,
240
+ seen = new Set(),
241
+ session,
242
+ maxItems = MAX_RECALL,
243
+ maxBytes = MAX_TIER1_BYTES,
244
+ } = {},
245
+ ) {
246
+ const effectiveMaxBytes = Math.min(Number.isInteger(maxBytes) && maxBytes > 0 ? maxBytes : MAX_TIER1_BYTES, MAX_TIER1_BYTES);
247
+ const shown = session ? recalledIn(session) : undefined;
248
+ const combinedSeen = new Set(seen);
249
+ if (shown) {
250
+ for (const id of shown) combinedSeen.add(id);
251
+ }
252
+ const scored = scoreRecords(records, { prompt, cwd, seen: combinedSeen });
253
+ const inlineCandidates = scored.filter((r) => isInlineAlways(r));
254
+ const indexCandidates = scored.filter((r) => !isInlineAlways(r));
255
+
256
+ const inlineRecords = [];
257
+ const indexRecords = [];
258
+
259
+ for (const record of inlineCandidates) {
260
+ if (inlineRecords.length + indexRecords.length >= maxItems) break;
261
+ const candidateInline = [...inlineRecords, record];
262
+ const candidateText = renderTier1Recall(candidateInline, indexRecords);
263
+ if (Buffer.byteLength(candidateText, 'utf8') > effectiveMaxBytes) continue;
264
+ inlineRecords.push(record);
265
+ }
266
+
267
+ for (const record of indexCandidates) {
268
+ if (inlineRecords.length + indexRecords.length >= maxItems) break;
269
+ const candidateIndex = [...indexRecords, record];
270
+ const candidateText = renderTier1Recall(inlineRecords, candidateIndex);
271
+ if (Buffer.byteLength(candidateText, 'utf8') > effectiveMaxBytes) continue;
272
+ indexRecords.push(record);
273
+ }
274
+
275
+ if (shown) {
276
+ for (const record of inlineRecords) shown.add(record.id);
277
+ }
278
+
279
+ const chosen = [...inlineRecords, ...indexRecords];
280
+ const text = chosen.length > 0 ? renderTier1Recall(inlineRecords, indexRecords) : '';
281
+ const source = Object.freeze({
282
+ kind: SOURCE_KIND,
283
+ form: indexRecords.length > 0 ? 'index' : 'recall',
284
+ ids: Object.freeze([...inlineRecords.map((r) => r.id), ...indexRecords.map((r) => r.id)]),
285
+ inlineIds: Object.freeze(inlineRecords.map((r) => r.id)),
286
+ indexIds: Object.freeze(indexRecords.map((r) => r.id)),
287
+ availableCount: inlineRecords.length + indexRecords.length,
288
+ });
289
+ const message = chosen.length > 0
290
+ ? Object.freeze({
291
+ role: 'user',
292
+ content: Object.freeze([Object.freeze({ type: 'text', text })]),
293
+ source,
294
+ id: randomUUID(),
295
+ })
296
+ : undefined;
297
+
298
+ Object.defineProperties(chosen, {
299
+ inlineRecords: { value: inlineRecords, enumerable: false },
300
+ indexRecords: { value: indexRecords, enumerable: false },
301
+ text: { value: text, enumerable: false },
302
+ source: { value: source, enumerable: false },
303
+ message: { value: message, enumerable: false },
304
+ });
305
+ return chosen;
306
+ }
307
+
308
+ const textOf = (message) => (Array.isArray(message?.content) ? message.content : [])
309
+ .map((part) => (part?.type === 'text' && typeof part.text === 'string' ? part.text : ''))
310
+ .join('\n');
311
+ const isPrompt = (message) => message?.role === 'user' && (message.source === undefined || message.source?.kind === 'user');
312
+ const isRecall = (message) => message?.source?.kind === SOURCE_KIND;
313
+
314
+ function historyOf(agentOrSession) {
315
+ try {
316
+ if (Array.isArray(agentOrSession)) return agentOrSession;
317
+ const visible =
318
+ agentOrSession?.context?.messages ??
319
+ agentOrSession?.messages ??
320
+ agentOrSession?.session?.context?.messages ??
321
+ agentOrSession?.session?.messages;
322
+ return Array.isArray(visible) ? visible : [];
323
+ } catch {
324
+ return [];
325
+ }
326
+ }
327
+
328
+ /** All memory ids surfaced in Tier 1 (inline or index) in an agent's message history. */
329
+ function tier1SeenInHistory(messages) {
330
+ const ids = new Set();
331
+ for (const message of messages ?? []) {
332
+ if (isRecall(message)) {
333
+ for (const id of message.source.ids ?? []) ids.add(id);
334
+ }
335
+ }
336
+ return ids;
337
+ }
338
+
339
+ /** Memory ids whose FULL bodies were already shown in `messages` (inlineIds in two-tier, or ids in legacy recall). */
340
+ function fullBodyShownInHistory(messages) {
341
+ const ids = new Set();
342
+ for (const message of messages ?? []) {
343
+ if (isRecall(message)) {
344
+ const fullIds = Array.isArray(message.source.inlineIds)
345
+ ? message.source.inlineIds
346
+ : (message.source.form === 'index' ? [] : (message.source.ids ?? []));
347
+ for (const id of fullIds) ids.add(id);
348
+ }
349
+ }
350
+ return ids;
351
+ }
352
+
353
+ const shownBySession = new WeakMap();
354
+
355
+ function resolveSessionObject(target) {
356
+ if (!target || typeof target !== 'object') return undefined;
357
+ if (target.session && typeof target.session === 'object') return target.session;
358
+ if (target.agent && typeof target.agent === 'object') {
359
+ return target.agent.session && typeof target.agent.session === 'object' ? target.agent.session : target.agent;
360
+ }
361
+ return target;
362
+ }
363
+
364
+ /**
365
+ * Returns the `Set` of memory IDs already shown in full in the given session/agent (or message array).
366
+ * Survives Host restarts when reconstructed from session message history.
367
+ */
368
+ export function recalledIn(target) {
369
+ if (Array.isArray(target)) {
370
+ return fullBodyShownInHistory(target);
371
+ }
372
+ const key = resolveSessionObject(target);
373
+ if (!key) return new Set();
374
+ let set = shownBySession.get(key);
375
+ if (!set) {
376
+ set = fullBodyShownInHistory(historyOf(target));
377
+ shownBySession.set(key, set);
378
+ }
379
+ return set;
380
+ }
381
+
382
+ /**
383
+ * Executes a Tier 2 on-demand `recall({ ids, query, limit }, exec)` request against `file` (or `records`).
384
+ * Deduplicates memories already in the session's `shown` Set (`recalledIn(exec?.agent?.session)`).
385
+ */
386
+ export function recallMemories(fileOrRecords, args = {}, exec = {}, { defaultSession, invalidate, notesDir } = {}) {
387
+ const file = typeof fileOrRecords === 'string' ? fileOrRecords : undefined;
388
+ const memories = Array.isArray(fileOrRecords) ? fileOrRecords : readMemories(file);
389
+ // The librarian's project notes (packages/picasso-librarian) are reachable here, on demand only: they are never
390
+ // in the Tier-1 reminder or the index lines, and the tool's schema is unchanged.
391
+ const notes = projectNoteRecords(notesDir ?? (file ? librarianNotesDir(file) : undefined));
392
+ const records = notes.length === 0 ? memories : [...memories, ...notes];
393
+ const limit = Number.isInteger(args?.limit) && args.limit > 0 ? args.limit : MAX_RECALL;
394
+ const requestedIds = Array.isArray(args?.ids) ? args.ids.map((id) => String(id).trim()).filter(Boolean) : [];
395
+ const query = typeof args?.query === 'string' ? args.query.trim() : '';
396
+
397
+ const matched = [];
398
+ const matchedIdSet = new Set();
399
+
400
+ for (const id of requestedIds) {
401
+ if (matchedIdSet.has(id)) continue;
402
+ const found = records.find((record) => record.id === id);
403
+ if (found) {
404
+ matched.push(found);
405
+ matchedIdSet.add(found.id);
406
+ }
407
+ }
408
+
409
+ if (query.length > 0) {
410
+ const qLower = query.toLowerCase();
411
+ const qWords = words(query);
412
+ const cwd = typeof exec?.agent?.cwd === 'string' && exec.agent.cwd ? exec.agent.cwd : undefined;
413
+ const queryScored = [];
414
+
415
+ for (const record of records) {
416
+ if (matchedIdSet.has(record.id)) continue;
417
+ if (cwd && !scopeCovers(record.scope, cwd) && !String(record.scope ?? '').toLowerCase().includes(qLower)) {
418
+ continue;
419
+ }
420
+ const tags = Array.isArray(record.tags) ? record.tags : [];
421
+ const haystack = [record.id, record.title, record.body, record.scope, classOf(record), ...tags]
422
+ .filter(Boolean)
423
+ .join(' ')
424
+ .toLowerCase();
425
+ const substringMatch = haystack.includes(qLower);
426
+ let overlap = 0;
427
+ if (qWords.size > 0) {
428
+ const recordWords = words(haystack);
429
+ for (const word of qWords) if (recordWords.has(word)) overlap += 1;
430
+ }
431
+ if (!substringMatch && overlap === 0) continue;
432
+ const score = (substringMatch ? 20 : 0) + overlap * 5 + (record.pinned === true ? 2 : 0);
433
+ queryScored.push({ record, score });
434
+ }
435
+
436
+ queryScored.sort((a, b) => b.score - a.score || String(b.record.updatedAt ?? '').localeCompare(String(a.record.updatedAt ?? '')));
437
+ for (const { record } of queryScored) {
438
+ matched.push(record);
439
+ matchedIdSet.add(record.id);
440
+ }
441
+ }
442
+
443
+ const selected = matched.slice(0, limit);
444
+ const sessionTarget = exec?.agent?.session ?? exec?.agent ?? exec?.session ?? defaultSession;
445
+ const shown = sessionTarget ? recalledIn(sessionTarget) : new Set();
446
+ const now = new Date().toISOString();
447
+ const lines = [];
448
+ const items = [];
449
+ const loadedIds = [];
450
+ const dedupedIds = [];
451
+ let touchedFile = false;
452
+
453
+ for (const record of selected) {
454
+ const cls = classOf(record);
455
+ const scope = String(record.scope ?? '').trim() || 'global';
456
+ if (shown.has(record.id)) {
457
+ const note = `[${record.id}] already loaded in this session`;
458
+ lines.push(note);
459
+ dedupedIds.push(record.id);
460
+ items.push({ id: record.id, class: cls, scope, deduplicated: true, text: note });
461
+ } else {
462
+ shown.add(record.id);
463
+ if (!record.id.startsWith(PROJECT_NOTES_PREFIX)) {
464
+ record.lastUsedAt = now;
465
+ touchedFile = true;
466
+ }
467
+ const line = `[${record.id}] (${cls}, ${scope}): ${record.body.trim()}`;
468
+ lines.push(line);
469
+ loadedIds.push(record.id);
470
+ items.push({ id: record.id, class: cls, scope, body: record.body.trim(), lastUsedAt: now, deduplicated: false, text: line });
471
+ }
472
+ }
473
+
474
+ if (touchedFile && file) {
475
+ try {
476
+ if (touchLastUsed(file, loadedIds.filter((id) => !id.startsWith(PROJECT_NOTES_PREFIX)), now)) invalidate?.();
477
+ } catch {
478
+ // Best-effort timestamp update (lock timeout, read-only fixtures): the recall itself already succeeded.
479
+ }
480
+ }
481
+
482
+ const text = lines.length > 0 ? lines.join('\n') : 'No matching memories found.';
483
+ // Plain JSON only: dsh rejects a tool output that is not lossless JSON (a method here made every recall fail).
484
+ return { text, content: [{ type: 'text', text }], items, loadedIds, dedupedIds };
485
+ }
486
+
487
+ /** Recall ids of the librarian's project notes: `project-notes:<slug>-<hash>`. */
488
+ export const PROJECT_NOTES_PREFIX = 'project-notes:';
489
+
490
+ /** `PICASSO_LIBRARIAN_NOTES_DIR`, else `<dir of the memory file>/librarian/notes` (the memory file sits in the Picasso home). */
491
+ export function librarianNotesDir(memoryFile, env = process.env) {
492
+ const explicit = typeof env.PICASSO_LIBRARIAN_NOTES_DIR === 'string' ? env.PICASSO_LIBRARIAN_NOTES_DIR.trim() : '';
493
+ if (explicit) return explicit;
494
+ return memoryFile ? join(dirname(memoryFile), 'librarian', 'notes') : undefined;
495
+ }
496
+
497
+ /** Each notes file as a recall record (class `project`, scoped to the project folder's name). */
498
+ export function projectNoteRecords(dir) {
499
+ if (!dir) return [];
500
+ let names;
501
+ try {
502
+ names = readdirSync(dir).filter((name) => name.endsWith('.md')).sort();
503
+ } catch {
504
+ return [];
505
+ }
506
+ const out = [];
507
+ for (const name of names) {
508
+ let text;
509
+ try {
510
+ text = readFileSync(join(dir, name), 'utf8').trim();
511
+ } catch {
512
+ continue;
513
+ }
514
+ const title = /^# Project notes · (.+)$/m.exec(text)?.[1]?.trim();
515
+ const path = /^Path: (.+)$/m.exec(text)?.[1]?.trim();
516
+ if (!title || !path || text.length === 0) continue;
517
+ out.push({ id: `${PROJECT_NOTES_PREFIX}${name.slice(0, -3)}`, title: `Project notes · ${title}`, body: text, scope: basename(path), memoryClass: 'project', tags: ['project-notes', title, path], pinned: false });
518
+ }
519
+ return out;
520
+ }
521
+
522
+ class MemoryService {
523
+ constructor({ file, load, defaultSession, invalidate }) {
524
+ this.file = file;
525
+ this.load = load;
526
+ this.defaultSession = defaultSession;
527
+ this.invalidate = invalidate;
528
+ }
529
+
530
+ list() {
531
+ return listMemories(this.load());
532
+ }
533
+
534
+ recall(args = {}, exec = {}) {
535
+ return recallMemories(this.file ?? this.load(), args, exec, {
536
+ defaultSession: this.defaultSession,
537
+ invalidate: this.invalidate,
538
+ });
539
+ }
540
+ }
541
+
542
+ Object.defineProperty(MemoryService.prototype, REMOTE_METHOD_DESCRIPTOR, {
543
+ configurable: true,
544
+ value: Object.freeze({
545
+ version: 1,
546
+ methods: Object.freeze(['list', 'recall'].map((method) => Object.freeze({ method, invocation: Object.freeze({ kind: 'direct' }) }))),
547
+ }),
548
+ });
549
+
550
+ export function apply(ctx, config = {}) {
551
+ const file = config.file ?? process.env[FILE_ENV];
552
+ const maxItems = Number.isInteger(config.maxItems) && config.maxItems > 0 ? config.maxItems : MAX_RECALL;
553
+ const maxBytes = Number.isInteger(config.maxBytes) && config.maxBytes > 0
554
+ ? Math.min(config.maxBytes, MAX_TIER1_BYTES)
555
+ : MAX_TIER1_BYTES;
556
+ /** Per agent: memory ids already surfaced in Tier 1 (`agent/pre-step`) this Host lifetime. */
557
+ const tier1SeenByAgent = new WeakMap();
558
+ const defaultSession = {};
559
+ let cache = { mtimeMs: -1, records: [] };
560
+ const invalidate = () => { cache.mtimeMs = -1; };
561
+ const load = () => {
562
+ if (Array.isArray(config.records)) return listMemories(config.records);
563
+ if (!file) return [];
564
+ let mtimeMs;
565
+ try {
566
+ mtimeMs = statSync(file).mtimeMs;
567
+ } catch (error) {
568
+ if (error?.code === 'ENOENT') return [];
569
+ throw error;
570
+ }
571
+ // A newer or malformed file throws here and is never cached as "no memories".
572
+ if (mtimeMs !== cache.mtimeMs) cache = { mtimeMs, records: readMemories(file) };
573
+ return cache.records;
574
+ };
575
+
576
+ const service = new MemoryService({ file, load, defaultSession, invalidate });
577
+ service.typertRemote = Object.freeze({ service, serviceKey: SERVICE_KEY, namespace: SERVICE_KEY });
578
+ ctx.provide?.(SERVICE_KEY, service);
579
+ // dsh runs cordis with strict inject: a bare `ctx.rpc` read throws `cannot get property "rpc" without inject`
580
+ // (even through `?.`) and kills the whole plugin before its hooks and the remember/recall tools register.
581
+ // Declaring `inject: ['rpc']` would instead make `rpc` a REQUIRED service and leave the plugin pending, so read it
582
+ // through `ctx.get` (never throws). `memory/list` is also exposed through `typertRemote` above.
583
+ ctx.get?.('rpc')?.register?.('memory/list', () => service.list());
584
+
585
+ ctx.on('agent/pre-step', async ({ agent, messages, step, signal }, next) => {
586
+ const decision = await next();
587
+ if (step !== 1 || decision?.kind === 'reject' || !Array.isArray(decision?.messages) || decision.messages.length === 0) return decision;
588
+ if (decision.messages.some(isRecall)) return decision;
589
+ let records;
590
+ try {
591
+ records = load();
592
+ } catch {
593
+ // `memory/newer-schema` or `memory/invalid`: inject nothing. `recall`, `remember` and `memory/list` report the error.
594
+ return decision;
595
+ }
596
+ if (records.length === 0) return decision;
597
+ const prompt = decision.messages.filter(isPrompt).map(textOf).join('\n');
598
+ if (!prompt.trim()) return decision;
599
+ let cwd;
600
+ try {
601
+ cwd = await ctx.get?.('workingDirectory')?.ensure?.(agent, signal);
602
+ } catch {
603
+ cwd = undefined;
604
+ }
605
+ if (typeof cwd !== 'string') cwd = typeof agent?.cwd === 'string' ? agent.cwd : undefined;
606
+
607
+ const history = historyOf(agent);
608
+ let tier1Seen = agent && typeof agent === 'object' ? tier1SeenByAgent.get(agent) : undefined;
609
+ if (!tier1Seen) {
610
+ tier1Seen = tier1SeenInHistory(history);
611
+ if (agent && typeof agent === 'object') tier1SeenByAgent.set(agent, tier1Seen);
612
+ }
613
+
614
+ const sessionObj = resolveSessionObject(agent) ?? defaultSession;
615
+ const shownInFull = recalledIn(sessionObj);
616
+ for (const id of fullBodyShownInHistory(history)) shownInFull.add(id);
617
+
618
+ const turnSelection = selectForTurn(records, {
619
+ prompt,
620
+ cwd,
621
+ seen: tier1Seen,
622
+ session: sessionObj,
623
+ maxItems,
624
+ maxBytes,
625
+ });
626
+ if (turnSelection.length === 0 || !turnSelection.message) return decision;
627
+ signal?.throwIfAborted?.();
628
+
629
+ // Mark all surfaced records in `tier1Seen` so Tier 1 doesn't repeat on subsequent turns,
630
+ // while ONLY `inlineRecords` are marked in `recalledIn(agent.session)` (`shownInFull`).
631
+ for (const memory of turnSelection) tier1Seen.add(memory.id);
632
+
633
+ const lastClaimed = decision.messages.findLastIndex((message) => messages?.includes?.(message));
634
+ return { ...decision, messages: decision.messages.toSpliced(lastClaimed + 1, 0, turnSelection.message) };
635
+ });
636
+
637
+ const registeredTargets = new WeakSet();
638
+ const registerToolsOn = (tools) => {
639
+ if (!tools || typeof tools.register !== 'function' || registeredTargets.has(tools)) return;
640
+ registeredTargets.add(tools);
641
+ // dsh refuses a second tool with the same name and rolls back everything this inject callback registered.
642
+ // picasso-lean-context's fallback `recall` can load first, so registering ours anyway threw and took
643
+ // `remember` with it (every CLI remember was "not registered for this agent"). Skip a name already taken.
644
+ const register = (definition) => {
645
+ let taken;
646
+ try {
647
+ taken = typeof tools.get === 'function' ? tools.get(definition.name) : undefined;
648
+ } catch {
649
+ taken = undefined;
650
+ }
651
+ if (taken === undefined) tools.register(definition);
652
+ };
653
+ register({
654
+ name: REMEMBER_TOOL,
655
+ description:
656
+ 'Save something the user asked you to remember — a preference, decision, or project fact — into Picasso memory so later threads recall it. Use sparingly: only when asked, or for a durable cross-session fact; never secrets, credentials, or transient task state.',
657
+ parameters: {
658
+ type: 'object',
659
+ properties: {
660
+ body: { type: 'string', description: 'The memory, one short sentence.' },
661
+ scope: { type: 'string', description: 'Folder/project name it applies to, or "workspace" for all projects (default: the current folder).' },
662
+ memoryClass: { type: 'string', enum: MEMORY_CLASSES, description: 'Memory class; default "fact".' },
663
+ pinned: { type: 'boolean', description: 'Pinned memories rank first in recall; default false.' },
664
+ },
665
+ required: ['body'],
666
+ additionalProperties: false,
667
+ },
668
+ output: {
669
+ schema: { type: 'object' },
670
+ render: (_args, value) => [{ type: 'text', text: value?.status === 'saved' ? `Remembered (id ${value.id}, scope ${value.scope}).` : `Memory updated (id ${value?.id}).` }],
671
+ },
672
+ isConcurrencySafe: () => false,
673
+ execute(args, exec) {
674
+ return rememberWrite(file, args, exec, invalidate);
675
+ },
676
+ });
677
+
678
+ register({
679
+ name: RECALL_TOOL,
680
+ description:
681
+ 'Load full bodies of saved memories on demand by id list or search query. Memories already loaded in full this session are not repeated.',
682
+ parameters: {
683
+ type: 'object',
684
+ properties: {
685
+ ids: {
686
+ type: 'array',
687
+ items: { type: 'string' },
688
+ description: 'Memory IDs to load in full.',
689
+ },
690
+ query: {
691
+ type: 'string',
692
+ description: 'Search query across memory title, body, tags, and scope.',
693
+ },
694
+ limit: {
695
+ type: 'number',
696
+ description: 'Maximum number of memories to return.',
697
+ },
698
+ },
699
+ additionalProperties: false,
700
+ },
701
+ output: {
702
+ schema: { type: 'object' },
703
+ render: (_args, value) => [{ type: 'text', text: typeof value === 'string' ? value : String(value?.text ?? '') }],
704
+ },
705
+ isConcurrencySafe: () => true,
706
+ execute(args, exec) {
707
+ return recallMemories(file ?? load(), args, exec, { defaultSession, invalidate });
708
+ },
709
+ });
710
+ };
711
+
712
+ // N9 + Pillar 4 — register `remember` and `recall` on `ctx.tools` (both via `ctx.inject(['tools'])` and direct `ctx.tools`).
713
+ // Under dsh's strict inject a bare `ctx.tools` read throws unless `tools` is declared, so the direct read is
714
+ // only the fallback for a context without `inject` (unit-test fakes).
715
+ if (typeof ctx.inject === 'function') {
716
+ ctx.inject(['tools'], (inner) => {
717
+ registerToolsOn(inner?.tools ?? ctx.get?.('tools'));
718
+ });
719
+ } else {
720
+ registerToolsOn(ctx.tools ?? ctx.get?.('tools'));
721
+ }
722
+ }
723
+
724
+ /**
725
+ * One `remember` call → the memory file, read-modify-write under `<file>.lock` and an atomic rename. A live record
726
+ * with the same body and scope is refreshed (new timestamp, class/pinned updated) instead of duplicated.
727
+ * Returns `{status: 'saved'|'updated', id, scope}`. Throws `memory/newer-schema` / `memory/invalid` for a file it
728
+ * must not rewrite.
729
+ */
730
+ export function rememberWrite(file, args, exec, invalidate) {
731
+ if (!file) throw new Error(`${REMEMBER_TOOL}: ${FILE_ENV} is not configured for this engine`);
732
+ const body = String(args?.body ?? '').trim();
733
+ if (!body) throw new Error(`${REMEMBER_TOOL}: 'body' is required`);
734
+ if (Buffer.byteLength(body, 'utf8') > REMEMBER_MAX_BODY) throw new Error(`${REMEMBER_TOOL}: memory is over ${REMEMBER_MAX_BODY} bytes — keep it to one short sentence`);
735
+ const memoryClass = args?.memoryClass === undefined ? 'fact' : String(args.memoryClass);
736
+ if (!MEMORY_CLASSES.includes(memoryClass)) throw new Error(`${REMEMBER_TOOL}: memoryClass must be one of ${MEMORY_CLASSES.join(', ')}`);
737
+ const cwd = typeof exec?.agent?.cwd === 'string' && exec.agent.cwd ? exec.agent.cwd : undefined;
738
+ const scope = String(args?.scope ?? '').trim() || (cwd ? basename(cwd).toLowerCase() : 'workspace');
739
+ const sameScope = (value) => String(value ?? '').trim().toLowerCase() === scope.toLowerCase();
740
+ const now = new Date().toISOString();
741
+
742
+ const result = mutateMemoryFile(file, (loaded) => {
743
+ if (loaded.format === 'v0') {
744
+ const rows = loaded.raw;
745
+ const existing = rows.find((row) => isLiveLegacyRow(row) && row.body.trim() === body && sameScope(row.scope));
746
+ if (existing) {
747
+ existing.memoryClass = memoryClass;
748
+ if (args?.pinned !== undefined) existing.pinned = args.pinned === true;
749
+ existing.updatedAt = now;
750
+ return { value: rows, result: { status: 'updated', id: existing.id, scope } };
751
+ }
752
+ const row = { id: randomUUID(), body, scope, source: 'agent', memoryClass, pinned: args?.pinned === true, updatedAt: now };
753
+ rows.push(row);
754
+ return { value: rows, result: { status: 'saved', id: row.id, scope } };
755
+ }
756
+
757
+ const records = loaded.raw.records;
758
+ const existing = records.find((record) => {
759
+ const view = fromVectorRecord(record);
760
+ return view !== undefined && view.body.trim() === body && sameScope(view.scope);
761
+ });
762
+ if (existing) {
763
+ const cliClass = toCliClass(memoryClass);
764
+ if (existing.metadata.memoryClass !== cliClass) {
765
+ existing.metadata.memoryClass = cliClass;
766
+ existing.namespace = namespaceFor(accountOf(existing.namespace), cliClass);
767
+ existing.vector = hashEmbeddingVector({ text: existing.metadata.body, purpose: 'memory-write', memoryClass: cliClass, namespace: existing.namespace });
768
+ existing.metadata.embedding = hashEmbeddingMetadata(now);
769
+ }
770
+ if (args?.pinned !== undefined) existing.metadata.pinned = args.pinned === true;
771
+ existing.metadata.lastObservedAt = now;
772
+ return { value: loaded.raw, result: { status: 'updated', id: existing.id, scope } };
773
+ }
774
+ const sessionId = String(exec?.agent?.session?.id ?? exec?.agent?.id ?? '').trim() || 'dsh';
775
+ const record = newVectorRecord({ body, scope, memoryClass, pinned: args?.pinned === true, now, sessionId });
776
+ records.push(record);
777
+ return { value: loaded.raw, result: { status: 'saved', id: record.id, scope } };
778
+ });
779
+ invalidate?.();
780
+ return result;
781
+ }
782
+
783
+ // ---------------------------------------------------------------------------------------------------------------
784
+ // File format (v0 / v1 / v2)
785
+ // ---------------------------------------------------------------------------------------------------------------
786
+
787
+ export const MEMORY_SCHEMA_VERSION = 2;
788
+ export const NEWER_SCHEMA_CODE = 'memory/newer-schema';
789
+ export const INVALID_FILE_CODE = 'memory/invalid';
790
+ const LOCAL_ACCOUNT = 'local';
791
+ const HASH_EMBEDDING_PROVIDER = 'picasso-memory';
792
+ const HASH_EMBEDDING_MODEL = 'picasso-deterministic-hash-embedding';
793
+ const HASH_EMBEDDING_DIMENSIONS = 32;
794
+ const CLI_CLASS_LEAVES = {
795
+ fact: 'facts',
796
+ decision: 'decisions',
797
+ failure: 'failures',
798
+ workflow: 'workflows',
799
+ repo_rule: 'repo_rules',
800
+ model_performance: 'model_performance',
801
+ };
802
+
803
+ /** A memory file this build must not read as empty or rewrite: `code` is `memory/newer-schema` or `memory/invalid`. */
804
+ export class MemoryFileError extends Error {
805
+ constructor(code, file, message, { found, supported } = {}) {
806
+ super(message);
807
+ this.name = 'MemoryFileError';
808
+ this.code = code;
809
+ this.file = file;
810
+ if (found !== undefined) this.found = found;
811
+ if (supported !== undefined) this.supported = supported;
812
+ }
813
+ }
814
+
815
+ /**
816
+ * Reads and classifies the memory file: `{ format: 'missing'|'v0'|'v1'|'v2', raw, records }`, where `records` are
817
+ * live records in this plugin's view (`{id, body, scope, memoryClass, pinned, …}`; tombstones left out).
818
+ * Throws `MemoryFileError` for a newer schema or a malformed file.
819
+ */
820
+ export function loadMemoryFile(file) {
821
+ let text;
822
+ try {
823
+ text = readFileSync(file, 'utf8');
824
+ } catch (error) {
825
+ if (error?.code === 'ENOENT') return { format: 'missing', raw: undefined, records: [] };
826
+ throw error;
827
+ }
828
+ let parsed;
829
+ try {
830
+ parsed = JSON.parse(text);
831
+ } catch {
832
+ throw invalid(file, 'malformed JSON');
833
+ }
834
+ if (Array.isArray(parsed)) {
835
+ return { format: 'v0', raw: parsed, records: parsed.filter(isLiveLegacyRow) };
836
+ }
837
+ if (!isRecord(parsed)) throw invalid(file, 'not a memory file');
838
+ const version = 'schemaVersion' in parsed ? parsed.schemaVersion : parsed.version;
839
+ if (!Number.isInteger(version) || version < 0) throw invalid(file, 'missing schemaVersion');
840
+ if (version > MEMORY_SCHEMA_VERSION) {
841
+ throw new MemoryFileError(
842
+ NEWER_SCHEMA_CODE,
843
+ file,
844
+ `${NEWER_SCHEMA_CODE}: ${file} was written by a newer Picasso (schema ${version}; this version reads up to ${MEMORY_SCHEMA_VERSION}). Update Picasso.`,
845
+ { found: version, supported: MEMORY_SCHEMA_VERSION },
846
+ );
847
+ }
848
+ const isV2 = 'schemaVersion' in parsed && version === MEMORY_SCHEMA_VERSION;
849
+ const isV1 = !('schemaVersion' in parsed) && version === 1;
850
+ if ((!isV2 && !isV1) || !Array.isArray(parsed.records)) throw invalid(file, `unsupported schema ${version}`);
851
+ parsed.records.forEach((record, index) => {
852
+ if (!isRecord(record) || typeof record.id !== 'string' || typeof record.namespace !== 'string' || !Array.isArray(record.vector) || !isRecord(record.metadata)) {
853
+ throw invalid(file, `record ${index} is not a VectorRecord`);
854
+ }
855
+ });
856
+ const records = parsed.records.map(fromVectorRecord).filter((record) => record !== undefined);
857
+ return { format: isV2 ? 'v2' : 'v1', raw: parsed, records };
858
+ }
859
+
860
+ /** Projects one v2 `VectorRecord` to this plugin's record view; `undefined` for a tombstone. */
861
+ export function fromVectorRecord(record) {
862
+ const metadata = isRecord(record?.metadata) ? record.metadata : {};
863
+ const attributes = isRecord(metadata.attributes) ? metadata.attributes : {};
864
+ if (typeof attributes.deletedAt === 'string' || typeof metadata.body !== 'string') return undefined;
865
+ const view = {
866
+ id: record.id,
867
+ body: metadata.body,
868
+ scope: typeof attributes.scope === 'string' ? attributes.scope : scopeFromNamespace(record.namespace),
869
+ source: typeof attributes.source === 'string' ? attributes.source : 'cli',
870
+ memoryClass: toPluginClass(metadata.memoryClass),
871
+ pinned: metadata.pinned === true,
872
+ updatedAt: metadata.lastObservedAt,
873
+ namespace: record.namespace,
874
+ };
875
+ if (typeof attributes.title === 'string') view.title = attributes.title;
876
+ if (Array.isArray(attributes.tags)) view.tags = attributes.tags;
877
+ if (attributes.stale === true) view.stale = true;
878
+ if (typeof attributes.lastUsedAt === 'string') view.lastUsedAt = attributes.lastUsedAt;
879
+ return view;
880
+ }
881
+
882
+ /**
883
+ * Under `<file>.lock`: load → `mutate(loaded)` → write. `mutate` returns `{ value, result }` where `value` is the
884
+ * raw file content in the loaded format (a v0 array, or a v1/v2 envelope). v0 is written back as v0; v1 and a
885
+ * missing file are written as v2 (a v1 original is first copied to `<file>.v1.bak`, once).
886
+ */
887
+ export function mutateMemoryFile(file, mutate) {
888
+ return withMemoryFileLock(file, (lock) => {
889
+ const loaded = loadMemoryFile(file);
890
+ if (loaded.format === 'missing') loaded.raw = { schemaVersion: MEMORY_SCHEMA_VERSION, records: [] };
891
+ const { value, result } = mutate(loaded);
892
+ let next = value;
893
+ if (loaded.format !== 'v0') {
894
+ const { version: _legacyVersion, ...rest } = value;
895
+ next = { ...rest, schemaVersion: MEMORY_SCHEMA_VERSION };
896
+ if (loaded.format === 'v1') backupOnce(file, `${file}.v1.bak`);
897
+ }
898
+ lock.assertHeld();
899
+ writeFileAtomicSync(file, `${JSON.stringify(next, null, 2)}\n`);
900
+ return result;
901
+ });
902
+ }
903
+
904
+ /** Sets `lastUsedAt` on recalled records; returns true when the file changed. */
905
+ function touchLastUsed(file, ids, now) {
906
+ if (ids.length === 0) return false;
907
+ const wanted = new Set(ids);
908
+ return mutateMemoryFile(file, (loaded) => {
909
+ let touched = false;
910
+ if (loaded.format === 'v0') {
911
+ for (const row of loaded.raw) {
912
+ if (isRecord(row) && wanted.has(row.id)) {
913
+ row.lastUsedAt = now;
914
+ touched = true;
915
+ }
916
+ }
917
+ } else {
918
+ for (const record of loaded.raw.records) {
919
+ if (wanted.has(record.id) && typeof record.metadata?.attributes?.deletedAt !== 'string') {
920
+ record.metadata.attributes = { ...(isRecord(record.metadata.attributes) ? record.metadata.attributes : {}), lastUsedAt: now };
921
+ touched = true;
922
+ }
923
+ }
924
+ }
925
+ return { value: loaded.raw, result: touched };
926
+ });
927
+ }
928
+
929
+ function isLiveLegacyRow(row) {
930
+ return isRecord(row) && typeof row.id === 'string' && typeof row.body === 'string' && row.body.trim() && row.stale !== true;
931
+ }
932
+
933
+ function invalid(file, detail) {
934
+ return new MemoryFileError(INVALID_FILE_CODE, file, `${INVALID_FILE_CODE}: ${file} is not a valid Picasso memory file: ${detail}`);
935
+ }
936
+
937
+ function toPluginClass(cls) {
938
+ return String(cls ?? 'fact').replaceAll('_', '-');
939
+ }
940
+
941
+ function toCliClass(cls) {
942
+ const normalized = String(cls ?? 'fact').trim().toLowerCase().replaceAll('-', '_');
943
+ if (normalized === 'style' || normalized in CLI_CLASS_LEAVES) return normalized;
944
+ return normalized === 'preference' ? 'style' : 'fact';
945
+ }
946
+
947
+ function accountOf(namespace) {
948
+ const match = /^account:([^/]+)\//u.exec(String(namespace ?? ''));
949
+ return match ? match[1] : (process.env.PICASSO_MEMORY_ACCOUNT_ID?.trim() || LOCAL_ACCOUNT);
950
+ }
951
+
952
+ function namespaceFor(account, cliClass) {
953
+ if (cliClass === 'style') return `account:${account}/style/general`;
954
+ return `account:${account}/projects/workspace:default/${CLI_CLASS_LEAVES[cliClass] ?? 'facts'}`;
955
+ }
956
+
957
+ function scopeFromNamespace(namespace) {
958
+ const match = /\/projects\/workspace:([^/]+)\//u.exec(String(namespace ?? ''));
959
+ return match && match[1] !== 'default' ? match[1] : 'workspace';
960
+ }
961
+
962
+ function hashEmbeddingMetadata(createdAt) {
963
+ return {
964
+ provider: HASH_EMBEDDING_PROVIDER,
965
+ model: HASH_EMBEDDING_MODEL,
966
+ dimensions: HASH_EMBEDDING_DIMENSIONS,
967
+ createdAt,
968
+ deterministicFallback: true,
969
+ credentialMode: 'local',
970
+ };
971
+ }
972
+
973
+ function newVectorRecord({ body, scope, memoryClass, pinned, now, sessionId }) {
974
+ const cliClass = toCliClass(memoryClass);
975
+ const namespace = namespaceFor(accountOf(undefined), cliClass);
976
+ return {
977
+ id: randomUUID(),
978
+ namespace,
979
+ vector: hashEmbeddingVector({ text: body, purpose: 'memory-write', memoryClass: cliClass, namespace }),
980
+ metadata: {
981
+ memoryClass: cliClass,
982
+ body,
983
+ provenance: { sessionId, eventIndex: 0 },
984
+ createdAt: now,
985
+ lastObservedAt: now,
986
+ stalenessScore: 0,
987
+ pinned,
988
+ embedding: hashEmbeddingMetadata(now),
989
+ attributes: { scope, source: 'agent' },
990
+ },
991
+ };
992
+ }
993
+
994
+ /**
995
+ * Byte-identical copy of `@picasso/memory` `hashEmbeddingVector` (the deterministic local embedding), so records this
996
+ * plugin writes sit in the same vector space as the CLI's. `packages/memory/test/shared-file-store.test.ts` pins it.
997
+ */
998
+ export function hashEmbeddingVector({ text, purpose, memoryClass, namespace, model = HASH_EMBEDDING_MODEL, dimensions = HASH_EMBEDDING_DIMENSIONS }) {
999
+ const vector = new Array(dimensions);
1000
+ let cursor = 0;
1001
+ let block = 0;
1002
+ while (cursor < dimensions) {
1003
+ const digest = createHash('sha256')
1004
+ .update(`${model}\n${purpose}\n${memoryClass}\n${namespace}\n`)
1005
+ .update(text)
1006
+ .update(`\n${block}`)
1007
+ .digest();
1008
+ for (let index = 0; index < digest.length && cursor < dimensions; index += 2) {
1009
+ vector[cursor] = digest.readUInt16BE(index) / 32_767.5 - 1;
1010
+ cursor += 1;
1011
+ }
1012
+ block += 1;
1013
+ }
1014
+ if (!vector.some((value) => value !== 0)) vector[0] = 1;
1015
+ return vector;
1016
+ }
1017
+
1018
+ // ---------------------------------------------------------------------------------------------------------------
1019
+ // Zero-dependency copy of the `@picasso/shared-home/lock` protocol (Sync §3.3), synchronous because dsh tool and
1020
+ // hook calls here are synchronous.
1021
+ // ---------------------------------------------------------------------------------------------------------------
1022
+
1023
+ export const LOCK_STALE_MS = 30_000;
1024
+ export const LOCK_ACQUIRE_TIMEOUT_MS = 10_000;
1025
+ const LOCK_RETRY_DELAY_MS = 15;
1026
+ const LOCK_MAX_RETRY_DELAY_MS = 250;
1027
+ const LOCK_UNREADABLE_GRACE_MS = 2_000;
1028
+
1029
+ /** A lock this build could not take (`lock/timeout`) or lost to a stale-lock breaker (`lock/lost`). */
1030
+ export class MemoryLockError extends Error {
1031
+ constructor(code, path, message) {
1032
+ super(message);
1033
+ this.name = 'MemoryLockError';
1034
+ this.code = code;
1035
+ this.path = path;
1036
+ }
1037
+ }
1038
+
1039
+ /** Runs `fn(lock)` while holding `<file>.lock`; `lock.assertHeld()` throws `lock/lost` if it was taken over. */
1040
+ export function withMemoryFileLock(file, fn, { staleMs = LOCK_STALE_MS, acquireTimeoutMs = LOCK_ACQUIRE_TIMEOUT_MS } = {}) {
1041
+ const lockPath = `${file}.lock`;
1042
+ mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
1043
+ const token = randomUUID();
1044
+ const deadline = Date.now() + acquireTimeoutMs;
1045
+ let attempt = 0;
1046
+ for (;;) {
1047
+ if (tryCreateLock(lockPath, token)) break;
1048
+ const current = readLockRecord(lockPath);
1049
+ if (current === undefined || isLockStale(current, staleMs)) {
1050
+ breakStaleLock(lockPath, current, staleMs, token);
1051
+ continue;
1052
+ }
1053
+ const now = Date.now();
1054
+ if (now >= deadline) {
1055
+ throw new MemoryLockError('lock/timeout', lockPath, `Timed out waiting for ${lockPath} (held by pid ${current.pid}).`);
1056
+ }
1057
+ const backoff = Math.min(LOCK_RETRY_DELAY_MS * 2 ** Math.min(attempt, 8), LOCK_MAX_RETRY_DELAY_MS);
1058
+ attempt += 1;
1059
+ sleepSync(Math.min(backoff + Math.floor(Math.random() * backoff), Math.max(1, deadline - now)));
1060
+ }
1061
+ const lock = {
1062
+ path: lockPath,
1063
+ token,
1064
+ assertHeld() {
1065
+ if (readLockRecord(lockPath)?.token !== token) {
1066
+ throw new MemoryLockError('lock/lost', lockPath, `${lockPath} was taken over by another process.`);
1067
+ }
1068
+ },
1069
+ };
1070
+ try {
1071
+ return fn(lock);
1072
+ } finally {
1073
+ if (readLockRecord(lockPath)?.token === token) rmSync(lockPath, { force: true });
1074
+ }
1075
+ }
1076
+
1077
+ function tryCreateLock(lockPath, token) {
1078
+ let fd;
1079
+ try {
1080
+ fd = openSync(lockPath, 'wx', 0o600);
1081
+ } catch (error) {
1082
+ if (error?.code === 'EEXIST') return false;
1083
+ throw error;
1084
+ }
1085
+ try {
1086
+ writeSync(fd, JSON.stringify({ pid: process.pid, token, acquiredAt: Date.now(), host: hostname() }));
1087
+ } finally {
1088
+ closeSync(fd);
1089
+ }
1090
+ return true;
1091
+ }
1092
+
1093
+ function readLockRecord(lockPath) {
1094
+ try {
1095
+ const parsed = JSON.parse(readFileSync(lockPath, 'utf8'));
1096
+ if (typeof parsed?.pid === 'number' && typeof parsed.token === 'string' && typeof parsed.acquiredAt === 'number') return parsed;
1097
+ } catch {
1098
+ // Missing, or mid-write by its creator: unknown.
1099
+ }
1100
+ return undefined;
1101
+ }
1102
+
1103
+ function isProcessAlive(pid) {
1104
+ if (!Number.isInteger(pid) || pid <= 0) return false;
1105
+ try {
1106
+ process.kill(pid, 0);
1107
+ return true;
1108
+ } catch (error) {
1109
+ return error?.code === 'EPERM';
1110
+ }
1111
+ }
1112
+
1113
+ function isLockStale(record, staleMs) {
1114
+ if (Date.now() - record.acquiredAt > staleMs) return true;
1115
+ const sameHost = record.host === undefined || record.host === hostname();
1116
+ return sameHost && !isProcessAlive(record.pid);
1117
+ }
1118
+
1119
+ function breakStaleLock(lockPath, observed, staleMs, breakerToken) {
1120
+ if (observed === undefined) {
1121
+ let mtimeMs;
1122
+ try {
1123
+ mtimeMs = statSync(lockPath).mtimeMs;
1124
+ } catch {
1125
+ mtimeMs = undefined;
1126
+ }
1127
+ if (mtimeMs === undefined || Date.now() - mtimeMs <= Math.min(staleMs, LOCK_UNREADABLE_GRACE_MS)) {
1128
+ sleepSync(LOCK_RETRY_DELAY_MS);
1129
+ return;
1130
+ }
1131
+ }
1132
+ const aside = `${lockPath}.stale-${breakerToken}`;
1133
+ try {
1134
+ renameSync(lockPath, aside);
1135
+ } catch {
1136
+ return;
1137
+ }
1138
+ const moved = readLockRecord(aside);
1139
+ if (observed !== undefined && moved !== undefined && moved.token !== observed.token) {
1140
+ try {
1141
+ linkSync(aside, lockPath);
1142
+ } catch {
1143
+ // The name was taken again; that owner's assertHeld() reports the loss.
1144
+ }
1145
+ }
1146
+ rmSync(aside, { force: true });
1147
+ }
1148
+
1149
+ const sleepCell = new Int32Array(new SharedArrayBuffer(4));
1150
+ function sleepSync(ms) {
1151
+ Atomics.wait(sleepCell, 0, 0, Math.max(1, ms));
1152
+ }
1153
+
1154
+ function writeFileAtomicSync(file, text, mode = 0o600) {
1155
+ const dir = dirname(file);
1156
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
1157
+ const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`;
1158
+ let renamed = false;
1159
+ try {
1160
+ const fd = openSync(tmp, 'wx', mode);
1161
+ try {
1162
+ writeSync(fd, text);
1163
+ fsyncSync(fd);
1164
+ } finally {
1165
+ closeSync(fd);
1166
+ }
1167
+ chmodSync(tmp, mode);
1168
+ renameSync(tmp, file);
1169
+ renamed = true;
1170
+ chmodSync(file, mode);
1171
+ } finally {
1172
+ if (!renamed) rmSync(tmp, { force: true });
1173
+ }
1174
+ }
1175
+
1176
+ function backupOnce(file, backup) {
1177
+ try {
1178
+ copyFileSync(file, backup, fsConstants.COPYFILE_EXCL);
1179
+ chmodSync(backup, 0o600);
1180
+ } catch (error) {
1181
+ if (error?.code !== 'EEXIST') throw error;
1182
+ }
1183
+ }
1184
+