@infodb/p3 0.4.0 → 0.6.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.
Files changed (209) hide show
  1. package/README.md +1 -0
  2. package/bin/p3.mjs +11 -5
  3. package/dist/web/assets/Outputs-CQi0oba1.js +1 -0
  4. package/dist/web/assets/RequestStatus-grC0F_SQ.js +1 -0
  5. package/dist/web/assets/Tabs-BJRGzidj.js +1 -0
  6. package/dist/web/assets/TagInput-DkuISbfK.js +1 -0
  7. package/dist/web/assets/TaskDrawer-CysOMAjG.js +3 -0
  8. package/dist/web/assets/_requestId-BQCwOAbs.js +30 -0
  9. package/dist/web/assets/_requestId-DgSOUH78.js +1 -0
  10. package/dist/web/assets/{ui-DdOGYj9z.js → appCtx-DCiGJFAe.js} +1 -1
  11. package/dist/web/assets/board-BsntpZXP.js +1 -0
  12. package/dist/web/assets/done-Bhxqy7bH.js +1 -0
  13. package/dist/web/assets/index-BF1xMdJo.css +2 -0
  14. package/dist/web/assets/index-BTuEPzgc.js +12 -0
  15. package/dist/web/assets/new-BwknRX3V.js +1 -0
  16. package/dist/web/assets/{preflightInput-DMxqnvF8.js → preflightInput-BAeEJYUK.js} +1 -1
  17. package/dist/web/assets/preload-helper-B40dBmwL.js +1 -0
  18. package/dist/web/assets/progressTree-DgrdDFih.js +1 -0
  19. package/dist/web/assets/release-notes-AgwbykyG.js +3 -0
  20. package/dist/web/assets/requestData-w6fhCYmh.js +1 -0
  21. package/dist/web/assets/routes-Bu3bhOaC.js +3 -0
  22. package/dist/web/assets/settings-BkV8KeQk.js +1 -0
  23. package/dist/web/index.html +4 -4
  24. package/docs/architecture.md +271 -3
  25. package/docs/development.md +22 -9
  26. package/docs/how-to-use.md +83 -7
  27. package/docs/installation.md +8 -6
  28. package/docs/publishing.md +4 -2
  29. package/lib/cli/args.js +172 -0
  30. package/lib/cli/chatgpt.js +70 -0
  31. package/lib/cli/codex.js +30 -0
  32. package/lib/cli/format.js +9 -0
  33. package/{src/cli/help.ts → lib/cli/help.js} +10 -8
  34. package/lib/cli/main.js +327 -0
  35. package/lib/cli/output.js +110 -0
  36. package/lib/cli/preflightCommands.js +301 -0
  37. package/lib/cli/project.js +649 -0
  38. package/lib/cli/readOnly.js +36 -0
  39. package/lib/cli/releaseNotesCommands.js +197 -0
  40. package/lib/cli/render.js +58 -0
  41. package/lib/cli/requestCommands.js +191 -0
  42. package/lib/cli/showView.js +100 -0
  43. package/lib/cli/taskCommands.js +152 -0
  44. package/lib/cli/userConfig.js +64 -0
  45. package/{src/core/chatgpt.ts → lib/core/chatgpt.js} +10 -16
  46. package/lib/core/context.js +41 -0
  47. package/lib/core/hierarchy.js +158 -0
  48. package/lib/core/machineSettings.js +146 -0
  49. package/lib/core/machineSettingsEdit.js +148 -0
  50. package/lib/core/ops.js +120 -0
  51. package/lib/core/preflight/carryover.js +105 -0
  52. package/lib/core/preflight/codexEngine.js +687 -0
  53. package/lib/core/preflight/codexImage.js +61 -0
  54. package/lib/core/preflight/diagnose.js +95 -0
  55. package/lib/core/preflight/engine.js +58 -0
  56. package/lib/core/preflight/input.js +83 -0
  57. package/lib/core/preflight/launch.js +68 -0
  58. package/lib/core/preflight/mockEngine.js +175 -0
  59. package/lib/core/preflight/render.js +304 -0
  60. package/lib/core/preflight/service.js +883 -0
  61. package/lib/core/preflight/split.js +83 -0
  62. package/lib/core/preflight/uiMaterials.js +281 -0
  63. package/lib/core/preflight/uiRender.js +89 -0
  64. package/lib/core/preflight/wireframe.js +63 -0
  65. package/lib/core/preflight/xlsx.js +324 -0
  66. package/lib/core/projectRegistry.js +207 -0
  67. package/lib/core/redact.js +28 -0
  68. package/lib/core/releaseNotes/completeRequests.js +106 -0
  69. package/lib/core/releaseNotes/generate.js +266 -0
  70. package/lib/core/releaseNotes/material.js +141 -0
  71. package/lib/core/releaseNotes/mockSummarizer.js +26 -0
  72. package/lib/core/releaseNotes/service.js +83 -0
  73. package/lib/core/releaseNotes/store.js +209 -0
  74. package/lib/core/repoAdmin.js +82 -0
  75. package/lib/core/repoRefs.js +72 -0
  76. package/lib/core/requestOps.js +164 -0
  77. package/lib/core/requestStatus.js +171 -0
  78. package/lib/core/store/attachments.js +242 -0
  79. package/lib/core/store/collection.js +254 -0
  80. package/lib/core/store/frontmatter.js +18 -0
  81. package/lib/core/store/fsutil.js +84 -0
  82. package/lib/core/store/locate.js +162 -0
  83. package/lib/core/store/normalize.js +152 -0
  84. package/lib/core/store/noteStore.js +59 -0
  85. package/lib/core/store/preflightStore.js +161 -0
  86. package/lib/core/store/projectFile.js +99 -0
  87. package/lib/core/store/workspace.js +320 -0
  88. package/lib/core/supersede.js +69 -0
  89. package/lib/core/userConfig.js +158 -0
  90. package/{src/core/userTheme.ts → lib/core/userTheme.js} +11 -13
  91. package/lib/core/workTargets.js +106 -0
  92. package/lib/server/api/chatgptRoutes.js +46 -0
  93. package/{src/server/api/local.ts → lib/server/api/local.js} +23 -22
  94. package/lib/server/api/manifest.js +147 -0
  95. package/lib/server/api/projectsRoutes.js +82 -0
  96. package/lib/server/api/releaseNoteRoutes.js +88 -0
  97. package/lib/server/api/repoRoutes.js +67 -0
  98. package/lib/server/api/routes.js +416 -0
  99. package/lib/server/api/userThemeRoutes.js +60 -0
  100. package/lib/server/server.js +85 -0
  101. package/lib/shared/dates.js +10 -0
  102. package/{src/shared/directTask.ts → lib/shared/directTask.js} +3 -11
  103. package/lib/shared/hierarchy.js +135 -0
  104. package/lib/shared/milestoneOrder.js +45 -0
  105. package/lib/shared/preflightInput.js +19 -0
  106. package/lib/shared/refs.js +44 -0
  107. package/lib/shared/repos.js +69 -0
  108. package/lib/shared/scopeView.js +39 -0
  109. package/{src/shared/tags.ts → lib/shared/tags.js} +9 -14
  110. package/lib/shared/types.js +74 -0
  111. package/lib/shared/workTarget.js +31 -0
  112. package/package.json +4 -7
  113. package/skills/p3/SKILL.md +10 -0
  114. package/dist/web/assets/Outputs-5Hby-S5Q.js +0 -1
  115. package/dist/web/assets/RequestStatus-CTkGjT02.js +0 -1
  116. package/dist/web/assets/TagInput-Rj3PNOAF.js +0 -1
  117. package/dist/web/assets/TaskDrawer-DtPhiYxP.js +0 -3
  118. package/dist/web/assets/_requestId-CGvAfIkB.js +0 -30
  119. package/dist/web/assets/_requestId-DxfYhgAq.js +0 -1
  120. package/dist/web/assets/board-wt47lfrE.js +0 -1
  121. package/dist/web/assets/done-C9Ct7ssb.js +0 -1
  122. package/dist/web/assets/index-BTFL2rpp.js +0 -12
  123. package/dist/web/assets/index-DAyBsvua.css +0 -2
  124. package/dist/web/assets/new-e4ID2vQV.js +0 -1
  125. package/dist/web/assets/preload-helper-DhIyFaOW.js +0 -1
  126. package/dist/web/assets/release-notes-CQ0d2r0k.js +0 -3
  127. package/dist/web/assets/requestData-BDZqyl35.js +0 -1
  128. package/dist/web/assets/routes-Bipv3lwJ.js +0 -2
  129. package/dist/web/assets/settings-Dwh8fj6p.js +0 -1
  130. package/src/cli/args.ts +0 -186
  131. package/src/cli/chatgpt.ts +0 -74
  132. package/src/cli/codex.ts +0 -28
  133. package/src/cli/format.ts +0 -9
  134. package/src/cli/main.ts +0 -337
  135. package/src/cli/output.ts +0 -117
  136. package/src/cli/preflightCommands.ts +0 -245
  137. package/src/cli/project.ts +0 -675
  138. package/src/cli/readOnly.ts +0 -36
  139. package/src/cli/releaseNotesCommands.ts +0 -198
  140. package/src/cli/render.ts +0 -60
  141. package/src/cli/requestCommands.ts +0 -172
  142. package/src/cli/showView.ts +0 -110
  143. package/src/cli/taskCommands.ts +0 -167
  144. package/src/cli/userConfig.ts +0 -58
  145. package/src/core/context.ts +0 -58
  146. package/src/core/machineSettings.ts +0 -207
  147. package/src/core/machineSettingsEdit.ts +0 -156
  148. package/src/core/ops.ts +0 -114
  149. package/src/core/preflight/carryover.ts +0 -133
  150. package/src/core/preflight/codexEngine.ts +0 -703
  151. package/src/core/preflight/codexImage.ts +0 -98
  152. package/src/core/preflight/diagnose.ts +0 -124
  153. package/src/core/preflight/engine.ts +0 -92
  154. package/src/core/preflight/input.ts +0 -65
  155. package/src/core/preflight/launch.ts +0 -86
  156. package/src/core/preflight/mockEngine.ts +0 -145
  157. package/src/core/preflight/render.ts +0 -339
  158. package/src/core/preflight/service.ts +0 -707
  159. package/src/core/preflight/uiMaterials.ts +0 -272
  160. package/src/core/preflight/uiRender.ts +0 -84
  161. package/src/core/preflight/wireframe.ts +0 -69
  162. package/src/core/preflight/xlsx.ts +0 -328
  163. package/src/core/projectRegistry.ts +0 -264
  164. package/src/core/redact.ts +0 -31
  165. package/src/core/releaseNotes/completeRequests.ts +0 -102
  166. package/src/core/releaseNotes/generate.ts +0 -283
  167. package/src/core/releaseNotes/material.ts +0 -114
  168. package/src/core/releaseNotes/mockSummarizer.ts +0 -28
  169. package/src/core/releaseNotes/service.ts +0 -110
  170. package/src/core/releaseNotes/store.ts +0 -216
  171. package/src/core/repoAdmin.ts +0 -81
  172. package/src/core/repoRefs.ts +0 -90
  173. package/src/core/requestOps.ts +0 -140
  174. package/src/core/requestStatus.ts +0 -58
  175. package/src/core/store/attachments.ts +0 -228
  176. package/src/core/store/collection.ts +0 -282
  177. package/src/core/store/frontmatter.ts +0 -22
  178. package/src/core/store/fsutil.ts +0 -90
  179. package/src/core/store/locate.ts +0 -181
  180. package/src/core/store/normalize.ts +0 -155
  181. package/src/core/store/noteStore.ts +0 -56
  182. package/src/core/store/preflightStore.ts +0 -136
  183. package/src/core/store/projectFile.ts +0 -101
  184. package/src/core/store/workspace.ts +0 -328
  185. package/src/core/supersede.ts +0 -74
  186. package/src/core/userConfig.ts +0 -205
  187. package/src/core/workTargets.ts +0 -120
  188. package/src/server/api/chatgptRoutes.ts +0 -49
  189. package/src/server/api/manifest.ts +0 -135
  190. package/src/server/api/projectsRoutes.ts +0 -89
  191. package/src/server/api/releaseNoteRoutes.ts +0 -89
  192. package/src/server/api/repoRoutes.ts +0 -67
  193. package/src/server/api/routes.ts +0 -382
  194. package/src/server/api/userThemeRoutes.ts +0 -62
  195. package/src/server/server.ts +0 -108
  196. package/src/shared/dates.ts +0 -12
  197. package/src/shared/milestoneOrder.ts +0 -44
  198. package/src/shared/preflightInput.ts +0 -27
  199. package/src/shared/refs.ts +0 -55
  200. package/src/shared/repos.ts +0 -113
  201. package/src/shared/scopeView.ts +0 -48
  202. package/src/shared/types.ts +0 -730
  203. package/src/shared/workTarget.ts +0 -44
  204. /package/{src → lib}/core/preflight/launcher.mjs +0 -0
  205. /package/{src → lib}/core/preflight/mock-ui.html +0 -0
  206. /package/{src → lib}/core/preflight/mock-ui.png +0 -0
  207. /package/{src → lib}/core/preflight/render-image/Dockerfile +0 -0
  208. /package/{src → lib}/core/preflight/render-image/fonts-ja.conf +0 -0
  209. /package/{src → lib}/core/preflight/render-image/render.mjs +0 -0
