@picassohq/cli 0.0.0-stage → 1.0.1

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 (230) 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 +3028 -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 +214 -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 +6049 -0
  67. package/runtime/packages/picasso-lean-context/package.json +26 -0
  68. package/runtime/packages/picasso-lean-context/timeline.js +417 -0
  69. package/runtime/packages/picasso-librarian/classify.js +146 -0
  70. package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
  71. package/runtime/packages/picasso-librarian/index.js +878 -0
  72. package/runtime/packages/picasso-librarian/notes.js +159 -0
  73. package/runtime/packages/picasso-librarian/package.json +34 -0
  74. package/runtime/packages/picasso-librarian/state.js +478 -0
  75. package/runtime/packages/picasso-memory/index.js +1184 -0
  76. package/runtime/packages/picasso-memory/package.json +21 -0
  77. package/runtime/packages/picasso-model-router/connections.js +895 -0
  78. package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
  79. package/runtime/packages/picasso-model-router/index.js +1081 -0
  80. package/runtime/packages/picasso-model-router/package.json +30 -0
  81. package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
  82. package/runtime/packages/picasso-options/index.js +263 -0
  83. package/runtime/packages/picasso-options/package.json +28 -0
  84. package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
  85. package/runtime/packages/picasso-progress-reports/index.js +267 -0
  86. package/runtime/packages/picasso-progress-reports/package.json +30 -0
  87. package/runtime/packages/picasso-progress-reports/report.js +235 -0
  88. package/runtime/packages/picasso-sdk-server/aside.js +128 -0
  89. package/runtime/packages/picasso-sdk-server/connections.js +38 -0
  90. package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
  91. package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
  92. package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
  93. package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
  94. package/runtime/packages/picasso-sdk-server/goal.js +131 -0
  95. package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
  96. package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
  97. package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
  98. package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
  99. package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
  100. package/runtime/packages/picasso-sdk-server/index.js +886 -0
  101. package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
  102. package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
  103. package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
  104. package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
  105. package/runtime/packages/picasso-sdk-server/package.json +50 -0
  106. package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
  107. package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
  108. package/runtime/packages/picasso-sdk-server/queue.js +322 -0
  109. package/runtime/packages/picasso-sdk-server/requester.js +43 -0
  110. package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
  111. package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
  112. package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
  113. package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
  114. package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
  115. package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
  116. package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
  117. package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
  118. package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
  119. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
  120. package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
  121. package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
  122. package/runtime/packages/picasso-web-search/backends.js +350 -0
  123. package/runtime/packages/picasso-web-search/config.js +121 -0
  124. package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
  125. package/runtime/packages/picasso-web-search/failure.js +111 -0
  126. package/runtime/packages/picasso-web-search/format.js +35 -0
  127. package/runtime/packages/picasso-web-search/index.js +66 -0
  128. package/runtime/packages/picasso-web-search/package.json +38 -0
  129. package/runtime/packages/picasso-web-search/router.js +155 -0
  130. package/runtime/packages/picasso-x-reader/circle.js +324 -0
  131. package/runtime/packages/picasso-x-reader/command.js +169 -0
  132. package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
  133. package/runtime/packages/picasso-x-reader/index.js +170 -0
  134. package/runtime/packages/picasso-x-reader/package.json +39 -0
  135. package/runtime/packages/picasso-x-reader/read.js +370 -0
  136. package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
  137. package/runtime/packages/picasso-x-reader/settings.js +131 -0
  138. package/runtime/packages/picasso-x-reader/urls.js +154 -0
  139. package/runtime/packages/picasso-x-reader/xmd.js +512 -0
  140. package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
  141. package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
  142. package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
  143. package/runtime/plugins/picasso-auto-approve/package.json +28 -0
  144. package/runtime/plugins/picasso-browser/index.js +424 -0
  145. package/runtime/plugins/picasso-browser/package.json +28 -0
  146. package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
  147. package/runtime/plugins/picasso-checkpoints/index.js +885 -0
  148. package/runtime/plugins/picasso-checkpoints/package.json +29 -0
  149. package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
  150. package/runtime/plugins/picasso-commands/index.js +497 -0
  151. package/runtime/plugins/picasso-commands/package.json +28 -0
  152. package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
  153. package/runtime/plugins/picasso-instructions/formats.js +145 -0
  154. package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
  155. package/runtime/plugins/picasso-instructions/glob.js +114 -0
  156. package/runtime/plugins/picasso-instructions/globals.js +90 -0
  157. package/runtime/plugins/picasso-instructions/imports.js +123 -0
  158. package/runtime/plugins/picasso-instructions/index.js +326 -0
  159. package/runtime/plugins/picasso-instructions/modes.js +64 -0
  160. package/runtime/plugins/picasso-instructions/package.json +30 -0
  161. package/runtime/plugins/picasso-instructions/parse.js +134 -0
  162. package/runtime/plugins/picasso-instructions/report.js +161 -0
  163. package/runtime/plugins/picasso-instructions/resolve.js +939 -0
  164. package/runtime/plugins/picasso-instructions/scan.js +181 -0
  165. package/runtime/plugins/picasso-instructions/settings.js +150 -0
  166. package/runtime/plugins/picasso-instructions/skills.js +345 -0
  167. package/runtime/plugins/picasso-lean-context/index.js +6049 -0
  168. package/runtime/plugins/picasso-lean-context/package.json +26 -0
  169. package/runtime/plugins/picasso-lean-context/timeline.js +417 -0
  170. package/runtime/plugins/picasso-librarian/classify.js +146 -0
  171. package/runtime/plugins/picasso-librarian/index.js +878 -0
  172. package/runtime/plugins/picasso-librarian/notes.js +159 -0
  173. package/runtime/plugins/picasso-librarian/package.json +34 -0
  174. package/runtime/plugins/picasso-librarian/state.js +478 -0
  175. package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
  176. package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
  177. package/runtime/plugins/picasso-mail/inbox.js +207 -0
  178. package/runtime/plugins/picasso-mail/index.js +293 -0
  179. package/runtime/plugins/picasso-mail/package.json +22 -0
  180. package/runtime/plugins/picasso-memory/index.js +1184 -0
  181. package/runtime/plugins/picasso-memory/package.json +21 -0
  182. package/runtime/plugins/picasso-model-router/connections.js +895 -0
  183. package/runtime/plugins/picasso-model-router/index.js +1081 -0
  184. package/runtime/plugins/picasso-model-router/package.json +30 -0
  185. package/runtime/plugins/picasso-options/index.js +263 -0
  186. package/runtime/plugins/picasso-options/package.json +28 -0
  187. package/runtime/plugins/picasso-progress-reports/index.js +267 -0
  188. package/runtime/plugins/picasso-progress-reports/package.json +30 -0
  189. package/runtime/plugins/picasso-progress-reports/report.js +235 -0
  190. package/runtime/plugins/picasso-provider-models/index.js +436 -0
  191. package/runtime/plugins/picasso-provider-models/package.json +28 -0
  192. package/runtime/plugins/picasso-repo-index/index.js +1850 -0
  193. package/runtime/plugins/picasso-repo-index/package.json +28 -0
  194. package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
  195. package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
  196. package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
  197. package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
  198. package/runtime/plugins/picasso-trackers/index.js +895 -0
  199. package/runtime/plugins/picasso-trackers/package.json +28 -0
  200. package/runtime/plugins/picasso-web-search/backends.js +350 -0
  201. package/runtime/plugins/picasso-web-search/config.js +121 -0
  202. package/runtime/plugins/picasso-web-search/failure.js +111 -0
  203. package/runtime/plugins/picasso-web-search/format.js +35 -0
  204. package/runtime/plugins/picasso-web-search/index.js +66 -0
  205. package/runtime/plugins/picasso-web-search/package.json +38 -0
  206. package/runtime/plugins/picasso-web-search/router.js +155 -0
  207. package/runtime/plugins/picasso-x-reader/circle.js +324 -0
  208. package/runtime/plugins/picasso-x-reader/command.js +169 -0
  209. package/runtime/plugins/picasso-x-reader/index.js +170 -0
  210. package/runtime/plugins/picasso-x-reader/package.json +39 -0
  211. package/runtime/plugins/picasso-x-reader/read.js +370 -0
  212. package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
  213. package/runtime/plugins/picasso-x-reader/settings.js +131 -0
  214. package/runtime/plugins/picasso-x-reader/urls.js +154 -0
  215. package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
  216. package/runtime/relay/attachment-text.mjs +737 -0
  217. package/runtime/relay/companion/companion.css +126 -0
  218. package/runtime/relay/companion/companion.js +648 -0
  219. package/runtime/relay/companion/icon.svg +5 -0
  220. package/runtime/relay/companion/index.html +25 -0
  221. package/runtime/relay/companion/manifest.json +13 -0
  222. package/runtime/relay/companion/sw.js +41 -0
  223. package/runtime/relay/main.mjs +37252 -0
  224. package/runtime/relay/model-listing.mjs +614 -0
  225. package/runtime/relay/versions-routes.mjs +1198 -0
  226. package/runtime/verify-plugins.mjs +205 -0
  227. package/runtime-lock/package-lock.json +10779 -0
  228. package/runtime-lock/package.json +7 -0
  229. package/scripts/install-runtime.mjs +400 -0
  230. package/README.md +0 -3
