@openchamber/web 1.18.3 → 1.19.0
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.
- package/README.md +1 -0
- package/dist/assets/{CodeMirrorCommentWidgets-DbUi6I9s.js → CodeMirrorCommentWidgets-DAvopJvy.js} +1 -1
- package/dist/assets/{CommitSection-Jc2_hNPE.js → CommitSection-D9cV-qR9.js} +1 -1
- package/dist/assets/{DiagramEditor-PCrYHBko.js → DiagramEditor-B9NCadU7.js} +1 -1
- package/dist/assets/DiagramView-LKGBwf4G.js +1 -0
- package/dist/assets/{DiffView-DEGlNjMH.js → DiffView-BWNq-0ov.js} +2 -2
- package/dist/assets/FilesView-DB-Q0Gkz.js +14 -0
- package/dist/assets/{GitView-C-n17voy.js → GitView-DsWXqWx3.js} +3 -3
- package/dist/assets/{JsonTreeView-BYcgdTOQ.js → JsonTreeView-h4dHASlq.js} +1 -1
- package/dist/assets/MarkdownImageGallery-n0ikH-xm.js +1 -0
- package/dist/assets/MarkdownRendererImpl-CT2mjx-s.js +12 -0
- package/dist/assets/OnboardingScreen-CDjgzxEe.js +1 -0
- package/dist/assets/{PatchDiff-Bn7bfgUv.js → PatchDiff-jPKTJje5.js} +1 -1
- package/dist/assets/{PierreDiffViewer-D1fWvrUn.js → PierreDiffViewer-D_Gt4A_6.js} +1 -1
- package/dist/assets/PlanView-UvuxIl9-.js +4 -0
- package/dist/assets/SessionSwitcherDropdown-xKU4LRuQ.js +1 -0
- package/dist/assets/SettingsView-3B9VN6Ys.js +28 -0
- package/dist/assets/SettingsWindow-CqQNDKNd.js +1 -0
- package/dist/assets/{ToolOutputDialog-BtIJkFno.js → ToolOutputDialog-PmjlAxVE.js} +6 -6
- package/dist/assets/{ToolPartDiffPreview-i3PQo6_0.js → ToolPartDiffPreview-B34Xw9wq.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-DkcusvMa.js → VirtualizedFileDiff-B37yB9jZ.js} +3 -3
- package/dist/assets/{WalkthroughView-Cc5Hd6P5.js → WalkthroughView-Bxun3k66.js} +2 -2
- package/dist/assets/{computeVirtualFileMetrics-xPena3W2.js → computeVirtualFileMetrics-DYFv_yZS.js} +2 -2
- package/dist/assets/contextPanelEmbeddedChat-BO1wRpaN.js +1 -0
- package/dist/assets/de-DbV6CLxv.js +9 -0
- package/dist/assets/document-attachments-DFAWlG3U.js +31 -0
- package/dist/assets/es-CVDlyzZ4.js +15 -0
- package/dist/assets/fr-Czc-p0g-.js +13 -0
- package/dist/assets/index-1OhiMDBz.css +1 -0
- package/dist/assets/index-BSvmTvZl.js +1 -0
- package/dist/assets/index-DzriVon2.js +7 -0
- package/dist/assets/{isDiffPlainText-Dudf-dWx.js → isDiffPlainText-DwHKxDYc.js} +1 -1
- package/dist/assets/{isFilePlainText-DS4QV1dd.js → isFilePlainText-Dwq6ILxo.js} +1 -1
- package/dist/assets/ja-dwc9NM_S.js +15 -0
- package/dist/assets/ko-Ds1DZ8FX.js +15 -0
- package/dist/assets/{lua-BgMRiT3U.js → lua-VAEuO923.js} +1 -1
- package/dist/assets/main-BF51IOVF.js +921 -0
- package/dist/assets/{main-C0DyIwTb.js → main-D7UPARut.js} +2 -2
- package/dist/assets/markdownCore-BgeBDwD3.js +2 -0
- package/dist/assets/{miniChat-CGfrxKpJ.js → miniChat-BISXSGOo.js} +2 -2
- package/dist/assets/mobile-BnYxVuvw.js +2 -0
- package/dist/assets/{patchFileDiff-C5D1OPCa.js → patchFileDiff-BEDPDypx.js} +2 -2
- package/dist/assets/pl-CLiTO7i-.js +15 -0
- package/dist/assets/pt-BR-GIimJgpK.js +15 -0
- package/dist/assets/renderElectronMiniChatApp-BaOy72Gi.js +2 -0
- package/dist/assets/{renderMobileApp-B5HA4qbi.js → renderMobileApp-BiMbzPq9.js} +7 -7
- package/dist/assets/runtimeEndpointReset-BMBRhIbf.js +15 -0
- package/dist/assets/scheduledTasksApi-01zzfzqH.js +1 -0
- package/dist/assets/{shikiHighlight-CmanopUB.js → shikiHighlight-DXYW46vW.js} +1 -1
- package/dist/assets/uk-DLfgD1ki.js +15 -0
- package/dist/assets/{useAppFontEffects-sHmU5b8u.js → useAppFontEffects-CbzHzFop.js} +139 -142
- package/dist/assets/{useInlineCommentController-gt56WkxJ.js → useInlineCommentController-CegKdDXi.js} +2 -2
- package/dist/assets/{vendor-base-ui-D_V6hAcE.js → vendor-base-ui-BYlZTzrw.js} +1 -1
- package/dist/assets/vendor-codemirror-autocomplete-DzPz9Wgq.js +1 -0
- package/dist/assets/vendor-codemirror-commands-B7H_j0iU.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-angular-CgY7_gQ1.js → vendor-codemirror-lang-angular-DEPs2M5t.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-B5Ta4enQ.js → vendor-codemirror-lang-cpp-DhkseaMo.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-VgNqFSH-.js → vendor-codemirror-lang-css-O0cZX78y.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-LxLz62pp.js → vendor-codemirror-lang-go-fMdQYcON.js} +1 -1
- package/dist/assets/vendor-codemirror-lang-html-CfgK872x.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-java-Bksi1PH4.js → vendor-codemirror-lang-java-CQj4S3zl.js} +1 -1
- package/dist/assets/vendor-codemirror-lang-javascript-Cc2ZYbgX.js +13 -0
- package/dist/assets/{vendor-codemirror-lang-jinja-C7npuDD7.js → vendor-codemirror-lang-jinja-BmZZv8g-.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-ryCw7nab.js → vendor-codemirror-lang-json-CMBS2tG9.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-BxsZJD6N.js → vendor-codemirror-lang-less-C6Eo8hVS.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-De6qch10.js → vendor-codemirror-lang-liquid-DSTR47-H.js} +1 -1
- package/dist/assets/vendor-codemirror-lang-markdown-BPGOH9ye.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-php-Cm1es33p.js → vendor-codemirror-lang-php-DD9udfPH.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-N414WYK-.js → vendor-codemirror-lang-python-HahnQaAS.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-C_WuUStH.js → vendor-codemirror-lang-rust-nLTovbjv.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-8UHTCAOM.js → vendor-codemirror-lang-sass-pL2Yc72v.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-CV3sMA5D.js → vendor-codemirror-lang-sql-BVBnan19.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-DzvC1Dhk.js → vendor-codemirror-lang-vue-BqGzJVm1.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-jlr-LDdA.js → vendor-codemirror-lang-wast-B0_m5DqU.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml-CrO63OVp.js → vendor-codemirror-lang-xml-Dj3voadT.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-dxi6CISW.js → vendor-codemirror-lang-yaml-yu-9Z5u7.js} +1 -1
- package/dist/assets/vendor-codemirror-language-BgPj_McA.js +3 -0
- package/dist/assets/{vendor-codemirror-language-data-Dihw9MtL.js → vendor-codemirror-language-data-CiAYDJXN.js} +2 -2
- package/dist/assets/vendor-codemirror-search-BmS-GmcX.js +2 -0
- package/dist/assets/{vendor-codemirror-state-CNWM3Q8V.js → vendor-codemirror-state-C9awkmn-.js} +5 -5
- package/dist/assets/vendor-codemirror-view-CiLROUVV.js +4 -0
- package/dist/assets/vendor-replit-codemirror-vim-B2DJlAhT.js +6 -0
- package/dist/assets/vendor-replit-codemirror-vim-core-FHzKdNUS.js +34 -0
- package/dist/assets/vendor-zod-adaMkgkm.js +39 -0
- package/dist/assets/{web-components-BL-Ur2Tb.js → web-components-DCLjCO9n.js} +1 -1
- package/dist/assets/zh-CN-DkeP5awK.js +15 -0
- package/dist/assets/zh-TW-BocaFm3d.js +15 -0
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/index.js +116 -3
- package/server/lib/agent-memory/actions.js +243 -0
- package/server/lib/agent-memory/actions.test.js +343 -0
- package/server/lib/agent-memory/feature-flag.js +19 -0
- package/server/lib/agent-memory/feature-flag.test.js +38 -0
- package/server/lib/agent-memory/project-resolution.js +56 -0
- package/server/lib/agent-memory/project-resolution.test.js +85 -0
- package/server/lib/agent-memory/routes.http.test.js +270 -0
- package/server/lib/agent-memory/routes.js +169 -0
- package/server/lib/agent-memory/runtime.js +427 -0
- package/server/lib/agent-memory/runtime.test.js +344 -0
- package/server/lib/agent-memory/threat-patterns.js +61 -0
- package/server/lib/agent-memory/threat-patterns.test.js +61 -0
- package/server/lib/agent-tool/DOCUMENTATION.md +14 -0
- package/server/lib/agent-tool/runtime.js +63 -13
- package/server/lib/agent-tool/runtime.test.js +85 -2
- package/server/lib/context-obligatory/runtime.js +34 -3
- package/server/lib/context-obligatory/runtime.test.js +114 -0
- package/server/lib/dev-tunnel/client.js +20 -1
- package/server/lib/dev-tunnel/tunnel.test.js +9 -0
- package/server/lib/fs/DOCUMENTATION.md +3 -0
- package/server/lib/fs/routes.js +149 -32
- package/server/lib/fs/routes.test.js +225 -0
- package/server/lib/git/DOCUMENTATION.md +8 -0
- package/server/lib/git/service.js +121 -67
- package/server/lib/git/service.test.js +129 -0
- package/server/lib/github/DOCUMENTATION.md +14 -3
- package/server/lib/github/pr-status.js +188 -83
- package/server/lib/github/pr-status.test.js +182 -0
- package/server/lib/github/routes.js +36 -30
- package/server/lib/markdown-image-grants/DOCUMENTATION.md +36 -0
- package/server/lib/markdown-image-grants/routes.js +340 -0
- package/server/lib/markdown-image-grants/routes.test.js +221 -0
- package/server/lib/notifications/template-runtime.js +2 -3
- package/server/lib/openchamber-control/action-resolution.test.js +65 -0
- package/server/lib/openchamber-control/actions.js +78 -0
- package/server/lib/openchamber-control/service.js +7 -0
- package/server/lib/openchamber-sessions/routes.js +14 -0
- package/server/lib/opencode/DOCUMENTATION.md +6 -4
- package/server/lib/opencode/claude-cli-auth.js +60 -0
- package/server/lib/opencode/claude-cli-auth.test.js +54 -0
- package/server/lib/opencode/feature-routes-runtime.js +22 -0
- package/server/lib/opencode/plugins.js +12 -3
- package/server/lib/opencode/plugins.test.js +18 -0
- package/server/lib/opencode/proxy-agent-wiring.test.js +152 -0
- package/server/lib/opencode/proxy.js +116 -6
- package/server/lib/opencode/proxy.test.js +158 -1
- package/server/lib/opencode/routes.js +4 -1
- package/server/lib/opencode/server-startup-runtime.js +22 -1
- package/server/lib/opencode/server-startup-runtime.test.js +44 -0
- package/server/lib/opencode/settings-helpers.js +11 -0
- package/server/lib/opencode/settings-helpers.test.js +35 -0
- package/server/lib/opencode/settings-runtime.js +51 -0
- package/server/lib/opencode/shared.js +120 -16
- package/server/lib/opencode/shared.test.js +185 -1
- package/server/lib/project-context/DOCUMENTATION.md +158 -0
- package/server/lib/project-context/routes.http.test.js +264 -0
- package/server/lib/project-context/routes.js +237 -0
- package/server/lib/project-context/runtime.js +667 -0
- package/server/lib/project-context/runtime.test.js +498 -0
- package/server/lib/quota/DOCUMENTATION.md +16 -1
- package/server/lib/quota/providers/claude/auth.js +113 -0
- package/server/lib/quota/providers/claude/auth.test.js +117 -0
- package/server/lib/quota/providers/claude/index.js +151 -0
- package/server/lib/quota/providers/claude/index.test.js +147 -0
- package/server/lib/quota/providers/claude/transforms.js +127 -0
- package/server/lib/quota/providers/claude/transforms.test.js +82 -0
- package/server/lib/quota/providers/command-code.js +90 -0
- package/server/lib/quota/providers/command-code.test.js +72 -0
- package/server/lib/quota/providers/index.js +22 -2
- package/server/lib/quota/providers/index.test.js +10 -1
- package/server/lib/quota/utils/formatters.js +2 -1
- package/server/lib/scheduled-tasks/runtime.js +21 -2
- package/server/lib/session-knowledge/DOCUMENTATION.md +87 -0
- package/server/lib/session-knowledge/routes.js +107 -0
- package/server/lib/session-knowledge/runtime.js +331 -0
- package/server/lib/session-knowledge/runtime.test.js +275 -0
- package/server/lib/skills-catalog/DOCUMENTATION.md +22 -22
- package/server/lib/skills-catalog/curated-sources.js +1 -1
- package/server/lib/skills-catalog/curated-sources.test.js +10 -0
- package/server/lib/small-model/index.js +8 -0
- package/server/lib/small-model/index.test.js +31 -1
- package/server/lib/small-model/routes.js +3 -1
- package/dist/assets/DiagramView-CndEcZNu.js +0 -1
- package/dist/assets/FilesView-CzUgIvUm.js +0 -14
- package/dist/assets/MarkdownImageGallery-DzHwkVIH.js +0 -1
- package/dist/assets/MarkdownRendererImpl-DUcIcWgs.js +0 -12
- package/dist/assets/OnboardingScreen-BmN0lhk4.js +0 -1
- package/dist/assets/PlanView-CWM0iyFk.js +0 -4
- package/dist/assets/SessionSwitcherDropdown-Cez-9xRh.js +0 -1
- package/dist/assets/SettingsView-Bl1drwPw.js +0 -28
- package/dist/assets/SettingsWindow-DL5axjDZ.js +0 -1
- package/dist/assets/contextPanelEmbeddedChat-tQekJUAF.js +0 -1
- package/dist/assets/de-u7gSnqWs.js +0 -9
- package/dist/assets/document-attachments-CX_YaDsu.js +0 -30
- package/dist/assets/es-T9O7aAOr.js +0 -15
- package/dist/assets/fr-Oor7ewbE.js +0 -13
- package/dist/assets/index-CVNuER6G.css +0 -1
- package/dist/assets/index-Crz1YOFl.js +0 -1
- package/dist/assets/index-iFY_N5aO.js +0 -7
- package/dist/assets/ja-DHpqbVmr.js +0 -15
- package/dist/assets/ko-CwLkS3nx.js +0 -15
- package/dist/assets/main-CAxX6DAN.js +0 -915
- package/dist/assets/markdownCore-DhfzuGXu.js +0 -2
- package/dist/assets/markdownImageAssets-BTNlRyjd.js +0 -1
- package/dist/assets/mobile-DEmhwNcV.js +0 -2
- package/dist/assets/pl-CcZILN8q.js +0 -15
- package/dist/assets/pt-BR-DYHhVK6o.js +0 -15
- package/dist/assets/renderElectronMiniChatApp-Dpbswpom.js +0 -2
- package/dist/assets/runtimeEndpointReset-cbahJ3hD.js +0 -13
- package/dist/assets/scheduledTasksApi-BxgGWTL8.js +0 -1
- package/dist/assets/uk-BA2kZR38.js +0 -15
- package/dist/assets/vendor-codemirror-autocomplete-BjbBRsUA.js +0 -1
- package/dist/assets/vendor-codemirror-commands-ARAOgp1x.js +0 -1
- package/dist/assets/vendor-codemirror-lang-html-B3Qe3OpS.js +0 -1
- package/dist/assets/vendor-codemirror-lang-javascript-Bbw3D7r0.js +0 -13
- package/dist/assets/vendor-codemirror-lang-markdown-FGQydhTc.js +0 -1
- package/dist/assets/vendor-codemirror-language-DUOssd4j.js +0 -3
- package/dist/assets/vendor-codemirror-search-8kyQdB3f.js +0 -2
- package/dist/assets/vendor-codemirror-view-DSzLbZiS.js +0 -4
- package/dist/assets/vendor-replit-codemirror-vim-B0Ecqnlh.js +0 -39
- package/dist/assets/zh-CN-dlOQK6v9.js +0 -15
- package/dist/assets/zh-TW-BnqQ-WL5.js +0 -15
- package/server/lib/quota/providers/claude.js +0 -107
|
@@ -0,0 +1,667 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project context storage: notes, todos, and plan files.
|
|
3
|
+
*
|
|
4
|
+
* The server is the sole writer of `<projectsDir>/<projectId>/context.json`.
|
|
5
|
+
* The sibling `<projectsDir>/<projectId>.json` stays client-owned (worktree
|
|
6
|
+
* setup, draft starters, project actions) and server-owned only for
|
|
7
|
+
* `version`/`scheduledTasks`; keeping the two apart is what removes the
|
|
8
|
+
* cross-process read-modify-write race that a shared file would create.
|
|
9
|
+
*
|
|
10
|
+
* Plan bodies live as markdown at `<projectsDir>/<projectId>/plans/<file>.md`
|
|
11
|
+
* and are referenced by base name only, so moving the project storage
|
|
12
|
+
* directory never invalidates a reference.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const PROJECT_CONTEXT_VERSION = 2;
|
|
16
|
+
const PROJECT_NOTE_BODY_MAX_LENGTH = 3000;
|
|
17
|
+
const PROJECT_NOTE_MAX_ITEMS = 200;
|
|
18
|
+
const PROJECT_TODO_TEXT_MAX_LENGTH = 120;
|
|
19
|
+
const PROJECT_PLAN_TITLE_MAX_LENGTH = 160;
|
|
20
|
+
const PROJECT_PLAN_BODY_MAX_LENGTH = 200_000;
|
|
21
|
+
const PROJECT_TODO_MAX_ITEMS = 500;
|
|
22
|
+
const PROJECT_PLAN_MAX_ITEMS = 500;
|
|
23
|
+
|
|
24
|
+
const PROJECT_ID_PATTERN = /^[a-zA-Z0-9._:-]+$/;
|
|
25
|
+
const PLAN_FILE_PATTERN = /^[a-zA-Z0-9._-]+\.md$/;
|
|
26
|
+
|
|
27
|
+
const asNonEmptyString = (value) => {
|
|
28
|
+
if (typeof value !== 'string') return null;
|
|
29
|
+
const trimmed = value.trim();
|
|
30
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const clampLength = (value, maxLength) => {
|
|
34
|
+
if (typeof value !== 'string') return '';
|
|
35
|
+
return value.length > maxLength ? value.slice(0, maxLength) : value;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const isObjectRecord = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
39
|
+
|
|
40
|
+
const NOTE_SOURCES = new Set(['manual', 'selection', 'agent']);
|
|
41
|
+
|
|
42
|
+
const sanitizeNoteOrigin = (value) => {
|
|
43
|
+
if (!isObjectRecord(value)) return null;
|
|
44
|
+
const sessionId = asNonEmptyString(value.sessionId);
|
|
45
|
+
const messageId = asNonEmptyString(value.messageId);
|
|
46
|
+
if (!sessionId) return null;
|
|
47
|
+
return messageId ? { sessionId, messageId } : { sessionId };
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Notes are a list of entries.
|
|
52
|
+
*
|
|
53
|
+
* Version 1 stored a single string. It is converted here rather than in a
|
|
54
|
+
* separate migration pass so that any read — including one that races another
|
|
55
|
+
* writer — sees the same shape.
|
|
56
|
+
*/
|
|
57
|
+
const sanitizeNotes = (value, now) => {
|
|
58
|
+
if (typeof value === 'string') {
|
|
59
|
+
const body = clampLength(value, PROJECT_NOTE_BODY_MAX_LENGTH).trim();
|
|
60
|
+
if (!body) return [];
|
|
61
|
+
return [{
|
|
62
|
+
id: `note_legacy_${now}`,
|
|
63
|
+
body,
|
|
64
|
+
createdAt: now,
|
|
65
|
+
updatedAt: now,
|
|
66
|
+
source: 'manual',
|
|
67
|
+
pinned: false,
|
|
68
|
+
}];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (!Array.isArray(value)) return [];
|
|
72
|
+
|
|
73
|
+
const result = [];
|
|
74
|
+
const seen = new Set();
|
|
75
|
+
for (const entry of value) {
|
|
76
|
+
if (result.length >= PROJECT_NOTE_MAX_ITEMS) break;
|
|
77
|
+
if (!isObjectRecord(entry)) continue;
|
|
78
|
+
const id = asNonEmptyString(entry.id);
|
|
79
|
+
const body = clampLength(typeof entry.body === 'string' ? entry.body : '', PROJECT_NOTE_BODY_MAX_LENGTH).trim();
|
|
80
|
+
if (!id || !body || seen.has(id)) continue;
|
|
81
|
+
seen.add(id);
|
|
82
|
+
|
|
83
|
+
const createdAt = Number.isFinite(entry.createdAt) && entry.createdAt >= 0 ? entry.createdAt : now;
|
|
84
|
+
const origin = sanitizeNoteOrigin(entry.origin);
|
|
85
|
+
result.push({
|
|
86
|
+
id,
|
|
87
|
+
body,
|
|
88
|
+
createdAt,
|
|
89
|
+
updatedAt: Number.isFinite(entry.updatedAt) && entry.updatedAt >= 0 ? entry.updatedAt : createdAt,
|
|
90
|
+
source: NOTE_SOURCES.has(entry.source) ? entry.source : 'manual',
|
|
91
|
+
pinned: entry.pinned === true,
|
|
92
|
+
...(origin ? { origin } : {}),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return result.sort((a, b) => b.createdAt - a.createdAt);
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const sanitizeTodos = (value, now) => {
|
|
100
|
+
if (!Array.isArray(value)) return [];
|
|
101
|
+
const result = [];
|
|
102
|
+
const seen = new Set();
|
|
103
|
+
for (const entry of value) {
|
|
104
|
+
if (result.length >= PROJECT_TODO_MAX_ITEMS) break;
|
|
105
|
+
if (!isObjectRecord(entry)) continue;
|
|
106
|
+
const id = asNonEmptyString(entry.id);
|
|
107
|
+
const text = clampLength(asNonEmptyString(entry.text) || '', PROJECT_TODO_TEXT_MAX_LENGTH);
|
|
108
|
+
if (!id || !text || seen.has(id)) continue;
|
|
109
|
+
seen.add(id);
|
|
110
|
+
result.push({
|
|
111
|
+
id,
|
|
112
|
+
text,
|
|
113
|
+
completed: entry.completed === true,
|
|
114
|
+
createdAt: Number.isFinite(entry.createdAt) && entry.createdAt >= 0 ? entry.createdAt : now,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
return result;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const sanitizePlanTitle = (value) => clampLength(asNonEmptyString(value) || '', PROJECT_PLAN_TITLE_MAX_LENGTH);
|
|
121
|
+
|
|
122
|
+
export const parsePlanMarkdown = (raw) => {
|
|
123
|
+
const normalized = (typeof raw === 'string' ? raw : '').replace(/\r\n?/g, '\n');
|
|
124
|
+
const match = normalized.match(/^\s*#\s+(.+?)\s*(?:\n+|$)/);
|
|
125
|
+
if (match) {
|
|
126
|
+
return {
|
|
127
|
+
title: sanitizePlanTitle(match[1]) || 'Plan',
|
|
128
|
+
body: normalized.slice(match[0].length).replace(/^\n+/, ''),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
const firstLine = normalized.split('\n').map((line) => line.trim()).find(Boolean) || 'Plan';
|
|
132
|
+
return {
|
|
133
|
+
title: sanitizePlanTitle(firstLine.replace(/^#+\s*/, '')) || 'Plan',
|
|
134
|
+
body: normalized.trim(),
|
|
135
|
+
};
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const formatPlanMarkdown = (title, body) => {
|
|
139
|
+
const normalizedTitle = sanitizePlanTitle(title) || 'Plan';
|
|
140
|
+
const normalizedBody = typeof body === 'string' ? body.trim() : '';
|
|
141
|
+
return normalizedBody ? `# ${normalizedTitle}\n\n${normalizedBody}` : `# ${normalizedTitle}\n`;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const slugifyPlanTitle = (value) => {
|
|
145
|
+
const normalized = value
|
|
146
|
+
.trim()
|
|
147
|
+
.toLowerCase()
|
|
148
|
+
.replace(/[`*_#>[\](){}.!?,:;"']/g, '')
|
|
149
|
+
.replace(/\s+/g, '-')
|
|
150
|
+
.replace(/[^a-z0-9-]/g, '-')
|
|
151
|
+
.replace(/-+/g, '-')
|
|
152
|
+
.replace(/^-+|-+$/g, '');
|
|
153
|
+
return normalized || 'plan';
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const sanitizePlanLinks = (value, now) => {
|
|
157
|
+
if (!Array.isArray(value)) return [];
|
|
158
|
+
const result = [];
|
|
159
|
+
const seenIds = new Set();
|
|
160
|
+
const seenFiles = new Set();
|
|
161
|
+
for (const entry of value) {
|
|
162
|
+
if (result.length >= PROJECT_PLAN_MAX_ITEMS) break;
|
|
163
|
+
if (!isObjectRecord(entry)) continue;
|
|
164
|
+
const id = asNonEmptyString(entry.id);
|
|
165
|
+
const file = asNonEmptyString(entry.file);
|
|
166
|
+
if (!id || !file || !PLAN_FILE_PATTERN.test(file)) continue;
|
|
167
|
+
if (seenIds.has(id) || seenFiles.has(file)) continue;
|
|
168
|
+
seenIds.add(id);
|
|
169
|
+
seenFiles.add(file);
|
|
170
|
+
result.push({
|
|
171
|
+
id,
|
|
172
|
+
file,
|
|
173
|
+
title: sanitizePlanTitle(entry.title) || 'Plan',
|
|
174
|
+
createdAt: Number.isFinite(entry.createdAt) && entry.createdAt >= 0 ? entry.createdAt : now,
|
|
175
|
+
pinned: entry.pinned === true,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
return result.sort((a, b) => b.createdAt - a.createdAt);
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const createEmptyContext = () => ({
|
|
182
|
+
version: PROJECT_CONTEXT_VERSION,
|
|
183
|
+
notes: [],
|
|
184
|
+
todos: [],
|
|
185
|
+
plans: [],
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
export const createProjectContextRuntime = (deps) => {
|
|
189
|
+
const { fsPromises, path, projectsDirPath, createId } = deps;
|
|
190
|
+
|
|
191
|
+
const idFactory = typeof createId === 'function'
|
|
192
|
+
? createId
|
|
193
|
+
: () => (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
|
|
194
|
+
? crypto.randomUUID()
|
|
195
|
+
: `plan_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`);
|
|
196
|
+
|
|
197
|
+
const writeLocks = new Map();
|
|
198
|
+
|
|
199
|
+
const sanitizeProjectId = (projectId) => {
|
|
200
|
+
const value = asNonEmptyString(projectId);
|
|
201
|
+
if (!value) {
|
|
202
|
+
throw new Error('projectId is required');
|
|
203
|
+
}
|
|
204
|
+
if (!PROJECT_ID_PATTERN.test(value)) {
|
|
205
|
+
throw new Error('projectId contains unsupported characters');
|
|
206
|
+
}
|
|
207
|
+
return value;
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
const storageDirFor = (projectId) => path.join(projectsDirPath, sanitizeProjectId(projectId));
|
|
211
|
+
const contextPathFor = (projectId) => path.join(storageDirFor(projectId), 'context.json');
|
|
212
|
+
const plansDirFor = (projectId) => path.join(storageDirFor(projectId), 'plans');
|
|
213
|
+
const legacyConfigPathFor = (projectId) => path.join(projectsDirPath, `${sanitizeProjectId(projectId)}.json`);
|
|
214
|
+
|
|
215
|
+
const readJson = async (filePath) => {
|
|
216
|
+
let raw;
|
|
217
|
+
try {
|
|
218
|
+
raw = await fsPromises.readFile(filePath, 'utf8');
|
|
219
|
+
} catch (error) {
|
|
220
|
+
if (error && error.code === 'ENOENT') return { missing: true, value: null };
|
|
221
|
+
throw error;
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
const parsed = JSON.parse(raw);
|
|
225
|
+
return { missing: false, value: isObjectRecord(parsed) ? parsed : null };
|
|
226
|
+
} catch {
|
|
227
|
+
return { missing: false, value: null };
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const writeJsonAtomic = async (filePath, value) => {
|
|
232
|
+
const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
233
|
+
await fsPromises.mkdir(path.dirname(filePath), { recursive: true });
|
|
234
|
+
await fsPromises.writeFile(temporaryPath, JSON.stringify(value, null, 2), 'utf8');
|
|
235
|
+
await fsPromises.rename(temporaryPath, filePath);
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
const withWriteLock = async (projectId, mutate) => {
|
|
239
|
+
const key = sanitizeProjectId(projectId);
|
|
240
|
+
const previous = writeLocks.get(key) || Promise.resolve();
|
|
241
|
+
let release;
|
|
242
|
+
const next = new Promise((resolve) => { release = resolve; });
|
|
243
|
+
const chained = previous.finally(() => next);
|
|
244
|
+
writeLocks.set(key, chained);
|
|
245
|
+
|
|
246
|
+
await previous;
|
|
247
|
+
try {
|
|
248
|
+
return await mutate();
|
|
249
|
+
} finally {
|
|
250
|
+
release();
|
|
251
|
+
if (writeLocks.get(key) === chained) {
|
|
252
|
+
writeLocks.delete(key);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* One-time migration of `projectNotes` / `projectTodos` / `projectPlanFiles`
|
|
259
|
+
* out of the client-owned `<projectId>.json`.
|
|
260
|
+
*
|
|
261
|
+
* Plan links carried absolute paths; those are converted to base names. A
|
|
262
|
+
* referenced file that is not already inside the plans directory is moved
|
|
263
|
+
* there so a stale absolute path from an earlier project id is recovered
|
|
264
|
+
* rather than dropped. A link whose file cannot be located at all is kept
|
|
265
|
+
* out of the result — the markdown is gone, so the link is dead either way.
|
|
266
|
+
*
|
|
267
|
+
* The legacy keys are removed only after `context.json` is durably written.
|
|
268
|
+
* A failure at any point leaves the legacy keys in place, so the migration
|
|
269
|
+
* simply runs again on the next read.
|
|
270
|
+
*/
|
|
271
|
+
const migrateFromLegacyConfig = async (projectId, now) => {
|
|
272
|
+
const legacyPath = legacyConfigPathFor(projectId);
|
|
273
|
+
const legacy = await readJson(legacyPath);
|
|
274
|
+
if (!legacy.value) {
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const hasLegacyKeys = legacy.value.projectNotes !== undefined
|
|
279
|
+
|| legacy.value.projectTodos !== undefined
|
|
280
|
+
|| legacy.value.projectPlanFiles !== undefined;
|
|
281
|
+
if (!hasLegacyKeys) {
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const plansDir = plansDirFor(projectId);
|
|
286
|
+
const links = [];
|
|
287
|
+
const rawLinks = Array.isArray(legacy.value.projectPlanFiles) ? legacy.value.projectPlanFiles : [];
|
|
288
|
+
for (const entry of rawLinks) {
|
|
289
|
+
if (!isObjectRecord(entry)) continue;
|
|
290
|
+
const id = asNonEmptyString(entry.id);
|
|
291
|
+
const absolutePath = asNonEmptyString(entry.path);
|
|
292
|
+
if (!id || !absolutePath) continue;
|
|
293
|
+
|
|
294
|
+
const file = path.basename(absolutePath);
|
|
295
|
+
if (!PLAN_FILE_PATTERN.test(file)) continue;
|
|
296
|
+
const targetPath = path.join(plansDir, file);
|
|
297
|
+
|
|
298
|
+
let raw = null;
|
|
299
|
+
try {
|
|
300
|
+
raw = await fsPromises.readFile(targetPath, 'utf8');
|
|
301
|
+
} catch (error) {
|
|
302
|
+
if (!error || error.code !== 'ENOENT') throw error;
|
|
303
|
+
// Not in the plans directory yet — recover it from the recorded path.
|
|
304
|
+
try {
|
|
305
|
+
raw = await fsPromises.readFile(absolutePath, 'utf8');
|
|
306
|
+
} catch (recoverError) {
|
|
307
|
+
if (!recoverError || recoverError.code !== 'ENOENT') throw recoverError;
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
await fsPromises.mkdir(plansDir, { recursive: true });
|
|
311
|
+
await fsPromises.writeFile(targetPath, raw, 'utf8');
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
links.push({
|
|
315
|
+
id,
|
|
316
|
+
file,
|
|
317
|
+
title: parsePlanMarkdown(raw).title,
|
|
318
|
+
createdAt: Number.isFinite(entry.createdAt) && entry.createdAt >= 0 ? entry.createdAt : now,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const migrated = {
|
|
323
|
+
version: PROJECT_CONTEXT_VERSION,
|
|
324
|
+
notes: sanitizeNotes(legacy.value.projectNotes, now),
|
|
325
|
+
todos: sanitizeTodos(legacy.value.projectTodos, now),
|
|
326
|
+
plans: sanitizePlanLinks(links, now),
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
await writeJsonAtomic(contextPathFor(projectId), migrated);
|
|
330
|
+
|
|
331
|
+
const remaining = { ...legacy.value };
|
|
332
|
+
delete remaining.projectNotes;
|
|
333
|
+
delete remaining.projectTodos;
|
|
334
|
+
delete remaining.projectPlanFiles;
|
|
335
|
+
await writeJsonAtomic(legacyPath, remaining);
|
|
336
|
+
|
|
337
|
+
return migrated;
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Read the stored context.
|
|
342
|
+
*
|
|
343
|
+
* Distinguishes the three states the caller must not conflate: a missing
|
|
344
|
+
* file is authoritative empty, malformed JSON is a failure, and an I/O
|
|
345
|
+
* error propagates. Never returns an empty context to paper over a read
|
|
346
|
+
* that did not succeed.
|
|
347
|
+
*
|
|
348
|
+
* Deliberately does NOT take the write lock: every mutator calls this while
|
|
349
|
+
* already holding it, so locking here would deadlock. The legacy migration
|
|
350
|
+
* it can trigger is safe unlocked — both of its writes are atomic renames
|
|
351
|
+
* of identical content, so concurrent migrations converge instead of
|
|
352
|
+
* interleaving.
|
|
353
|
+
*/
|
|
354
|
+
const readContext = async (projectId) => {
|
|
355
|
+
const now = Date.now();
|
|
356
|
+
const stored = await readJson(contextPathFor(projectId));
|
|
357
|
+
|
|
358
|
+
if (!stored.missing && !stored.value) {
|
|
359
|
+
throw new Error('Stored project context is malformed');
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
if (stored.missing) {
|
|
363
|
+
const migrated = await migrateFromLegacyConfig(projectId, now);
|
|
364
|
+
if (migrated) {
|
|
365
|
+
return {
|
|
366
|
+
version: PROJECT_CONTEXT_VERSION,
|
|
367
|
+
notes: sanitizeNotes(migrated.notes, now),
|
|
368
|
+
todos: sanitizeTodos(migrated.todos, now),
|
|
369
|
+
plans: sanitizePlanLinks(migrated.plans, now),
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
return createEmptyContext();
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
return {
|
|
376
|
+
version: PROJECT_CONTEXT_VERSION,
|
|
377
|
+
notes: sanitizeNotes(stored.value.notes, now),
|
|
378
|
+
todos: sanitizeTodos(stored.value.todos, now),
|
|
379
|
+
plans: sanitizePlanLinks(stored.value.plans, now),
|
|
380
|
+
};
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
const writeContext = async (projectId, context) => {
|
|
384
|
+
await writeJsonAtomic(contextPathFor(projectId), {
|
|
385
|
+
version: PROJECT_CONTEXT_VERSION,
|
|
386
|
+
notes: context.notes,
|
|
387
|
+
todos: context.todos,
|
|
388
|
+
plans: context.plans,
|
|
389
|
+
});
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
const saveTodos = async (projectId, todos) => {
|
|
393
|
+
return withWriteLock(projectId, async () => {
|
|
394
|
+
const now = Date.now();
|
|
395
|
+
const current = await readContext(projectId);
|
|
396
|
+
const next = { ...current, todos: sanitizeTodos(todos, now) };
|
|
397
|
+
await writeContext(projectId, next);
|
|
398
|
+
return next;
|
|
399
|
+
});
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Notes are addressed individually.
|
|
404
|
+
*
|
|
405
|
+
* Splitting them from todos is what lets the panel stop writing both fields
|
|
406
|
+
* on every keystroke-driven save: a todo toggle can no longer clobber notes
|
|
407
|
+
* the user is still typing, and an agent-authored note can no longer lose a
|
|
408
|
+
* concurrent todo change.
|
|
409
|
+
*/
|
|
410
|
+
const createNote = async (projectId, value) => {
|
|
411
|
+
const body = clampLength(typeof value?.body === 'string' ? value.body : '', PROJECT_NOTE_BODY_MAX_LENGTH).trim();
|
|
412
|
+
if (!body) {
|
|
413
|
+
throw new Error('body is required');
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
return withWriteLock(projectId, async () => {
|
|
417
|
+
const now = Date.now();
|
|
418
|
+
const current = await readContext(projectId);
|
|
419
|
+
if (current.notes.length >= PROJECT_NOTE_MAX_ITEMS) {
|
|
420
|
+
throw new Error(`A project can hold at most ${PROJECT_NOTE_MAX_ITEMS} notes`);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const note = {
|
|
424
|
+
id: idFactory(),
|
|
425
|
+
body,
|
|
426
|
+
createdAt: now,
|
|
427
|
+
updatedAt: now,
|
|
428
|
+
source: NOTE_SOURCES.has(value?.source) ? value.source : 'manual',
|
|
429
|
+
pinned: false,
|
|
430
|
+
...(sanitizeNoteOrigin(value?.origin) ? { origin: sanitizeNoteOrigin(value.origin) } : {}),
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
const next = { ...current, notes: [note, ...current.notes] };
|
|
434
|
+
await writeContext(projectId, next);
|
|
435
|
+
return { note, context: next };
|
|
436
|
+
});
|
|
437
|
+
};
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Patch one note. Omitted fields are left alone, so pinning a note cannot
|
|
441
|
+
* roll back an edit that landed between the two requests.
|
|
442
|
+
*/
|
|
443
|
+
const updateNote = async (projectId, noteId, patch) => {
|
|
444
|
+
const id = asNonEmptyString(noteId);
|
|
445
|
+
if (!id) {
|
|
446
|
+
throw new Error('noteId is required');
|
|
447
|
+
}
|
|
448
|
+
const hasBody = typeof patch?.body === 'string';
|
|
449
|
+
const hasPinned = typeof patch?.pinned === 'boolean';
|
|
450
|
+
if (!hasBody && !hasPinned) {
|
|
451
|
+
throw new Error('body or pinned is required');
|
|
452
|
+
}
|
|
453
|
+
const body = hasBody ? clampLength(patch.body, PROJECT_NOTE_BODY_MAX_LENGTH).trim() : null;
|
|
454
|
+
if (hasBody && !body) {
|
|
455
|
+
throw new Error('body is required');
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
return withWriteLock(projectId, async () => {
|
|
459
|
+
const now = Date.now();
|
|
460
|
+
const current = await readContext(projectId);
|
|
461
|
+
const existing = current.notes.find((note) => note.id === id);
|
|
462
|
+
if (!existing) {
|
|
463
|
+
return null;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const note = {
|
|
467
|
+
...existing,
|
|
468
|
+
...(hasBody ? { body, updatedAt: now } : {}),
|
|
469
|
+
...(hasPinned ? { pinned: patch.pinned } : {}),
|
|
470
|
+
};
|
|
471
|
+
const next = { ...current, notes: current.notes.map((entry) => (entry.id === id ? note : entry)) };
|
|
472
|
+
await writeContext(projectId, next);
|
|
473
|
+
return { note, context: next };
|
|
474
|
+
});
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
const deleteNote = async (projectId, noteId) => {
|
|
478
|
+
const id = asNonEmptyString(noteId);
|
|
479
|
+
if (!id) {
|
|
480
|
+
throw new Error('noteId is required');
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
return withWriteLock(projectId, async () => {
|
|
484
|
+
const current = await readContext(projectId);
|
|
485
|
+
if (!current.notes.some((note) => note.id === id)) {
|
|
486
|
+
return { deleted: false, context: current };
|
|
487
|
+
}
|
|
488
|
+
const next = { ...current, notes: current.notes.filter((note) => note.id !== id) };
|
|
489
|
+
await writeContext(projectId, next);
|
|
490
|
+
return { deleted: true, context: next };
|
|
491
|
+
});
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
const readPlan = async (projectId, planId) => {
|
|
495
|
+
const id = asNonEmptyString(planId);
|
|
496
|
+
if (!id) {
|
|
497
|
+
throw new Error('planId is required');
|
|
498
|
+
}
|
|
499
|
+
const context = await readContext(projectId);
|
|
500
|
+
const link = context.plans.find((entry) => entry.id === id);
|
|
501
|
+
if (!link) {
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
let raw;
|
|
506
|
+
try {
|
|
507
|
+
raw = await fsPromises.readFile(path.join(plansDirFor(projectId), link.file), 'utf8');
|
|
508
|
+
} catch (error) {
|
|
509
|
+
if (error && error.code === 'ENOENT') return null;
|
|
510
|
+
throw error;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const parsed = parsePlanMarkdown(raw);
|
|
514
|
+
return { id: link.id, file: link.file, createdAt: link.createdAt, title: parsed.title, body: parsed.body, raw };
|
|
515
|
+
};
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Overwrite a plan's markdown in place.
|
|
519
|
+
*
|
|
520
|
+
* Takes the whole raw document, because the editor surface owns the file
|
|
521
|
+
* verbatim — round-tripping through title + body would rewrite the heading
|
|
522
|
+
* and silently reformat what the user typed. The manifest title is
|
|
523
|
+
* re-derived from the saved content so the list never drifts from the file.
|
|
524
|
+
*
|
|
525
|
+
* The file name is deliberately not regenerated on a title change: it is the
|
|
526
|
+
* stable identity behind the link, and renaming it would strand the markdown
|
|
527
|
+
* if the manifest write failed afterwards.
|
|
528
|
+
*/
|
|
529
|
+
const updatePlan = async (projectId, planId, value) => {
|
|
530
|
+
const id = asNonEmptyString(planId);
|
|
531
|
+
if (!id) {
|
|
532
|
+
throw new Error('planId is required');
|
|
533
|
+
}
|
|
534
|
+
if (typeof value?.raw !== 'string') {
|
|
535
|
+
throw new Error('raw is required');
|
|
536
|
+
}
|
|
537
|
+
const raw = clampLength(value.raw, PROJECT_PLAN_BODY_MAX_LENGTH);
|
|
538
|
+
|
|
539
|
+
return withWriteLock(projectId, async () => {
|
|
540
|
+
const current = await readContext(projectId);
|
|
541
|
+
const link = current.plans.find((entry) => entry.id === id);
|
|
542
|
+
if (!link) {
|
|
543
|
+
return null;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const filePath = path.join(plansDirFor(projectId), link.file);
|
|
547
|
+
// Refuse to recreate a file that was deleted underneath us: the link is
|
|
548
|
+
// already dead, and writing here would resurrect it with editor content
|
|
549
|
+
// the user believed was discarded.
|
|
550
|
+
try {
|
|
551
|
+
await fsPromises.access(filePath);
|
|
552
|
+
} catch (error) {
|
|
553
|
+
if (error && error.code === 'ENOENT') return null;
|
|
554
|
+
throw error;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
await fsPromises.writeFile(filePath, raw, 'utf8');
|
|
558
|
+
|
|
559
|
+
const parsed = parsePlanMarkdown(raw);
|
|
560
|
+
const nextLink = { ...link, title: parsed.title };
|
|
561
|
+
const next = {
|
|
562
|
+
...current,
|
|
563
|
+
plans: current.plans.map((entry) => (entry.id === id ? nextLink : entry)),
|
|
564
|
+
};
|
|
565
|
+
await writeContext(projectId, next);
|
|
566
|
+
|
|
567
|
+
return { plan: nextLink, context: next, title: parsed.title, body: parsed.body, raw };
|
|
568
|
+
});
|
|
569
|
+
};
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Create a plan from title + body.
|
|
573
|
+
*
|
|
574
|
+
* The markdown file is written before the manifest entry. A failure after
|
|
575
|
+
* the file write leaves an unreferenced markdown file rather than a
|
|
576
|
+
* manifest entry pointing at nothing — the orphan is inert, a dangling
|
|
577
|
+
* entry would surface as a broken row in the UI.
|
|
578
|
+
*/
|
|
579
|
+
const createPlan = async (projectId, value) => {
|
|
580
|
+
const title = sanitizePlanTitle(value?.title) || 'Plan';
|
|
581
|
+
const body = clampLength(typeof value?.body === 'string' ? value.body : '', PROJECT_PLAN_BODY_MAX_LENGTH);
|
|
582
|
+
|
|
583
|
+
return withWriteLock(projectId, async () => {
|
|
584
|
+
const current = await readContext(projectId);
|
|
585
|
+
const createdAt = Date.now();
|
|
586
|
+
const plansDir = plansDirFor(projectId);
|
|
587
|
+
await fsPromises.mkdir(plansDir, { recursive: true });
|
|
588
|
+
|
|
589
|
+
const baseName = `${createdAt}-${slugifyPlanTitle(title)}`;
|
|
590
|
+
let file = `${baseName}.md`;
|
|
591
|
+
let attempt = 1;
|
|
592
|
+
while (current.plans.some((entry) => entry.file === file)) {
|
|
593
|
+
file = `${baseName}-${attempt}.md`;
|
|
594
|
+
attempt += 1;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
await fsPromises.writeFile(path.join(plansDir, file), formatPlanMarkdown(title, body), 'utf8');
|
|
598
|
+
|
|
599
|
+
const link = { id: idFactory(), file, title, createdAt, pinned: false };
|
|
600
|
+
const next = { ...current, plans: [link, ...current.plans] };
|
|
601
|
+
await writeContext(projectId, next);
|
|
602
|
+
return { plan: link, context: next };
|
|
603
|
+
});
|
|
604
|
+
};
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Delete a plan.
|
|
608
|
+
*
|
|
609
|
+
* The manifest entry is removed first so a failed file unlink cannot leave
|
|
610
|
+
* the UI showing a plan that no longer opens. The leftover markdown is
|
|
611
|
+
* unreferenced and harmless.
|
|
612
|
+
*/
|
|
613
|
+
/** Pin state is patched on its own so it cannot roll back a concurrent edit. */
|
|
614
|
+
const setPlanPinned = async (projectId, planId, pinned) => {
|
|
615
|
+
const id = asNonEmptyString(planId);
|
|
616
|
+
if (!id) {
|
|
617
|
+
throw new Error('planId is required');
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
return withWriteLock(projectId, async () => {
|
|
621
|
+
const current = await readContext(projectId);
|
|
622
|
+
const existing = current.plans.find((entry) => entry.id === id);
|
|
623
|
+
if (!existing) {
|
|
624
|
+
return null;
|
|
625
|
+
}
|
|
626
|
+
const plan = { ...existing, pinned: pinned === true };
|
|
627
|
+
const next = { ...current, plans: current.plans.map((entry) => (entry.id === id ? plan : entry)) };
|
|
628
|
+
await writeContext(projectId, next);
|
|
629
|
+
return { plan, context: next };
|
|
630
|
+
});
|
|
631
|
+
};
|
|
632
|
+
|
|
633
|
+
const deletePlan = async (projectId, planId) => {
|
|
634
|
+
const id = asNonEmptyString(planId);
|
|
635
|
+
if (!id) {
|
|
636
|
+
throw new Error('planId is required');
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
return withWriteLock(projectId, async () => {
|
|
640
|
+
const current = await readContext(projectId);
|
|
641
|
+
const link = current.plans.find((entry) => entry.id === id);
|
|
642
|
+
if (!link) {
|
|
643
|
+
return { deleted: false, context: current };
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
const next = { ...current, plans: current.plans.filter((entry) => entry.id !== id) };
|
|
647
|
+
await writeContext(projectId, next);
|
|
648
|
+
await fsPromises.rm(path.join(plansDirFor(projectId), link.file), { force: true });
|
|
649
|
+
return { deleted: true, context: next };
|
|
650
|
+
});
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
return {
|
|
654
|
+
readContext,
|
|
655
|
+
saveTodos,
|
|
656
|
+
createNote,
|
|
657
|
+
updateNote,
|
|
658
|
+
deleteNote,
|
|
659
|
+
readPlan,
|
|
660
|
+
updatePlan,
|
|
661
|
+
createPlan,
|
|
662
|
+
setPlanPinned,
|
|
663
|
+
deletePlan,
|
|
664
|
+
contextPathFor,
|
|
665
|
+
plansDirFor,
|
|
666
|
+
};
|
|
667
|
+
};
|