@@ -0,0 +1,171 @@
1
+ import { Hierarchy } from "../shared/hierarchy.js";
2
+ /**
3
+ * 要望の「対応済」(resolved)の規則。CLI と API のどちらから変えても同じように効くよう、ここにまとめる。
4
+ *
5
+ * - 対応済にできるのは、自分のタスクが全部完了(status=done)で読めないタスクファイルが無く、見送り以外の子が全部
6
+ * 対応済か完了済(その配下も同じ。外で編集された子の未完了も見つける)で、配下に親子の問題が無く、自分のタスクか
7
+ * 見送り以外の子が1件以上あるときだけ。見送りの子は対象外(excluded)。人の「済み」(checkedAt)・PR・マージは条件にしない。
8
+ * 置き換えられたタスクも、残っていれば数える
9
+ * - 子のある要望を完了済(done)にするときも同じ条件を確かめる(子の無い要望の完了済は今までどおり確かめない)
10
+ * - 対応済の要望に未完了のタスクができたら(足した・完了から戻した・再評価でタスク化した)進行中に戻す。配下に未完了が
11
+ * できたら、対応済の祖先も進行中に戻し、完了済の祖先は変えずに警告(ancestor_done)を返す
12
+ * - 最後のタスクを完了にしても自動では対応済・完了済にしない(作業を終えた側・人が明示的に設定する)
13
+ */
14
+ export class StatusRuleError extends Error {
15
+ }
16
+ const finished = (s) => s === "resolved" || s === "done";
17
+ /** 読み込んである要望の親子(読めない要望も問題として扱う) */
18
+ export function hierarchyNow(ws) {
19
+ return new Hierarchy({ requests: ws.requests.list(), unreadable: ws.requests.errors.keys() });
20
+ }
21
+ /**
22
+ * 読み込んである状態で判定する(書かない・読み直さない)。リリースノートの材料のように、読み直した Workspace の上で使う。
23
+ * 子孫は見送りの子とその下を除いて辿る
24
+ */
25
+ export function completionCheckOf(ws, h, rid) {
26
+ const col = ws.tasksOf(rid);
27
+ const broken = [...col.errors.keys()];
28
+ const kids = h.children(rid);
29
+ const excluded = kids.filter((k) => k.status === "rejected").map((k) => k.id);
30
+ const result = (blocker) => ({ ...(blocker ? { blocker } : {}), excluded });
31
+ if (broken.length)
32
+ return result(`読めないタスクファイルがあります: ${broken.join(", ")}(直してから対応済にしてください)`);
33
+ const self = h.get(rid);
34
+ const own = self ? h.issueOf(self) : undefined;
35
+ if (own)
36
+ return result(`親子の問題があります: ${own.message}`);
37
+ const tasks = col.list();
38
+ const live = kids.filter((k) => k.status !== "rejected");
39
+ if (!tasks.length && !live.length) {
40
+ return result(kids.length
41
+ ? `タスクが無く、子の要望が全部見送りです(対象外: ${excluded.join(", ")})。対応済にできません`
42
+ : "タスクがありません(タスクの無い要望は対応済にできません)");
43
+ }
44
+ const open = tasks.filter((t) => t.status !== "done");
45
+ if (open.length)
46
+ return result(`完了していないタスクがあります: ${open.map((t) => `${t.id}(${t.status})`).join(", ")}(完了させるか、不要ならアーカイブしてから対応済にしてください)`);
47
+ // 配下: 見送り以外の子孫が全部 対応済・完了済で、その自分のタスクも全部完了
48
+ const problems = [];
49
+ const seen = new Set([rid]);
50
+ const walk = (pid) => {
51
+ for (const c of h.children(pid)) {
52
+ if (c.status === "rejected" || seen.has(c.id))
53
+ continue;
54
+ seen.add(c.id);
55
+ const issue = h.issueOf(c);
56
+ const ccol = ws.tasksOf(c.id);
57
+ const cbroken = [...ccol.errors.keys()];
58
+ const copen = ccol.list().filter((t) => t.status !== "done");
59
+ if (issue)
60
+ problems.push(issue.message);
61
+ else if (!finished(c.status))
62
+ problems.push(`子 ${c.id} が未完了(${c.status})`);
63
+ else if (cbroken.length)
64
+ problems.push(`子 ${c.id} に読めないタスクファイル(${cbroken.join(", ")})`);
65
+ else if (copen.length)
66
+ problems.push(`子 ${c.id} は ${c.status} ですが完了していないタスクがあります(${copen.map((t) => `${t.id}(${t.status})`).join(", ")})`);
67
+ walk(c.id);
68
+ }
69
+ };
70
+ walk(rid);
71
+ if (problems.length)
72
+ return result(`配下の要望が終わっていません: ${problems.join(" / ")}(子の作業を終えて子を対応済にするか、不要な子は見送りにしてから、もう一度)`);
73
+ return result();
74
+ }
75
+ /** 要望とその子孫を読み直す(判定の直前。外での変更を取り込む) */
76
+ async function refresh(ws, rid) {
77
+ await ws.requests.load();
78
+ const h = hierarchyNow(ws);
79
+ await Promise.all([rid, ...h.descendants(rid).map((r) => r.id)].map((id) => ws.tasksOf(id).load()));
80
+ return h;
81
+ }
82
+ /** 対応済にできるか(ディスクから読み直して判定する) */
83
+ export async function completionCheck(ws, rid) {
84
+ return completionCheckOf(ws, await refresh(ws, rid), rid);
85
+ }
86
+ /** 対応済にできないなら理由(できるなら undefined)。判定の直前にディスクから読み直す */
87
+ export async function resolveBlocker(ws, rid) {
88
+ return (await completionCheck(ws, rid)).blocker;
89
+ }
90
+ /** ステータスを対応済(子のある要望は完了済も)に変えるなら規則を確かめる(満たさなければ何も書かずに失敗する) */
91
+ export async function checkStatusChange(ws, rid, next) {
92
+ if (next !== "resolved" && next !== "done")
93
+ return;
94
+ if (next === "done") {
95
+ await ws.requests.load();
96
+ if (!hierarchyNow(ws).children(rid).length)
97
+ return;
98
+ }
99
+ const why = await resolveBlocker(ws, rid);
100
+ if (why)
101
+ throw new StatusRuleError(`${rid} を${next === "done" ? "完了済" : "対応済"}にできません: ${why}`);
102
+ }
103
+ /** 対応済・完了済なのに未完了のタスク・配下がある(外部の直接編集など)。画面と CLI で知らせる */
104
+ export function resolvedIssue(ws, r) {
105
+ if (!finished(r.status))
106
+ return undefined;
107
+ const label = r.status === "resolved" ? "対応済" : "完了済";
108
+ const open = ws.tasksOf(r.id).list().filter((t) => t.status !== "done");
109
+ if (open.length && r.status === "resolved")
110
+ return `対応済ですが、完了していないタスクがあります: ${open.map((t) => t.id).join(", ")}(進行中に戻すには status=active)`;
111
+ const h = hierarchyNow(ws);
112
+ if (!h.children(r.id).length)
113
+ return undefined;
114
+ const { blocker } = completionCheckOf(ws, h, r.id);
115
+ return blocker ? `${label}ですが、${blocker}(進行中に戻すには status=active)` : undefined;
116
+ }
117
+ /**
118
+ * タスクを変えた後に呼ぶ: 対応済の要望に未完了のタスクがあれば進行中に戻す。戻したら true。
119
+ * タスクの変更は済んでいるので、要望の更新に失敗したら、そう分かるエラーにする(再試行は request set status=active)。
120
+ */
121
+ export async function reopenIfNeeded(ws, rid, actor) {
122
+ const r = ws.requests.get(rid);
123
+ if (!r || r.status !== "resolved")
124
+ return false;
125
+ if (!ws.tasksOf(rid).list().some((t) => t.status !== "done"))
126
+ return false;
127
+ try {
128
+ await ws.requests.update(rid, { status: "active" }, { actor });
129
+ return true;
130
+ }
131
+ catch (e) {
132
+ throw new Error(`タスクは更新しましたが、要望 ${rid} を進行中に戻せませんでした: ${e.message}(p3 request set ${rid} status=active で直してください)`);
133
+ }
134
+ }
135
+ /**
136
+ * 要望(rid)を変えた後に呼ぶ: rid が未完了(対応済・完了済でない、または自分のタスクに未完了がある)なら、対応済の祖先を
137
+ * 近い順に進行中に戻し、完了済の祖先は警告にする。見送りの祖先より上は、rid を対象外にしているので辿らない。
138
+ * 途中で失敗したら、戻したものと失敗したものと直し方が分かるエラーにする(戻したものは戻さない)
139
+ */
140
+ export async function reopenAncestors(ws, rid, actor) {
141
+ const out = { reopened: [], warnings: [] };
142
+ const r = ws.requests.get(rid);
143
+ if (!r || r.status === "rejected")
144
+ return out;
145
+ const open = !finished(r.status) || ws.tasksOf(rid).list().some((t) => t.status !== "done");
146
+ if (!open)
147
+ return out;
148
+ for (const a of hierarchyNow(ws).ancestors(rid).reverse()) {
149
+ if (a.status === "rejected")
150
+ break;
151
+ if (a.status === "done") {
152
+ out.warnings.push({
153
+ code: "ancestor_done",
154
+ target: a.id,
155
+ from: rid,
156
+ message: `祖先の ${a.id} は完了済ですが、配下の ${rid} が未完了になりました(再開するなら p3 request set ${a.id} status=active)`,
157
+ });
158
+ }
159
+ else if (a.status === "resolved") {
160
+ try {
161
+ await ws.requests.update(a.id, { status: "active" }, { actor });
162
+ out.reopened.push(a.id);
163
+ }
164
+ catch (e) {
165
+ const done = out.reopened.length ? `${out.reopened.join(", ")} は進行中に戻しましたが、` : "";
166
+ throw new Error(`${done}祖先の ${a.id} を進行中に戻せませんでした: ${e.message}(p3 request set ${a.id} status=active で直してください)`);
167
+ }
168
+ }
169
+ }
170
+ return out;
171
+ }
@@ -0,0 +1,242 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { ATTACHMENT_FILE_LIMITS } from "../../shared/types.js";
5
+ import { imageInfo, UI_LIMITS } from "../preflight/uiMaterials.js";
6
+ import { nowIso, writeFileAtomic } from "./fsutil.js";
7
+ export const ATTACHMENT_ID = /^A-\d{8}-\d{6}-[0-9a-f]{4}$/;
8
+ /** 上限(1つの要望あたり) */
9
+ export const ATTACHMENT_LIMITS = {
10
+ ...ATTACHMENT_FILE_LIMITS,
11
+ /** xlsx(ZIP)の項目数と、展開したときの合計(中身は読まない。一覧だけで断る) */
12
+ zipEntries: 10_000,
13
+ zipUncompressed: 200 * 1024 * 1024,
14
+ };
15
+ export class AttachmentError extends Error {
16
+ }
17
+ const EXT = { png: "png", jpeg: "jpg", xlsx: "xlsx" };
18
+ export const ATTACHMENT_TYPES = {
19
+ png: "image/png",
20
+ jpeg: "image/jpeg",
21
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
22
+ };
23
+ /**
24
+ * ZIP の一覧(中央ディレクトリ)だけを読む。展開はしない(中身の読み取りは xlsx の展開で、別に上限をかけて行う)。
25
+ * 読めなければ undefined
26
+ */
27
+ export function zipEntries(buf) {
28
+ const min = Math.max(0, buf.length - 65_557);
29
+ let eocd = -1;
30
+ for (let i = buf.length - 22; i >= min; i--) {
31
+ if (buf.readUInt32LE(i) === 0x06054b50) {
32
+ eocd = i;
33
+ break;
34
+ }
35
+ }
36
+ if (eocd < 0)
37
+ return undefined;
38
+ const count = buf.readUInt16LE(eocd + 10);
39
+ let at = buf.readUInt32LE(eocd + 16);
40
+ const entries = [];
41
+ for (let i = 0; i < count; i++) {
42
+ if (at + 46 > buf.length || buf.readUInt32LE(at) !== 0x02014b50)
43
+ return undefined;
44
+ const nameLen = buf.readUInt16LE(at + 28);
45
+ const extra = buf.readUInt16LE(at + 30);
46
+ const comment = buf.readUInt16LE(at + 32);
47
+ entries.push({ name: buf.toString("utf8", at + 46, at + 46 + nameLen), uncompressed: buf.readUInt32LE(at + 24) });
48
+ at += 46 + nameLen + extra + comment;
49
+ }
50
+ return entries;
51
+ }
52
+ /** 中身から形式を決めて確かめる。拡張子とも合わせる。だめなら AttachmentError */
53
+ export function inspectAttachment(data, name) {
54
+ const ext = name.toLowerCase().split(".").pop() ?? "";
55
+ const want = ext === "png" ? "png" : ext === "jpg" || ext === "jpeg" ? "jpeg" : ext === "xlsx" ? "xlsx" : undefined;
56
+ if (!want)
57
+ throw new AttachmentError(`添付できるのは PNG / JPEG / xlsx です(${name})。xls や xlsm は xlsx で保存し直すか、画像にしてください`);
58
+ if (want === "xlsx") {
59
+ if (data.length > ATTACHMENT_LIMITS.xlsxBytes)
60
+ throw new AttachmentError(`xlsx が大きすぎます(上限 ${ATTACHMENT_LIMITS.xlsxBytes} バイト)`);
61
+ if (data.readUInt32LE(0) !== 0x04034b50)
62
+ throw new AttachmentError(`${name}: xlsx(ZIP)として読めません`);
63
+ const entries = zipEntries(data);
64
+ if (!entries)
65
+ throw new AttachmentError(`${name}: xlsx(ZIP)の一覧が読めません`);
66
+ if (entries.length > ATTACHMENT_LIMITS.zipEntries)
67
+ throw new AttachmentError(`${name}: 中のファイルが多すぎます(${entries.length})`);
68
+ const total = entries.reduce((n, e) => n + e.uncompressed, 0);
69
+ if (total > ATTACHMENT_LIMITS.zipUncompressed)
70
+ throw new AttachmentError(`${name}: 展開すると大きすぎます(${total} バイト)`);
71
+ if (entries.some((e) => e.name.startsWith("/") || e.name.includes("\\") || e.name.split("/").includes("..")))
72
+ throw new AttachmentError(`${name}: 中に外を指すパスがあります`);
73
+ const names = new Set(entries.map((e) => e.name));
74
+ if (!names.has("[Content_Types].xml") || !names.has("xl/workbook.xml"))
75
+ throw new AttachmentError(`${name}: xlsx のブックではありません`);
76
+ if ([...names].some((n) => /vbaProject\.bin$/i.test(n)))
77
+ throw new AttachmentError(`${name}: マクロを含むブックは扱いません(マクロを外した xlsx にしてください)`);
78
+ return { format: "xlsx" };
79
+ }
80
+ if (data.length > ATTACHMENT_LIMITS.imageBytes)
81
+ throw new AttachmentError(`画像が大きすぎます(上限 ${ATTACHMENT_LIMITS.imageBytes} バイト)`);
82
+ const info = imageInfo(data);
83
+ if (!info)
84
+ throw new AttachmentError(`${name}: PNG / JPEG として読めません`);
85
+ if (info.format !== want)
86
+ throw new AttachmentError(`${name}: 拡張子と中身の形式が合いません(中身は ${info.format})`);
87
+ if (info.width > UI_LIMITS.width || info.height > UI_LIMITS.height || info.width * info.height > UI_LIMITS.pixels) {
88
+ throw new AttachmentError(`${name}: 画像の大きさが上限を超えています(${info.width}x${info.height})`);
89
+ }
90
+ return info;
91
+ }
92
+ /** ダウンロードの名前(制御文字・パスの区切りを外す) */
93
+ export function safeFileName(name, format) {
94
+ // oxlint-disable-next-line no-control-regex -- 制御文字を外すのが目的
95
+ const base = name.replace(/[\u0000-\u001f\u007f/\\:*?"<>|]/g, "_").replace(/^\.+/, "").trim().slice(0, 120);
96
+ const ext = `.${EXT[format]}`;
97
+ const withExt = /\.(png|jpe?g|xlsx)$/i.test(base) ? base : `${base || "attachment"}${ext}`;
98
+ return withExt || `attachment${ext}`;
99
+ }
100
+ /**
101
+ * requests/<要望ID>/attachments/<ID>/
102
+ * meta.json 元の名前・説明・出典・形式・大きさ・sha256・追加した人と日時
103
+ * file.<拡張子> 原本(内部の名前)
104
+ *
105
+ * 1件1フォルダなので、複数人が同時に足しても衝突しない。書きかけ(.tmp-)と消しかけ(.del-)は一覧に出さない。
106
+ */
107
+ export class AttachmentStore {
108
+ requestsDir;
109
+ constructor(requestsDir) {
110
+ this.requestsDir = requestsDir;
111
+ }
112
+ dir(requestId) {
113
+ return join(this.requestsDir, requestId, "attachments");
114
+ }
115
+ fileOf(requestId, a) {
116
+ return join(this.dir(requestId), a.id, `file.${EXT[a.format]}`);
117
+ }
118
+ async add(requestId, input, actor) {
119
+ const name = input.name.trim().split(/[\\/]/).pop() ?? "";
120
+ if (!name)
121
+ throw new AttachmentError("ファイル名がありません");
122
+ const info = inspectAttachment(input.data, name);
123
+ const { items } = await this.list(requestId);
124
+ if (items.length >= ATTACHMENT_LIMITS.count)
125
+ throw new AttachmentError(`添付は1つの要望に ${ATTACHMENT_LIMITS.count} 件までです`);
126
+ const total = items.reduce((n, a) => n + a.bytes, 0) + input.data.length;
127
+ if (total > ATTACHMENT_LIMITS.totalBytes)
128
+ throw new AttachmentError(`添付の合計が上限(${ATTACHMENT_LIMITS.totalBytes} バイト)を超えます`);
129
+ const createdAt = nowIso();
130
+ const id = `A-${createdAt.replace(/[-:]/g, "").replace("T", "-").slice(0, 15)}-${randomBytes(2).toString("hex")}`;
131
+ const text = (v) => (v?.trim() ? v.trim() : undefined);
132
+ const a = {
133
+ id,
134
+ requestId,
135
+ name,
136
+ format: info.format,
137
+ bytes: input.data.length,
138
+ sha256: createHash("sha256").update(input.data).digest("hex"),
139
+ ...(text(input.description) ? { description: text(input.description) } : {}),
140
+ ...(text(input.source) ? { source: text(input.source) } : {}),
141
+ ...(info.width ? { width: info.width, height: info.height } : {}),
142
+ createdAt,
143
+ ...(actor ? { createdBy: actor } : {}),
144
+ };
145
+ // 書きかけのフォルダに全部書いてから名前を変える(途中で止まっても一覧に半端なものが出ない)
146
+ const tmp = join(this.dir(requestId), `.tmp-${id}`);
147
+ await mkdir(tmp, { recursive: true });
148
+ try {
149
+ await writeFile(join(tmp, `file.${EXT[a.format]}`), input.data);
150
+ await writeFile(join(tmp, "meta.json"), JSON.stringify(withoutRequest(a), null, 2) + "\n");
151
+ await rename(tmp, join(this.dir(requestId), id));
152
+ }
153
+ catch (e) {
154
+ await rm(tmp, { recursive: true, force: true });
155
+ throw e;
156
+ }
157
+ return a;
158
+ }
159
+ /** 古い順。読めないものは invalid に理由(黙って捨てない) */
160
+ async list(requestId) {
161
+ const names = await readdir(this.dir(requestId)).catch(() => []);
162
+ const items = [];
163
+ const invalid = [];
164
+ for (const id of names.filter((n) => !n.startsWith("."))) {
165
+ try {
166
+ items.push(await this.read(requestId, id));
167
+ }
168
+ catch (e) {
169
+ invalid.push({ id, error: e.message });
170
+ }
171
+ }
172
+ items.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
173
+ return { items, invalid };
174
+ }
175
+ async read(requestId, id) {
176
+ if (!ATTACHMENT_ID.test(id))
177
+ throw new AttachmentError("名前が A-YYYYMMDD-HHMMSS-xxxx ではありません");
178
+ const dir = join(this.dir(requestId), id);
179
+ const st = await lstat(dir);
180
+ if (!st.isDirectory())
181
+ throw new AttachmentError("フォルダではありません");
182
+ const meta = JSON.parse(await readFile(join(dir, "meta.json"), "utf8"));
183
+ if (meta.id !== id || !(meta.format in EXT) || typeof meta.name !== "string")
184
+ throw new AttachmentError("meta.json が読めません");
185
+ return { ...meta, requestId };
186
+ }
187
+ async get(requestId, id) {
188
+ if (!ATTACHMENT_ID.test(id))
189
+ return undefined;
190
+ return this.read(requestId, id).catch(() => undefined);
191
+ }
192
+ /** 原本を読む。保存したときの形式・大きさ・sha256 と合うかを確かめる(差し替えやシンボリックリンクは断る) */
193
+ async content(requestId, id) {
194
+ const meta = await this.get(requestId, id);
195
+ if (!meta)
196
+ throw new AttachmentError(`添付 ${id} がありません`);
197
+ const file = this.fileOf(requestId, meta);
198
+ const st = await lstat(file).catch(() => undefined);
199
+ if (!st?.isFile())
200
+ throw new AttachmentError(`添付 ${id} の原本がありません`);
201
+ const data = await readFile(file);
202
+ if (data.length !== meta.bytes || createHash("sha256").update(data).digest("hex") !== meta.sha256) {
203
+ throw new AttachmentError(`添付 ${id} の原本が保存したときと変わっています`);
204
+ }
205
+ return { meta, data };
206
+ }
207
+ async remove(requestId, id) {
208
+ if (!(await this.get(requestId, id)))
209
+ throw new AttachmentError(`添付 ${id} がありません`);
210
+ // 先に名前を変えて一覧から外してから消す(消しかけを開始時のコピーが読まない)
211
+ const del = join(this.dir(requestId), `.del-${id}-${randomBytes(2).toString("hex")}`);
212
+ await rename(join(this.dir(requestId), id), del);
213
+ await rm(del, { recursive: true, force: true });
214
+ }
215
+ /**
216
+ * Preflight を始めるときに、今の添付を run の中へコピーして固定する。画像は <runDir>/ui/current/、xlsx は
217
+ * <runDir>/attachments/ に置き、一覧を <runDir>/attachments.json に書く。コピーの途中で消された・変わったものがあれば
218
+ * AttachmentError(その Preflight は始めない。原本は残る)
219
+ */
220
+ async snapshot(requestId, runDir) {
221
+ const { items } = await this.list(requestId);
222
+ const fixed = [];
223
+ for (const a of items) {
224
+ let data;
225
+ try {
226
+ ({ data } = await this.content(requestId, a.id));
227
+ }
228
+ catch (e) {
229
+ throw new AttachmentError(`添付を固定できません(始める間に添付が変わりました。もう一度始めてください): ${e.message}`);
230
+ }
231
+ const path = a.format === "xlsx" ? `attachments/${a.id}.xlsx` : `ui/current/${a.id}.${EXT[a.format]}`;
232
+ await mkdir(join(runDir, path, ".."), { recursive: true });
233
+ await writeFile(join(runDir, path), data);
234
+ const { requestId: _, ...rest } = a;
235
+ fixed.push({ ...rest, path });
236
+ }
237
+ if (fixed.length)
238
+ await writeFileAtomic(join(runDir, "attachments.json"), JSON.stringify(fixed, null, 2) + "\n");
239
+ return fixed;
240
+ }
241
+ }
242
+ const withoutRequest = ({ requestId: _, ...a }) => a;
@@ -0,0 +1,254 @@
1
+ import { access, mkdir, readFile, readdir, rename } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { parseFrontmatter, stringifyFrontmatter } from "./frontmatter.js";
4
+ import { createExclusive, nowIso, writeFileAtomic } from "./fsutil.js";
5
+ export class ConflictError extends Error {
6
+ id;
7
+ expected;
8
+ actual;
9
+ constructor(id, expected, actual) {
10
+ super(`${id}: rev conflict (expected ${expected}, actual ${actual})`);
11
+ this.id = id;
12
+ this.expected = expected;
13
+ this.actual = actual;
14
+ }
15
+ }
16
+ export class NotFoundError extends Error {
17
+ id;
18
+ constructor(id) {
19
+ super(`${id} not found`);
20
+ this.id = id;
21
+ }
22
+ }
23
+ /**
24
+ * 1エンティティ = 1 Markdown ファイル(YAML frontmatter + 本文)のコレクション。
25
+ * メモリ上にキャッシュし、ファイル変更(人手・AI・Codex・git pull)は reload() で取り込む。
26
+ *
27
+ * 全件の読み込み(load / prepareLoad)は、読み終えてから入れ替える(読んでいる途中の空や半分の状態を見せない)。
28
+ * 読み込みの間に作成・更新・アーカイブ・1件の読み直しがあった ID は、読んだ結果ではなくその時点の状態を残す
29
+ * (読み込みが先に読んだ古い内容で、後の書き込みを戻さない)。
30
+ */
31
+ export class MarkdownCollection {
32
+ opts;
33
+ items = new Map();
34
+ /** 読めないファイル。壊れたファイルで全体が落ちないようにする */
35
+ errors = new Map();
36
+ layout;
37
+ /** 進行中の全件の読み込みごとの「その間に変わった ID」 */
38
+ loads = new Set();
39
+ constructor(opts) {
40
+ this.opts = opts;
41
+ this.layout = opts.layout;
42
+ }
43
+ async load() {
44
+ (await this.prepareLoad()).commit();
45
+ }
46
+ /** ディスクから全件を読む。公開は commit でまとめて(同期で)行う */
47
+ async prepareLoad() {
48
+ const touched = new Set();
49
+ this.loads.add(touched);
50
+ const items = new Map();
51
+ const errors = new Map();
52
+ try {
53
+ for (const id of await this.layout.scan()) {
54
+ const r = await this.read(id);
55
+ if ("item" in r)
56
+ items.set(id, r.item);
57
+ else if ("error" in r)
58
+ errors.set(id, r.error);
59
+ }
60
+ }
61
+ catch (e) {
62
+ this.loads.delete(touched);
63
+ throw e;
64
+ }
65
+ return {
66
+ ids: [...items.keys()],
67
+ commit: () => {
68
+ if (!this.loads.delete(touched))
69
+ return;
70
+ for (const id of touched) {
71
+ const live = this.items.get(id);
72
+ if (live)
73
+ items.set(id, live);
74
+ else
75
+ items.delete(id);
76
+ const err = this.errors.get(id);
77
+ if (err !== undefined)
78
+ errors.set(id, err);
79
+ else
80
+ errors.delete(id);
81
+ }
82
+ this.items = items;
83
+ this.errors.clear();
84
+ for (const [id, e] of errors)
85
+ this.errors.set(id, e);
86
+ },
87
+ abort: () => void this.loads.delete(touched),
88
+ };
89
+ }
90
+ /**
91
+ * 1件をディスクから読むだけ(読み込んだ内容・索引・変更通知には触れない)。監視に頼らずに今のファイルを確かめるため。
92
+ * 無ければ { missing }、読めなければ { error }
93
+ */
94
+ peek(id) {
95
+ return this.read(id);
96
+ }
97
+ async read(id) {
98
+ try {
99
+ const { data, body } = parseFrontmatter(await readFile(this.layout.path(id), "utf8"));
100
+ return { item: this.opts.normalize(data, body, id) };
101
+ }
102
+ catch (e) {
103
+ return e.code === "ENOENT" ? { missing: true } : { error: String(e) };
104
+ }
105
+ }
106
+ touch(id) {
107
+ for (const t of this.loads)
108
+ t.add(id);
109
+ }
110
+ put(id, item) {
111
+ this.items.set(id, item);
112
+ this.touch(id);
113
+ }
114
+ /** 1件を読み直す。消えていれば除く */
115
+ async reload(id) {
116
+ const r = await this.read(id);
117
+ if ("item" in r) {
118
+ this.put(id, r.item);
119
+ this.errors.delete(id);
120
+ }
121
+ else {
122
+ this.items.delete(id);
123
+ if ("error" in r)
124
+ this.errors.set(id, r.error);
125
+ else
126
+ this.errors.delete(id);
127
+ this.touch(id);
128
+ }
129
+ }
130
+ list() {
131
+ return [...this.items.values()].sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true }));
132
+ }
133
+ get(id) {
134
+ return this.items.get(id);
135
+ }
136
+ require(id) {
137
+ const v = this.items.get(id);
138
+ if (!v)
139
+ throw new NotFoundError(id);
140
+ return v;
141
+ }
142
+ path(id) {
143
+ return this.layout.path(id);
144
+ }
145
+ serialize(item) {
146
+ const { body, ...rest } = item;
147
+ const skip = new Set(["body", ...(this.opts.derived ?? [])]);
148
+ const ordered = {};
149
+ for (const k of this.opts.keyOrder)
150
+ if (!skip.has(k))
151
+ ordered[k] = rest[k];
152
+ for (const [k, v] of Object.entries(rest))
153
+ if (!(k in ordered) && !skip.has(k))
154
+ ordered[k] = v;
155
+ return stringifyFrontmatter(ordered, body);
156
+ }
157
+ /** 作る。省いた項目は normalize の既定値になる */
158
+ async create(input, actor) {
159
+ // アーカイブ済みの ID も使わない(アーカイブしたタスクへの関係が新しいタスクを指さないように)
160
+ const existing = [...new Set([...this.items.keys(), ...(await this.layout.scan()), ...((await this.layout.reserved?.()) ?? [])])];
161
+ // 別のプロセス(CLI・AI)と同時に作っても、排他作成で衝突を検出して次の ID にする
162
+ for (let attempt = 0;; attempt++) {
163
+ const id = this.layout.nextId(existing, attempt);
164
+ const now = nowIso();
165
+ const item = this.opts.normalize({}, "", id);
166
+ Object.assign(item, input, { id, rev: 1, createdAt: now, updatedAt: now, updatedBy: actor });
167
+ const final = this.opts.beforeWrite?.(undefined, item) ?? item;
168
+ Object.assign(item, final);
169
+ if (await createExclusive(this.layout.path(id), this.serialize(item))) {
170
+ this.put(id, item);
171
+ return item;
172
+ }
173
+ existing.push(id);
174
+ }
175
+ }
176
+ /**
177
+ * 決めた ID で作る(予約した ID で作り直せるように)。既にファイルがあれば書かずに undefined(排他作成)
178
+ */
179
+ async createAt(id, input, actor) {
180
+ const now = nowIso();
181
+ const item = this.opts.normalize({}, "", id);
182
+ Object.assign(item, input, { id, rev: 1, createdAt: now, updatedAt: now, updatedBy: actor });
183
+ Object.assign(item, this.opts.beforeWrite?.(undefined, item) ?? item);
184
+ if (!(await createExclusive(this.layout.path(id), this.serialize(item))))
185
+ return undefined;
186
+ this.put(id, item);
187
+ return item;
188
+ }
189
+ /**
190
+ * 部分更新。expectedRev を渡すと楽観ロック(AI が古い状態を元に上書きするのを防ぐ)。
191
+ */
192
+ async update(id, patch, opts = {}) {
193
+ // 外部での編集を取りこぼさないよう、更新の直前にディスクから読み直す
194
+ await this.reload(id);
195
+ const cur = this.require(id);
196
+ if (opts.expectedRev !== undefined && opts.expectedRev !== cur.rev) {
197
+ throw new ConflictError(id, opts.expectedRev, cur.rev);
198
+ }
199
+ const merged = {
200
+ ...cur,
201
+ ...patch,
202
+ id,
203
+ rev: cur.rev + 1,
204
+ createdAt: cur.createdAt,
205
+ updatedAt: nowIso(),
206
+ updatedBy: opts.actor ?? cur.updatedBy,
207
+ };
208
+ const next = this.opts.beforeWrite?.(cur, merged) ?? merged;
209
+ await writeFileAtomic(this.layout.path(id), this.serialize(next));
210
+ this.put(id, next);
211
+ return next;
212
+ }
213
+ /** 物理削除はせず .archive/ へ移す */
214
+ async archive(id) {
215
+ this.require(id);
216
+ const { from, to } = this.layout.archive(id);
217
+ // 既にアーカイブに同じ ID があれば上書きしない(rename は黙って置き換えるので先に確かめる)
218
+ if (await access(to).then(() => true, () => false))
219
+ throw new Error(`${id} は既にアーカイブにあります(${to})。上書きしません`);
220
+ await mkdir(dirname(to), { recursive: true });
221
+ await rename(from, to);
222
+ this.items.delete(id);
223
+ this.touch(id);
224
+ }
225
+ }
226
+ /** ディレクトリの中の "<ID>.md"(タスク)。ID は要望の中の連番 */
227
+ export function fileLayout(dir, idPattern, format) {
228
+ /** ディレクトリの中の有効な名前の ID(中身は読まないので、壊れたファイルでも ID は予約される) */
229
+ const ids = async (d) => (await readdir(d).catch(() => []))
230
+ .filter((f) => f.endsWith(".md"))
231
+ .map((f) => f.slice(0, -3))
232
+ .filter((id) => idPattern.test(id));
233
+ return {
234
+ path: (id) => join(dir, `${id}.md`),
235
+ scan: () => ids(dir),
236
+ reserved: () => ids(join(dir, ".archive")),
237
+ nextId: (existing, attempt) => {
238
+ const nums = existing.map((id) => Number(/\d+/.exec(id)?.[0] ?? 0));
239
+ return format((nums.length ? Math.max(...nums) : 0) + 1 + attempt);
240
+ },
241
+ archive: (id) => ({ from: join(dir, `${id}.md`), to: join(dir, ".archive", `${id}.md`) }),
242
+ };
243
+ }
244
+ /** "<ID>/<file>"(要望)。フォルダごと1件で、ID は新しく作る */
245
+ export function folderLayout(dir, file, idPattern, newId) {
246
+ return {
247
+ path: (id) => join(dir, id, file),
248
+ scan: async () => (await readdir(dir, { withFileTypes: true }).catch(() => []))
249
+ .filter((d) => d.isDirectory() && idPattern.test(d.name))
250
+ .map((d) => d.name),
251
+ nextId: () => newId(),
252
+ archive: (id) => ({ from: join(dir, id), to: join(dir, ".archive", id) }),
253
+ };
254
+ }