@@ -0,0 +1,796 @@
1
+ // @picasso/session-lifecycle — archive, soft delete and restore for dsh sessions.
2
+ //
3
+ // dsh 0.2.1-rc.5 has no session archive or delete API, so this plugin adds one as a Host Remote service
4
+ // (`sessionLifecycle/*`) without touching dsh's own stores:
5
+ // archive / unarchive a flag in a JSON sidecar next to the session root (`<dsh data>/picasso-session-lifecycle.json`).
6
+ // delete moves the session's persistence folder (`<root>/<project>/<session>`) to
7
+ // `<dsh data>/trash/<session>-<ts>`; refused while the session runs or another process holds
8
+ // its write lease (`session.lock`). The session's side conversations go with it (trash entries
9
+ // marked `cascadeOf: <session>`), all or nothing.
10
+ // restore moves a trashed folder back to where it was, and the side conversations its delete took along.
11
+ // destroy removes a trashed folder for good (with the side conversations its delete took along);
12
+ // only trash entries qualify, so a live session still has to pass delete's refusals first.
13
+ // list archived and trashed ids (trash rows carry the label the caller saved at delete time),
14
+ // plus the hidden project folders.
15
+ // hideProject / unhideProject "Remove project from sidebar": a folder path flagged in the same sidecar; its threads
16
+ // are not touched (clients leave the folder group out until it is unhidden).
17
+ // side / unside "Side conversation" (Picasso's /btw): a fork of a thread flagged with the thread it came from;
18
+ // clients keep side sessions out of every thread list (they live in the thread's right panel).
19
+ // The flag survives trash and restore.
20
+ // Trash older than 30 days is purged when the plugin starts (a parent's side conversations with it).
21
+ //
22
+ // Zero runtime dependencies on purpose: it ships beside the relay (not inside dsh's node_modules), so it registers its
23
+ // Remote methods with the gateway's source-mode markers (the descriptor `@deepseek-ai/dsh-typert-protocol`'s `@Remote`
24
+ // decorator writes) and raises failures as structural dsh RemoteErrors (`isDSHRemoteError`).
25
+ import { execFile } from 'node:child_process';
26
+ import { randomInt, randomUUID } from 'node:crypto';
27
+ import { existsSync, readFileSync } from 'node:fs';
28
+ import { link, mkdir, open, readdir, readFile, readlink, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
29
+ import { homedir, hostname } from 'node:os';
30
+ import { dirname, join, relative, resolve, sep } from 'node:path';
31
+
32
+ export const name = 'picasso-session-lifecycle';
33
+ /** The dsh release this plugin is written and tested against (Picasso pins the engine to it). */
34
+ export const dshTarget = '0.2.2-rc.3';
35
+ export const SERVICE_KEY = 'sessionLifecycle';
36
+ export const SIDECAR_FILENAME = 'picasso-session-lifecycle.json';
37
+ export const TRASH_DIRNAME = 'trash';
38
+ export const TRASH_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
39
+ /** The sidecar schema this build reads and writes. A newer sidecar raises `sessionLifecycle/newer-schema`. */
40
+ export const SIDECAR_VERSION = 1;
41
+ const REMOTE_METHOD_DESCRIPTOR = '@deepseek-ai/dsh-typert-protocol/remote-methods';
42
+ const LEASE_FILENAME = 'session.lock';
43
+
44
+ /** A dsh RemoteError, identified structurally by the gateway (`remoteErrorOf`), so the code reaches the client. */
45
+ export class LifecycleError extends Error {
46
+ constructor(code, message, details = {}) {
47
+ super(message);
48
+ this.name = 'RemoteError';
49
+ this.code = `sessionLifecycle/${code}`;
50
+ this.details = details;
51
+ this.isDSHRemoteError = true;
52
+ }
53
+ }
54
+
55
+ /** dsh-session-persistence-jsonl's `encodeSegment`: the session folder name for an id. */
56
+ export function encodeSegment(raw) {
57
+ if (raw.length === 0) throw new Error('cannot encode an empty path segment');
58
+ if (raw === '.') return '~002E';
59
+ if (raw === '..') return '~002E~002E';
60
+ let out = '';
61
+ for (let i = 0; i < raw.length; i++) {
62
+ const code = raw.charCodeAt(i);
63
+ const ch = String.fromCharCode(code);
64
+ out += ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch) ? ch : `~${code.toString(16).toUpperCase().padStart(4, '0')}`;
65
+ }
66
+ return out;
67
+ }
68
+
69
+ /**
70
+ * Process ids holding `path` open; a held `session.lock` is a live dsh writer lease.
71
+ * macOS uses `lsof -t`; Linux scans /proc/<pid>/fd symlinks — lsof is not part of the slim
72
+ * node images and on Debian it would live at /usr/bin/lsof anyway (ACR run ch3v).
73
+ */
74
+ export function openHolders(path) {
75
+ if (process.platform === 'linux') return procOpenHolders(path);
76
+ return new Promise((resolvePids) => {
77
+ execFile('/usr/sbin/lsof', ['-t', '--', path], { timeout: 5000 }, (error, stdout) => {
78
+ if (error && typeof error.code !== 'number') return resolvePids([]);
79
+ resolvePids(String(stdout).split('\n').map((line) => Number(line.trim())).filter((pid) => Number.isInteger(pid) && pid > 0));
80
+ });
81
+ });
82
+ }
83
+
84
+ /** Linux openHolders: every /proc/<pid>/fd symlink pointing at the file's real path. */
85
+ async function procOpenHolders(path) {
86
+ const target = await realpath(path).catch(() => resolve(path));
87
+ const pids = [];
88
+ let procs;
89
+ try {
90
+ procs = await readdir('/proc');
91
+ } catch {
92
+ return pids;
93
+ }
94
+ for (const proc of procs) {
95
+ if (!/^[0-9]+$/.test(proc)) continue;
96
+ let fds;
97
+ try {
98
+ fds = await readdir(`/proc/${proc}/fd`);
99
+ } catch {
100
+ continue; // process exited or is not ours to inspect
101
+ }
102
+ for (const fd of fds) {
103
+ try {
104
+ if ((await readlink(`/proc/${proc}/fd/${fd}`)) === target) {
105
+ pids.push(Number(proc));
106
+ break;
107
+ }
108
+ } catch {
109
+ // the fd raced closed between readdir and readlink — keep scanning
110
+ }
111
+ }
112
+ }
113
+ return pids;
114
+ }
115
+
116
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
117
+ const emptyState = () => ({ version: 1, archived: {}, trashed: {}, hiddenProjects: {}, side: {}, superseded: {} });
118
+
119
+ /**
120
+ * The lifecycle store. `root` is the JSONL persistence root (`dshHomePath('sessions')`); the sidecar and the trash live
121
+ * in its parent (the dsh data directory). Every mutation is serialized and the sidecar is replaced atomically.
122
+ */
123
+ export class SessionLifecycle {
124
+ constructor(options) {
125
+ this.root = resolve(options.root);
126
+ this.dataDir = resolve(options.dataDir ?? dirname(this.root));
127
+ this.sidecar = join(this.dataDir, SIDECAR_FILENAME);
128
+ this.trashDir = join(this.dataDir, TRASH_DIRNAME);
129
+ this.now = options.now ?? Date.now;
130
+ this.retentionMs = options.retentionMs ?? TRASH_RETENTION_MS;
131
+ this.isRunning = options.isRunning ?? (() => false);
132
+ this.holders = options.holders ?? openHolders;
133
+ this.moveFolder = options.moveFolder;
134
+ this.ownPid = options.ownPid ?? process.pid;
135
+ this.lockOptions = options.lock ?? {};
136
+ this.tail = Promise.resolve();
137
+ }
138
+
139
+ // ── Remote surface (`sessionLifecycle/<method>`; wire args are the parameter names) ─────────────────────────────
140
+
141
+ archive(sessionId) {
142
+ return this.serial(async () => {
143
+ const id = requireId(sessionId);
144
+ const state = this.read();
145
+ if (state.trashed[id]) throw new LifecycleError('session-trashed', `Session ${id} is in the trash; restore it first.`, { sessionId: id });
146
+ if ((await this.findSessionDir(id)) === undefined) throw new LifecycleError('session-not-found', `No session ${id} in ${this.root}.`, { sessionId: id });
147
+ state.archived[id] = { archivedAt: state.archived[id]?.archivedAt ?? this.now() };
148
+ await this.write(state);
149
+ return { sessionId: id, archived: true, archivedAt: state.archived[id].archivedAt };
150
+ });
151
+ }
152
+
153
+ unarchive(sessionId) {
154
+ return this.serial(async () => {
155
+ const id = requireId(sessionId);
156
+ const state = this.read();
157
+ const was = id in state.archived;
158
+ delete state.archived[id];
159
+ if (was) await this.write(state);
160
+ return { sessionId: id, archived: false };
161
+ });
162
+ }
163
+
164
+ /**
165
+ * Soft delete: the session folder moves into the trash. `label` is caller metadata kept for the trash list. The
166
+ * session's side conversations (side sessions whose parent it is, open or closed, not already in the trash) move with
167
+ * it, each trash entry marked `cascadeOf: <session>` and remembering whether it was archived; one running or held by
168
+ * another process refuses the whole delete before anything moves.
169
+ */
170
+ delete(sessionId, label) {
171
+ return this.serial(async () => {
172
+ const id = requireId(sessionId);
173
+ const state = this.read();
174
+ if (state.trashed[id]) throw new LifecycleError('session-trashed', `Session ${id} is already in the trash.`, { sessionId: id });
175
+ const dir = await this.findSessionDir(id);
176
+ if (dir === undefined) throw new LifecycleError('session-not-found', `No session ${id} in ${this.root}.`, { sessionId: id });
177
+ await this.requireIdle(id, dir);
178
+ const children = [];
179
+ for (const child of sideDescendants(state, id)) {
180
+ if (state.trashed[child]) continue;
181
+ const childDir = await this.findSessionDir(child);
182
+ if (childDir === undefined) continue;
183
+ await this.requireIdle(child, childDir, id);
184
+ children.push({ child, childDir });
185
+ }
186
+ const trashedAt = this.now();
187
+ await mkdir(this.trashDir, { recursive: true, mode: 0o700 });
188
+ try {
189
+ await this.moveToTrash(state, id, dir, trashedAt, isRecord(label) ? { label: sanitizeLabel(label) } : {});
190
+ delete state.archived[id];
191
+ for (const { child, childDir } of children) {
192
+ const archivedAt = state.archived[child]?.archivedAt;
193
+ await this.moveToTrash(state, child, childDir, trashedAt, { cascadeOf: id, ...(typeof archivedAt === 'number' ? { archivedAt } : {}) });
194
+ delete state.archived[child];
195
+ }
196
+ } finally {
197
+ // Whatever moved is recorded, even if a later rename failed, so nothing in the trash is ever untracked.
198
+ await this.write(state);
199
+ }
200
+ return {
201
+ sessionId: id, trashed: true, trashedAt, expiresAt: trashedAt + this.retentionMs,
202
+ ...(children.length > 0 ? { cascade: children.map(({ child }) => child) } : {}),
203
+ };
204
+ });
205
+ }
206
+
207
+ /**
208
+ * Moves a trashed folder back, then every side conversation its delete took along (`cascadeOf`), archived again if it
209
+ * was. A side conversation that cannot come back (its folder gone or taken) stays out and is named in `cascadeFailed`.
210
+ */
211
+ restore(sessionId) {
212
+ return this.serial(async () => {
213
+ const id = requireId(sessionId);
214
+ const state = this.read();
215
+ if (!state.trashed[id]) throw new LifecycleError('not-trashed', `Session ${id} is not in the trash.`, { sessionId: id });
216
+ const cascade = [];
217
+ const cascadeFailed = [];
218
+ try {
219
+ await this.moveBack(state, id);
220
+ for (const [child, entry] of Object.entries(state.trashed)) {
221
+ if (entry.cascadeOf !== id) continue;
222
+ try {
223
+ await this.moveBack(state, child);
224
+ if (typeof entry.archivedAt === 'number') state.archived[child] = { archivedAt: entry.archivedAt };
225
+ cascade.push(child);
226
+ } catch (error) {
227
+ cascadeFailed.push({ sessionId: child, code: error?.code ?? 'sessionLifecycle/restore-failed' });
228
+ }
229
+ }
230
+ } finally {
231
+ // A vanished trash folder drops its entry (`trash-missing`); every completed move is recorded.
232
+ await this.write(state);
233
+ }
234
+ return {
235
+ sessionId: id, trashed: false,
236
+ ...(cascade.length > 0 ? { cascade: cascade.sort() } : {}),
237
+ ...(cascadeFailed.length > 0 ? { cascadeFailed } : {}),
238
+ };
239
+ });
240
+ }
241
+
242
+ /**
243
+ * "Delete forever": removes one trashed folder and the side conversations its delete took along (`cascadeOf`),
244
+ * skipping the 30-day wait. Only trash entries qualify (`not-trashed` otherwise), so a live or open session is
245
+ * still protected by `delete`'s session-running / session-open refusals on the way in.
246
+ */
247
+ destroy(sessionId) {
248
+ return this.serial(async () => {
249
+ const id = requireId(sessionId);
250
+ const state = this.read();
251
+ const entry = state.trashed[id];
252
+ if (!entry) throw new LifecycleError('not-trashed', `Session ${id} is not in the trash.`, { sessionId: id });
253
+ const doomed = new Set([id]);
254
+ for (const [child, childEntry] of Object.entries(state.trashed)) if (childEntry.cascadeOf === id) doomed.add(child);
255
+ for (const gone of doomed) {
256
+ await rm(join(this.trashDir, state.trashed[gone].folder), { recursive: true, force: true });
257
+ delete state.trashed[gone];
258
+ delete state.side[gone];
259
+ delete state.superseded[gone];
260
+ }
261
+ await this.write(state);
262
+ const cascade = [...doomed].filter((child) => child !== id).sort();
263
+ return { sessionId: id, destroyed: true, ...(cascade.length > 0 ? { cascade } : {}) };
264
+ });
265
+ }
266
+
267
+ /** Hides a project folder from client sidebars; its sessions stay as they are. */
268
+ hideProject(cwd) {
269
+ return this.serial(async () => {
270
+ const path = requireFolder(cwd);
271
+ const state = this.read();
272
+ state.hiddenProjects[path] = { hiddenAt: state.hiddenProjects[path]?.hiddenAt ?? this.now() };
273
+ await this.write(state);
274
+ return { cwd: path, hidden: true, hiddenAt: state.hiddenProjects[path].hiddenAt };
275
+ });
276
+ }
277
+
278
+ unhideProject(cwd) {
279
+ return this.serial(async () => {
280
+ const path = requireFolder(cwd);
281
+ const state = this.read();
282
+ const was = path in state.hiddenProjects;
283
+ delete state.hiddenProjects[path];
284
+ if (was) await this.write(state);
285
+ return { cwd: path, hidden: false };
286
+ });
287
+ }
288
+
289
+ /**
290
+ * Flags a session as a side conversation of `parentId` (both must exist): hidden from thread lists. `sideAt` (ms)
291
+ * carries a fork time over: an edited side question's fork keeps the original's, so it lists where the original did
292
+ * and its tab still starts at the same turn. Without it the flag records now (kept when re-flagged).
293
+ */
294
+ side(sessionId, parentId, sideAt) {
295
+ return this.serial(async () => {
296
+ const id = requireId(sessionId);
297
+ const parent = requireId(parentId);
298
+ if (id === parent) throw new LifecycleError('bad-request', 'A session cannot be a side conversation of itself.', { sessionId: id });
299
+ const state = this.read();
300
+ if (state.trashed[id]) throw new LifecycleError('session-trashed', `Session ${id} is in the trash; restore it first.`, { sessionId: id });
301
+ if ((await this.findSessionDir(id)) === undefined) throw new LifecycleError('session-not-found', `No session ${id} in ${this.root}.`, { sessionId: id });
302
+ const given = typeof sideAt === 'number' && Number.isFinite(sideAt) && sideAt > 0 ? sideAt : undefined;
303
+ const at = given ?? (state.side[id]?.parentId === parent ? state.side[id].sideAt : this.now());
304
+ state.side[id] = { parentId: parent, sideAt: at };
305
+ await this.write(state);
306
+ return { sessionId: id, side: true, parentId: parent, sideAt: at };
307
+ });
308
+ }
309
+
310
+ /** Clears the side flag: the session lists as an ordinary thread again. */
311
+ unside(sessionId) {
312
+ return this.serial(async () => {
313
+ const id = requireId(sessionId);
314
+ const state = this.read();
315
+ const was = id in state.side;
316
+ delete state.side[id];
317
+ if (was) await this.write(state);
318
+ return { sessionId: id, side: false };
319
+ });
320
+ }
321
+
322
+ /**
323
+ * "Edited the message": the original thread is replaced by a fork but kept on disk as a hidden backup. It is
324
+ * hidden from every thread list, sidebar, search and side-conversation tab until `unsupersede` (the Undo path).
325
+ * `forkId` names the fork that replaced it (an edit or a regenerate cut with `session/fork`): the two are versions of
326
+ * one message, so the original is kept while any fork recorded here still exists (`sweepSuperseded`).
327
+ */
328
+ supersede(sessionId, forkId) {
329
+ return this.serial(async () => {
330
+ const id = requireId(sessionId);
331
+ const fork = forkId === undefined || forkId === null ? undefined : requireId(forkId);
332
+ if (fork === id) throw new LifecycleError('bad-request', 'A session cannot be superseded by itself.', { sessionId: id });
333
+ const state = this.read();
334
+ const previous = isRecord(state.superseded[id]) ? state.superseded[id] : {};
335
+ const recorded = Array.isArray(previous.forks) ? previous.forks.filter((entry) => typeof entry === 'string') : [];
336
+ const forks = [...new Set([...recorded, ...(fork === undefined ? [] : [fork])])];
337
+ state.superseded[id] = { supersededAt: previous.supersededAt ?? this.now(), ...(forks.length > 0 ? { forks } : {}) };
338
+ await this.write(state);
339
+ return { sessionId: id, superseded: true, supersededAt: state.superseded[id].supersededAt, ...(forks.length > 0 ? { forks } : {}) };
340
+ });
341
+ }
342
+
343
+ /** Undo: the original thread lists again. */
344
+ unsupersede(sessionId) {
345
+ return this.serial(async () => {
346
+ const id = requireId(sessionId);
347
+ const state = this.read();
348
+ const was = id in state.superseded;
349
+ delete state.superseded[id];
350
+ if (was) await this.write(state);
351
+ return { sessionId: id, superseded: false };
352
+ });
353
+ }
354
+
355
+ /**
356
+ * Moves a thread's working folder to `path` (the engine's `workingDirectory.set`): the way out for a thread whose
357
+ * folder is gone (a merged and removed git worktree) and the "Choose folder…" action. The folder must exist now;
358
+ * the engine republishes the session's cwd and states the change once in the thread's log.
359
+ */
360
+ async setWorkingDirectory(sessionId, path) {
361
+ const id = requireId(sessionId);
362
+ const folder = requireFolder(path);
363
+ let exists = false;
364
+ try {
365
+ exists = (await stat(folder)).isDirectory();
366
+ } catch {
367
+ exists = false;
368
+ }
369
+ if (!exists) throw new LifecycleError('working-directory-missing', `${folder} is not a folder that exists.`, { path: folder });
370
+ if (typeof this.moveFolder !== 'function') throw new LifecycleError('unsupported', 'This engine cannot move a thread to another folder.');
371
+ const moved = await this.moveFolder(id, folder);
372
+ return { sessionId: id, path: typeof moved === 'string' && moved.length > 0 ? moved : folder };
373
+ }
374
+
375
+ list() {
376
+ return this.serial(async () => {
377
+ const state = this.read();
378
+ return {
379
+ side: Object.keys(state.side).sort(),
380
+ sideOf: Object.fromEntries(Object.entries(state.side).map(([id, entry]) => [id, entry.parentId])),
381
+ sideAt: Object.fromEntries(Object.entries(state.side).map(([id, entry]) => [id, entry.sideAt])),
382
+ hiddenProjects: Object.entries(state.hiddenProjects)
383
+ .map(([cwd, entry]) => ({ cwd, hiddenAt: entry.hiddenAt }))
384
+ .sort((a, b) => b.hiddenAt - a.hiddenAt),
385
+ archived: Object.keys(state.archived).sort(),
386
+ trashed: Object.keys(state.trashed).sort(),
387
+ superseded: Object.keys(state.superseded).sort(),
388
+ supersededAt: Object.fromEntries(Object.entries(state.superseded).map(([id, entry]) => [id, entry.supersededAt])),
389
+ archivedAt: Object.fromEntries(Object.entries(state.archived).map(([id, entry]) => [id, entry.archivedAt])),
390
+ trash: Object.entries(state.trashed)
391
+ .map(([id, entry]) => ({
392
+ sessionId: id, trashedAt: entry.trashedAt, expiresAt: entry.trashedAt + this.retentionMs,
393
+ ...(entry.label ? { label: entry.label } : {}),
394
+ ...(typeof entry.cascadeOf === 'string' ? { cascadeOf: entry.cascadeOf } : {}),
395
+ }))
396
+ .sort((a, b) => b.trashedAt - a.trashedAt),
397
+ };
398
+ });
399
+ }
400
+
401
+ /**
402
+ * "Edited the message" backups older than 7 days move to the trash (with the trash's own 30-day purge), and their
403
+ * superseded flag clears — Undo is meant to be quick; nobody reaches a week-old hidden thread. A backup that is a
404
+ * version of a live family is no backup: while a fork `supersede` recorded for it still has its folder (it is not in
405
+ * the trash), the version switcher still opens it, so it stays (still hidden from lists) and is checked again at the
406
+ * next sweep. A backup with no recorded fork (a turn-1 edit re-bases on a fresh thread, which has no lineage) is
407
+ * swept as before.
408
+ */
409
+ sweepSuperseded() {
410
+ return this.serial(async () => {
411
+ const cutoff = this.now() - 7 * 24 * 60 * 60 * 1000;
412
+ const state = this.read();
413
+ const expired = Object.entries(state.superseded).filter(([, entry]) => isRecord(entry) && typeof entry.supersededAt === 'number' && entry.supersededAt <= cutoff).map(([id]) => id);
414
+ if (expired.length === 0) return { swept: [] };
415
+ const swept = [];
416
+ for (const id of expired) {
417
+ if (state.trashed[id]) { delete state.superseded[id]; continue; }
418
+ if (await this.hasLiveFork(state, state.superseded[id])) continue;
419
+ const dir = await this.findSessionDir(id);
420
+ delete state.superseded[id];
421
+ if (dir === undefined) continue; // the folder is already gone; just lift the flag
422
+ try {
423
+ const label = { title: 'Superseded thread' };
424
+ await mkdir(this.trashDir, { recursive: true });
425
+ await this.moveToTrash(state, id, dir, this.now(), { label });
426
+ swept.push(id);
427
+ } catch {
428
+ state.superseded[id] = { supersededAt: cutoff }; // retry tomorrow
429
+ }
430
+ }
431
+ await this.write(state);
432
+ return { swept };
433
+ });
434
+ }
435
+
436
+ // ── Maintenance ──────────────────────────────────────────────────────────────────────────────────────────────────
437
+
438
+ /**
439
+ * Removes trash older than the retention window (with the side conversations a purged delete took along), plus
440
+ * orphaned trash folders whose name stamp is that old. A purged session is gone for good, so its side flag goes too.
441
+ */
442
+ purge() {
443
+ return this.serial(async () => {
444
+ const state = this.read();
445
+ const cutoff = this.now() - this.retentionMs;
446
+ const expired = new Set(Object.entries(state.trashed).filter(([, entry]) => entry.trashedAt <= cutoff).map(([id]) => id));
447
+ for (const [id, entry] of Object.entries(state.trashed)) if (expired.has(entry.cascadeOf)) expired.add(id);
448
+ const purged = [];
449
+ for (const [id, entry] of Object.entries(state.trashed)) {
450
+ if (!expired.has(id)) continue;
451
+ await rm(join(this.trashDir, entry.folder), { recursive: true, force: true });
452
+ delete state.trashed[id];
453
+ delete state.side[id];
454
+ purged.push(id);
455
+ }
456
+ const known = new Set(Object.values(state.trashed).map((entry) => entry.folder));
457
+ for (const folder of await safeReaddir(this.trashDir)) {
458
+ const stamp = Number(/-(\d{10,})$/.exec(folder)?.[1]);
459
+ if (known.has(folder) || !Number.isFinite(stamp) || stamp > cutoff) continue;
460
+ await rm(join(this.trashDir, folder), { recursive: true, force: true });
461
+ }
462
+ if (purged.length > 0) await this.write(state);
463
+ return { purged };
464
+ });
465
+ }
466
+
467
+ /** Whether a fork `supersede` recorded for a backup still exists outside the trash (the two are versions of one message). */
468
+ async hasLiveFork(state, entry) {
469
+ for (const fork of Array.isArray(entry?.forks) ? entry.forks : []) {
470
+ if (typeof fork !== 'string' || state.trashed[fork]) continue;
471
+ if ((await this.findSessionDir(fork)) !== undefined) return true;
472
+ }
473
+ return false;
474
+ }
475
+
476
+ /** Refuses (session-running / session-open) while `id` runs or another process holds its lease; `parentId` names the delete it blocks. */
477
+ async requireIdle(id, dir, parentId) {
478
+ const what = parentId === undefined ? `Session ${id}` : `Side conversation ${id} of session ${parentId}`;
479
+ const details = parentId === undefined ? { sessionId: id } : { sessionId: parentId, sideSessionId: id };
480
+ if (await this.isRunning(id)) throw new LifecycleError('session-running', `${what} is running; stop it before deleting.`, details);
481
+ // A writer in another process (another dsh Host, a TUI, a headless run) refuses the delete. This Host's own lease
482
+ // on an idle session it has open (any session a client followed) does not: the folder is renamed, not copied, so
483
+ // the held descriptor and the locked inode travel with it, exclusion stays intact, and restore renames it back.
484
+ const holders = (await this.holders(join(dir, LEASE_FILENAME))).filter((pid) => pid !== this.ownPid);
485
+ if (holders.length > 0) {
486
+ throw new LifecycleError('session-open', `${what} has an open writer (pid ${holders.join(', ')}); close it before deleting.`, { ...details, pids: holders });
487
+ }
488
+ }
489
+
490
+ /** Renames `dir` into the trash and records the entry (`extra`: label, cascadeOf, archivedAt) in `state`. */
491
+ async moveToTrash(state, id, dir, trashedAt, extra) {
492
+ const folder = `${encodeSegment(id)}-${trashedAt}`;
493
+ await rename(dir, join(this.trashDir, folder));
494
+ state.trashed[id] = { trashedAt, folder, origin: relative(this.root, dir).split(sep).join('/'), ...extra };
495
+ }
496
+
497
+ /** Renames a trashed folder back to its origin and drops the entry from `state` (also when the folder is gone). */
498
+ async moveBack(state, id) {
499
+ const entry = state.trashed[id];
500
+ const from = join(this.trashDir, entry.folder);
501
+ const to = join(this.root, ...String(entry.origin).split('/'));
502
+ if (!isInside(this.root, to)) throw new LifecycleError('restore-invalid', `Trash entry for ${id} points outside ${this.root}.`, { sessionId: id });
503
+ if (!existsSync(from)) {
504
+ delete state.trashed[id];
505
+ throw new LifecycleError('trash-missing', `The trashed folder for ${id} is gone.`, { sessionId: id });
506
+ }
507
+ if (existsSync(to)) throw new LifecycleError('restore-conflict', `A session folder already exists at ${to}.`, { sessionId: id });
508
+ await mkdir(dirname(to), { recursive: true, mode: 0o700 });
509
+ await rename(from, to);
510
+ delete state.trashed[id];
511
+ }
512
+
513
+ async findSessionDir(id) {
514
+ const segment = encodeSegment(id);
515
+ for (const project of await safeReaddir(this.root)) {
516
+ const candidate = join(this.root, project, segment);
517
+ try {
518
+ if ((await stat(candidate)).isDirectory()) return candidate;
519
+ } catch {
520
+ // not in this project
521
+ }
522
+ }
523
+ return undefined;
524
+ }
525
+
526
+ read() {
527
+ let parsed;
528
+ try {
529
+ parsed = JSON.parse(readFileSync(this.sidecar, 'utf8'));
530
+ } catch {
531
+ return emptyState();
532
+ }
533
+ if (isRecord(parsed) && typeof parsed.version === 'number' && parsed.version > SIDECAR_VERSION) {
534
+ // A newer Picasso wrote it (both surfaces' Hosts mount this plugin on one ~/.dsh): never read or rewrite it as empty.
535
+ throw new LifecycleError('newer-schema', `${this.sidecar} was written by a newer Picasso (schema ${parsed.version}; this version reads up to ${SIDECAR_VERSION}). Update Picasso.`, { file: this.sidecar, found: parsed.version, supported: SIDECAR_VERSION });
536
+ }
537
+ if (!isRecord(parsed)) return emptyState();
538
+ return {
539
+ version: SIDECAR_VERSION,
540
+ archived: isRecord(parsed.archived) ? parsed.archived : {},
541
+ trashed: isRecord(parsed.trashed) ? parsed.trashed : {},
542
+ hiddenProjects: isRecord(parsed.hiddenProjects) ? parsed.hiddenProjects : {},
543
+ side: isRecord(parsed.side) ? parsed.side : {},
544
+ superseded: isRecord(parsed.superseded) ? parsed.superseded : {},
545
+ };
546
+ }
547
+
548
+ async write(state) {
549
+ await mkdir(this.dataDir, { recursive: true });
550
+ const temporary = `${this.sidecar}.${process.pid}.tmp`;
551
+ await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
552
+ await rename(temporary, this.sidecar);
553
+ }
554
+
555
+ /**
556
+ * Runs `body` after every earlier call in this process, holding `<sidecar>.lock` for the whole read-modify-write:
557
+ * the CLI's and the Mac's Hosts both mount this plugin on one `~/.dsh`, so the sidecar has writers in two processes.
558
+ */
559
+ serial(body) {
560
+ const locked = () => withSidecarLock(`${this.sidecar}.lock`, body, this.lockOptions);
561
+ const run = this.tail.then(locked, locked);
562
+ this.tail = run.catch(() => undefined);
563
+ return run;
564
+ }
565
+ }
566
+
567
+ // ── Sidecar lock: a zero-dependency copy of `@picasso/shared-home/lock` (Sync §3.3) ─────────────────────────────────
568
+ // `<file>.lock` is created O_CREAT|O_EXCL with mode 0600 and holds {"pid","token","acquiredAt","host"}, byte-compatible
569
+ // with shared-home, so any writer using either excludes the other. A lock is stale when its pid is dead on this host or
570
+ // it is older than `staleMs`; a breaker renames it aside to `<lock>.stale-<token>` before unlinking (no ABA), and puts
571
+ // back a fresh lock it moved by mistake with an exclusive link.
572
+
573
+ export const LOCK_STALE_MS = 30_000;
574
+ const LOCK_TIMEOUT_MS = 10_000;
575
+ const LOCK_RETRY_MS = 15;
576
+ const LOCK_MAX_RETRY_MS = 250;
577
+ const LOCK_UNREADABLE_GRACE_MS = 2_000;
578
+
579
+ export async function withSidecarLock(lockPath, body, options = {}) {
580
+ const lock = await acquireSidecarLock(lockPath, options);
581
+ try {
582
+ return await body();
583
+ } finally {
584
+ await lock.release();
585
+ }
586
+ }
587
+
588
+ export async function acquireSidecarLock(lockPath, options = {}) {
589
+ const staleMs = options.staleMs ?? LOCK_STALE_MS;
590
+ const deadline = Date.now() + (options.acquireTimeoutMs ?? LOCK_TIMEOUT_MS);
591
+ const token = randomUUID();
592
+ await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 });
593
+ for (let attempt = 0; ; attempt++) {
594
+ if (await tryCreateLock(lockPath, token)) return heldLock(lockPath, token);
595
+ const current = await readLockRecord(lockPath);
596
+ if (current === undefined || lockIsStale(current, staleMs)) {
597
+ await breakStaleLock(lockPath, current, staleMs, token);
598
+ continue;
599
+ }
600
+ const now = Date.now();
601
+ if (now >= deadline) {
602
+ throw new LifecycleError('lock-timeout', `Timed out waiting for ${lockPath} (held by pid ${current.pid}).`, { lockPath, pid: current.pid });
603
+ }
604
+ const backoff = Math.min(LOCK_RETRY_MS * 2 ** Math.min(attempt, 8), LOCK_MAX_RETRY_MS);
605
+ await sleep(Math.min(backoff + randomInt(backoff), Math.max(1, deadline - now)));
606
+ }
607
+ }
608
+
609
+ async function tryCreateLock(lockPath, token) {
610
+ let handle;
611
+ try {
612
+ handle = await open(lockPath, 'wx', 0o600);
613
+ } catch (error) {
614
+ if (error?.code === 'EEXIST') return false;
615
+ throw error;
616
+ }
617
+ try {
618
+ await handle.writeFile(JSON.stringify({ pid: process.pid, token, acquiredAt: Date.now(), host: hostname() }), 'utf8');
619
+ } finally {
620
+ await handle.close();
621
+ }
622
+ return true;
623
+ }
624
+
625
+ function heldLock(lockPath, token) {
626
+ let released = false;
627
+ return {
628
+ path: lockPath,
629
+ token,
630
+ async release() {
631
+ if (released) return;
632
+ released = true;
633
+ if ((await readLockRecord(lockPath))?.token === token) await rm(lockPath, { force: true });
634
+ },
635
+ };
636
+ }
637
+
638
+ async function readLockRecord(lockPath) {
639
+ try {
640
+ const parsed = JSON.parse(await readFile(lockPath, 'utf8'));
641
+ if (typeof parsed.pid === 'number' && typeof parsed.token === 'string' && typeof parsed.acquiredAt === 'number') return parsed;
642
+ } catch {
643
+ // missing, or its creator is between create and write
644
+ }
645
+ return undefined;
646
+ }
647
+
648
+ function lockIsStale(record, staleMs) {
649
+ if (Date.now() - record.acquiredAt > staleMs) return true;
650
+ const sameHost = record.host === undefined || record.host === hostname();
651
+ return sameHost && !pidAlive(record.pid);
652
+ }
653
+
654
+ function pidAlive(pid) {
655
+ if (!Number.isInteger(pid) || pid <= 0) return false;
656
+ try {
657
+ process.kill(pid, 0);
658
+ return true;
659
+ } catch (error) {
660
+ return error?.code === 'EPERM';
661
+ }
662
+ }
663
+
664
+ async function breakStaleLock(lockPath, observed, staleMs, breakerToken) {
665
+ if (observed === undefined) {
666
+ const info = await stat(lockPath).catch(() => undefined);
667
+ if (info === undefined || Date.now() - info.mtimeMs <= Math.min(staleMs, LOCK_UNREADABLE_GRACE_MS)) {
668
+ await sleep(LOCK_RETRY_MS);
669
+ return;
670
+ }
671
+ }
672
+ const aside = `${lockPath}.stale-${breakerToken}`;
673
+ try {
674
+ await rename(lockPath, aside);
675
+ } catch {
676
+ return; // another breaker or the owner already moved it
677
+ }
678
+ const moved = await readLockRecord(aside);
679
+ if (observed !== undefined && moved !== undefined && moved.token !== observed.token) {
680
+ await link(aside, lockPath).catch(() => undefined);
681
+ }
682
+ await rm(aside, { force: true });
683
+ }
684
+
685
+ function sleep(ms) {
686
+ return new Promise((resolveSleep) => setTimeout(resolveSleep, ms));
687
+ }
688
+
689
+ const REMOTE_METHODS = ['archive', 'unarchive', 'delete', 'restore', 'destroy', 'list', 'hideProject', 'unhideProject', 'side', 'unside', 'supersede', 'unsupersede', 'setWorkingDirectory'];
690
+
691
+ /** The gateway's source-mode Remote markers, as `@Remote()` would write them on the class prototype. */
692
+ Object.defineProperty(SessionLifecycle.prototype, REMOTE_METHOD_DESCRIPTOR, {
693
+ configurable: true,
694
+ value: Object.freeze({ version: 1, methods: Object.freeze(REMOTE_METHODS.map((method) => Object.freeze({ method, invocation: Object.freeze({ kind: 'direct' }) }))) }),
695
+ });
696
+
697
+ /** Every side conversation of `parentId`, and theirs in turn (breadth first, each once), sorted per level. */
698
+ function sideDescendants(state, parentId) {
699
+ const found = [];
700
+ const seen = new Set([parentId]);
701
+ let level = [parentId];
702
+ while (level.length > 0) {
703
+ const next = Object.entries(state.side)
704
+ .filter(([id, entry]) => !seen.has(id) && isRecord(entry) && level.includes(entry.parentId))
705
+ .map(([id]) => id)
706
+ .sort();
707
+ for (const id of next) seen.add(id);
708
+ found.push(...next);
709
+ level = next;
710
+ }
711
+ return found;
712
+ }
713
+
714
+ function requireId(sessionId) {
715
+ if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 512) {
716
+ throw new LifecycleError('bad-request', 'sessionId must be a non-empty string.');
717
+ }
718
+ return sessionId;
719
+ }
720
+
721
+ /** An absolute folder path (trailing slashes dropped), as clients group threads by working directory. */
722
+ function requireFolder(cwd) {
723
+ if (typeof cwd !== 'string' || !cwd.startsWith('/') || cwd.length > 4096) {
724
+ throw new LifecycleError('bad-request', 'cwd must be an absolute folder path.');
725
+ }
726
+ let path = cwd;
727
+ while (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1);
728
+ return path;
729
+ }
730
+
731
+ function sanitizeLabel(label) {
732
+ const out = {};
733
+ for (const key of ['title', 'cwd']) if (typeof label[key] === 'string') out[key] = label[key].slice(0, 512);
734
+ if (typeof label.updatedAt === 'number' && Number.isFinite(label.updatedAt)) out.updatedAt = label.updatedAt;
735
+ return out;
736
+ }
737
+
738
+ function isInside(root, path) {
739
+ const rel = relative(root, path);
740
+ return rel.length > 0 && !rel.startsWith('..') && !rel.startsWith(sep) && rel.split(sep).length === 2;
741
+ }
742
+
743
+ async function safeReaddir(dir) {
744
+ try {
745
+ return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
746
+ } catch {
747
+ return [];
748
+ }
749
+ }
750
+
751
+ /** The persistence root: config `root`, else `$DSH_HOME/sessions`, else `~/.dsh/sessions` (dsh-base's default). */
752
+ export function sessionsRoot(config) {
753
+ if (isRecord(config) && typeof config.root === 'string' && config.root) return config.root;
754
+ return join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'sessions');
755
+ }
756
+
757
+ /** Cordis entry. Provides `sessionLifecycle`, bound for the Typert gateway (`typertRemote`), and purges old trash. */
758
+ export function apply(ctx, config) {
759
+ const liveAgent = (id) => {
760
+ try {
761
+ return ctx.get('agents')?.get?.(id);
762
+ } catch {
763
+ return undefined;
764
+ }
765
+ };
766
+ // The thread's agent for a folder move: the live one, else the engine's own resolver (it resumes a thread at rest).
767
+ const moveFolder = async (id, folder) => {
768
+ let agent = liveAgent(id);
769
+ if (agent === undefined) {
770
+ const controller = ctx.get('sessionController');
771
+ const found = typeof controller?.resolveAgent === 'function' ? await controller.resolveAgent(id) : undefined;
772
+ agent = found?.agent;
773
+ if (agent === undefined) throw new LifecycleError('session-not-found', `No thread ${id} to move.`, { sessionId: id, cause: found?.error?.message });
774
+ }
775
+ const directory = ctx.get('workingDirectory');
776
+ if (typeof directory?.set !== 'function') throw new LifecycleError('unsupported', 'This engine cannot move a thread to another folder.');
777
+ return directory.set(agent, folder);
778
+ };
779
+ const service = new SessionLifecycle({ root: sessionsRoot(config), isRunning: (id) => liveAgent(id)?.status === 'running', moveFolder });
780
+ service.typertRemote = Object.freeze({ service, serviceKey: SERVICE_KEY, namespace: SERVICE_KEY });
781
+ ctx.provide(SERVICE_KEY, service);
782
+ const sweep = () => service.sweepSuperseded().then(
783
+ ({ swept }) => {
784
+ if (swept.length > 0) console.warn(`[picasso-session-lifecycle] moved ${swept.length} superseded session(s) older than 7 days to the trash`);
785
+ },
786
+ (error) => console.warn(`[picasso-session-lifecycle] superseded sweep failed: ${String(error)}`),
787
+ );
788
+ service.purge().then(
789
+ ({ purged }) => {
790
+ if (purged.length > 0) console.warn(`[picasso-session-lifecycle] purged ${purged.length} trashed session(s) older than 30 days`);
791
+ },
792
+ (error) => console.warn(`[picasso-session-lifecycle] trash purge failed: ${String(error)}`),
793
+ ).finally(sweep);
794
+ const daily = setInterval(sweep, 24 * 60 * 60 * 1000);
795
+ daily.unref?.();
796
+ }