@infodb/p3 0.0.0-stage → 0.2.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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -2
  3. package/bin/p3.mjs +18 -0
  4. package/dist/web/apple-touch-icon.png +0 -0
  5. package/dist/web/assets/Outputs-Ni3pNuGU.js +1 -0
  6. package/dist/web/assets/RequestStatus-K8TZwpur.js +1 -0
  7. package/dist/web/assets/TagInput-BICKVH2x.js +1 -0
  8. package/dist/web/assets/TaskDrawer-BkDIstIN.js +3 -0
  9. package/dist/web/assets/_requestId-B5O_ytaq.js +1 -0
  10. package/dist/web/assets/_requestId-C66puEMO.js +30 -0
  11. package/dist/web/assets/action-CMjATXqv.js +1 -0
  12. package/dist/web/assets/board-CbfDjkls.js +1 -0
  13. package/dist/web/assets/copy-B1ZbihKL.js +2 -0
  14. package/dist/web/assets/done-CPQbCFHg.js +1 -0
  15. package/dist/web/assets/draft-dT3gLDIt.js +1 -0
  16. package/dist/web/assets/format-DuK6P1hb.js +1 -0
  17. package/dist/web/assets/index-BUcs2J6N.js +12 -0
  18. package/dist/web/assets/index-C3DkqwJ9.css +2 -0
  19. package/dist/web/assets/link-_s8ndNKS.js +1 -0
  20. package/dist/web/assets/new-T60RB7de.js +1 -0
  21. package/dist/web/assets/preload-helper-dXqN7N-I.js +1 -0
  22. package/dist/web/assets/release-notes-DxrPhDbt.js +3 -0
  23. package/dist/web/assets/requestData-D8ZiSZss.js +1 -0
  24. package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
  25. package/dist/web/assets/routes-D9ZxXoLk.js +2 -0
  26. package/dist/web/assets/search-CJ8MBKTz.js +1 -0
  27. package/dist/web/assets/settings-DsHVyqzJ.js +1 -0
  28. package/dist/web/assets/supersede-CLXlhCq0.js +1 -0
  29. package/dist/web/assets/ui-Cvke4y4X.js +1 -0
  30. package/dist/web/favicon.ico +0 -0
  31. package/dist/web/favicon.svg +12 -0
  32. package/dist/web/index.html +23 -0
  33. package/docs/architecture.md +591 -0
  34. package/docs/chatgpt-sign-in.md +163 -0
  35. package/docs/development.md +194 -0
  36. package/docs/how-to-use.md +524 -0
  37. package/docs/installation.md +284 -0
  38. package/docs/publishing.md +65 -0
  39. package/package.json +86 -3
  40. package/skills/p3/SKILL.md +95 -0
  41. package/src/cli/args.ts +179 -0
  42. package/src/cli/chatgpt.ts +74 -0
  43. package/src/cli/codex.ts +28 -0
  44. package/src/cli/format.ts +9 -0
  45. package/src/cli/help.ts +99 -0
  46. package/src/cli/main.ts +267 -0
  47. package/src/cli/output.ts +99 -0
  48. package/src/cli/preflightCommands.ts +237 -0
  49. package/src/cli/project.ts +508 -0
  50. package/src/cli/readOnly.ts +36 -0
  51. package/src/cli/releaseNotesCommands.ts +139 -0
  52. package/src/cli/render.ts +60 -0
  53. package/src/cli/requestCommands.ts +170 -0
  54. package/src/cli/showView.ts +110 -0
  55. package/src/cli/taskCommands.ts +167 -0
  56. package/src/cli/userConfig.ts +58 -0
  57. package/src/core/chatgpt.ts +33 -0
  58. package/src/core/context.ts +57 -0
  59. package/src/core/machineSettings.ts +207 -0
  60. package/src/core/machineSettingsEdit.ts +156 -0
  61. package/src/core/ops.ts +114 -0
  62. package/src/core/preflight/carryover.ts +133 -0
  63. package/src/core/preflight/codexEngine.ts +702 -0
  64. package/src/core/preflight/codexImage.ts +98 -0
  65. package/src/core/preflight/diagnose.ts +124 -0
  66. package/src/core/preflight/engine.ts +92 -0
  67. package/src/core/preflight/input.ts +65 -0
  68. package/src/core/preflight/launch.ts +86 -0
  69. package/src/core/preflight/launcher.mjs +75 -0
  70. package/src/core/preflight/mock-ui.html +24 -0
  71. package/src/core/preflight/mock-ui.png +0 -0
  72. package/src/core/preflight/mockEngine.ts +145 -0
  73. package/src/core/preflight/render-image/Dockerfile +23 -0
  74. package/src/core/preflight/render-image/render.mjs +53 -0
  75. package/src/core/preflight/render.ts +336 -0
  76. package/src/core/preflight/service.ts +690 -0
  77. package/src/core/preflight/uiMaterials.ts +272 -0
  78. package/src/core/preflight/uiRender.ts +84 -0
  79. package/src/core/preflight/wireframe.ts +69 -0
  80. package/src/core/preflight/xlsx.ts +328 -0
  81. package/src/core/redact.ts +31 -0
  82. package/src/core/releaseNotes/generate.ts +271 -0
  83. package/src/core/releaseNotes/material.ts +114 -0
  84. package/src/core/releaseNotes/mockSummarizer.ts +28 -0
  85. package/src/core/releaseNotes/service.ts +106 -0
  86. package/src/core/releaseNotes/store.ts +216 -0
  87. package/src/core/repoAdmin.ts +81 -0
  88. package/src/core/repoRefs.ts +90 -0
  89. package/src/core/requestOps.ts +140 -0
  90. package/src/core/requestStatus.ts +58 -0
  91. package/src/core/store/attachments.ts +228 -0
  92. package/src/core/store/collection.ts +282 -0
  93. package/src/core/store/frontmatter.ts +22 -0
  94. package/src/core/store/fsutil.ts +90 -0
  95. package/src/core/store/locate.ts +181 -0
  96. package/src/core/store/normalize.ts +155 -0
  97. package/src/core/store/noteStore.ts +56 -0
  98. package/src/core/store/preflightStore.ts +136 -0
  99. package/src/core/store/projectFile.ts +101 -0
  100. package/src/core/store/workspace.ts +328 -0
  101. package/src/core/supersede.ts +74 -0
  102. package/src/core/userConfig.ts +180 -0
  103. package/src/core/userTheme.ts +22 -0
  104. package/src/core/workTargets.ts +120 -0
  105. package/src/server/api/chatgptRoutes.ts +48 -0
  106. package/src/server/api/local.ts +33 -0
  107. package/src/server/api/manifest.ts +119 -0
  108. package/src/server/api/releaseNoteRoutes.ts +78 -0
  109. package/src/server/api/repoRoutes.ts +67 -0
  110. package/src/server/api/routes.ts +374 -0
  111. package/src/server/api/userThemeRoutes.ts +62 -0
  112. package/src/server/server.ts +49 -0
  113. package/src/shared/dates.ts +12 -0
  114. package/src/shared/preflightInput.ts +27 -0
  115. package/src/shared/refs.ts +55 -0
  116. package/src/shared/repos.ts +113 -0
  117. package/src/shared/scopeView.ts +48 -0
  118. package/src/shared/tags.ts +27 -0
  119. package/src/shared/types.ts +700 -0
  120. package/src/shared/workTarget.ts +44 -0
@@ -0,0 +1,140 @@
1
+ import type { Request, Task } from "../shared/types.ts";
2
+ import { defaultRepo } from "../shared/workTarget.ts";
3
+ import type { P3Context } from "./context.ts";
4
+ import { checkStatusChange, reopenIfNeeded } from "./requestStatus.ts";
5
+ import { startWarnings, type Warning } from "./supersede.ts";
6
+ import { checkRepoTarget, ensureWorkstreams } from "./workTargets.ts";
7
+
8
+ /**
9
+ * 要望とタスクの変更の手順。CLI と API はここを呼び、引数の解釈と出力だけを持つ。
10
+ * 規則(作業先・対応済・置き換えの警告・ブランチの割り当て・進行中に戻す・変更通知)を足すときは、ここだけを直す。
11
+ * タスクの関係(depends_on・supersedes)は Preflight のタスク化だけが張る(手で張る操作は持たない)
12
+ *
13
+ * 手順はどれも「確かめる(何も書かない)→ 保存 → 後始末(ブランチの割り当て・進行中に戻す)→ 変更通知」の順。
14
+ */
15
+
16
+ /** 入力が規則に合わない(何も書いていない)。CLI は使い方の誤り、API は 400 */
17
+ export class OpRuleError extends Error {}
18
+
19
+ export interface WriteOpts {
20
+ /** 楽観ロック。違えば ConflictError */
21
+ expectedRev?: number;
22
+ actor?: string;
23
+ }
24
+
25
+ /** タスクを変えた結果。reopened: 対応済から進行中に戻した要望 */
26
+ export interface TaskResult {
27
+ task: Task;
28
+ warnings: Warning[];
29
+ reopened?: string;
30
+ }
31
+
32
+ function changed(ctx: P3Context, kind: "task" | "request", request: string, ref?: string) {
33
+ ctx.ws.emit({ type: "changed", kind, request, ref });
34
+ }
35
+
36
+ /** 要望のマイルストーンは project.yaml にあるものだけ */
37
+ export function checkMilestone(ctx: P3Context, id: string | null | undefined) {
38
+ if (id && !ctx.ws.project.milestones.some((m) => m.id === id)) {
39
+ throw new OpRuleError(`マイルストーンがありません: ${id}(p3 milestone add ${id} か、画面の設定で追加してください)`);
40
+ }
41
+ }
42
+
43
+ /**
44
+ * マイルストーンを外すときの規則(CLI の milestone rm と、API の設定全体の更新で同じに効かせる)。
45
+ * next: 外した後に残るマイルストーンの ID。使っている要望か、リリースノート(読めないファイルも含む)があれば断る
46
+ */
47
+ export async function checkMilestoneRemoval(ctx: P3Context, next: string[]): Promise<void> {
48
+ const keep = new Set(next);
49
+ const removed = ctx.ws.project.milestones.map((m) => m.id).filter((id) => !keep.has(id));
50
+ if (!removed.length) return;
51
+ const used = [...new Set(ctx.ws.requests.list().flatMap((r) => (r.milestone && removed.includes(r.milestone) ? [r.milestone] : [])))];
52
+ if (used.length) {
53
+ const n = (id: string) => ctx.ws.requests.list().filter((r) => r.milestone === id).length;
54
+ throw new OpRuleError(`使用中のマイルストーンは消せません: ${used.map((id) => `${id}(要望 ${n(id)} 件)`).join(", ")}。要望の milestone を外してから消してください`);
55
+ }
56
+ const notes = (await ctx.ws.releaseNotes.ids()).filter((id) => removed.includes(id));
57
+ if (notes.length) {
58
+ throw new OpRuleError(`リリースノートのあるマイルストーンは消せません: ${notes.join(", ")}(release-notes/<ID>.md を残すなら消さないでください)`);
59
+ }
60
+ }
61
+
62
+ /** タスクを変えた後: ブランチの割り当てと、対応済の要望に未完了のタスクができたら進行中に戻す */
63
+ async function afterTaskWrite(ctx: P3Context, rid: string, task: Task, repo: string | null | undefined, actor?: string): Promise<string | undefined> {
64
+ if (repo) await ensureWorkstreams(ctx.ws, rid, [repo], actor);
65
+ const reopened = (await reopenIfNeeded(ctx.ws, rid, actor)) ? rid : undefined;
66
+ changed(ctx, "task", rid, task.ref);
67
+ if (reopened) changed(ctx, "request", rid);
68
+ return reopened;
69
+ }
70
+
71
+ /**
72
+ * タスクを作る。repo: 省くと作業先にできる参照先が1つならそれ(ほかは作業先なし)、null は作業先なし。
73
+ * 作業先とリポジトリごとの成果物の参照先は、作業先にできるものだけ(書く前に断る)
74
+ */
75
+ export async function createTask(ctx: P3Context, rid: string, input: Partial<Task> & { title: string }, actor?: string): Promise<TaskResult> {
76
+ ctx.ws.requests.require(rid);
77
+ const repo = "repo" in input ? (input.repo ?? null) : defaultRepo(ctx.ws.project);
78
+ checkRepoTarget(ctx.ws, repo);
79
+ for (const o of input.repoOutputs ?? []) checkRepoTarget(ctx.ws, o.repo);
80
+ const task = await ctx.ws.tasksOf(rid).create({ ...input, repo, status: input.status ?? "todo" }, actor);
81
+ return { task, warnings: [], reopened: await afterTaskWrite(ctx, rid, task, repo, actor) };
82
+ }
83
+
84
+ /**
85
+ * タスクを変える。checked: 人の「済み」を付ける / 外す(付けられるのは完了したタスクだけ)。
86
+ * 置き換えられたタスクを作業中にすると warnings を返す(変更はする)
87
+ */
88
+ export async function updateTask(
89
+ ctx: P3Context,
90
+ rid: string,
91
+ tid: string,
92
+ patch: Partial<Task> & { checked?: boolean },
93
+ opts: WriteOpts = {},
94
+ ): Promise<TaskResult> {
95
+ const col = ctx.ws.tasksOf(rid);
96
+ const cur = col.require(tid);
97
+ const { checked, ...rest } = patch;
98
+ const next: Partial<Task> = { ...rest };
99
+ if ("repo" in patch) {
100
+ checkRepoTarget(ctx.ws, patch.repo);
101
+ next.repo = patch.repo ?? null;
102
+ }
103
+ for (const o of patch.repoOutputs ?? []) checkRepoTarget(ctx.ws, o.repo);
104
+ if (checked !== undefined) {
105
+ if (checked && (next.status ?? cur.status) !== "done") throw new OpRuleError(`${cur.ref} はまだ完了していません(済みにできるのは完了したタスクだけ)`);
106
+ next.checkedAt = checked ? new Date().toISOString() : undefined;
107
+ }
108
+ const warnings = startWarnings(ctx.ws, cur.ref, cur.status, next.status);
109
+ const task = await col.update(tid, next, opts);
110
+ return { task, warnings, reopened: await afterTaskWrite(ctx, rid, task, patch.repo, opts.actor) };
111
+ }
112
+
113
+ /** タスクをアーカイブする(.archive/ へ移す。消さない) */
114
+ export async function archiveTask(ctx: P3Context, rid: string, tid: string): Promise<void> {
115
+ await ctx.ws.tasksOf(rid).archive(tid);
116
+ changed(ctx, "task", rid, `${rid}/${tid}`);
117
+ }
118
+
119
+ /** 要望を作る(下書き) */
120
+ export async function createRequest(ctx: P3Context, input: Partial<Request> & { title: string }, actor?: string): Promise<Request> {
121
+ checkMilestone(ctx, input.milestone);
122
+ const r = await ctx.ws.requests.create({ body: "", areas: [], tags: [], ...input, status: "draft" }, actor);
123
+ changed(ctx, "request", r.id);
124
+ return r;
125
+ }
126
+
127
+ /** 要望を変える。対応済にするのは全タスクが完了のときだけ(requestStatus.ts) */
128
+ export async function updateRequest(ctx: P3Context, rid: string, patch: Partial<Request>, opts: WriteOpts = {}): Promise<Request> {
129
+ checkMilestone(ctx, patch.milestone);
130
+ await checkStatusChange(ctx.ws, rid, patch.status);
131
+ const r = await ctx.ws.requests.update(rid, patch, opts);
132
+ changed(ctx, "request", r.id);
133
+ return r;
134
+ }
135
+
136
+ /** 要望をアーカイブする(フォルダごと .archive/ へ) */
137
+ export async function archiveRequest(ctx: P3Context, rid: string): Promise<void> {
138
+ await ctx.ws.requests.archive(rid);
139
+ changed(ctx, "request", rid);
140
+ }
@@ -0,0 +1,58 @@
1
+ import type { Request, RequestStatus } from "../shared/types.ts";
2
+ import type { Workspace } from "./store/workspace.ts";
3
+
4
+ /**
5
+ * 要望の「対応済」(resolved)の規則。CLI と API のどちらから変えても同じように効くよう、ここにまとめる。
6
+ *
7
+ * - 対応済にできるのは、タスクが1件以上あり、全部が完了(status=done)で、読めないタスクファイルが無いときだけ。
8
+ * 人の「済み」(checkedAt)・PR・マージは条件にしない。置き換えられたタスクも、残っていれば数える
9
+ * - 対応済の要望に未完了のタスクができたら(足した・完了から戻した・再評価でタスク化した)進行中に戻す
10
+ * - 最後のタスクを完了にしても自動では対応済にしない(作業を終えた側が明示的に設定する)
11
+ */
12
+
13
+ export class StatusRuleError extends Error {}
14
+
15
+ /** 対応済にできないなら理由(できるなら undefined)。判定の直前にディスクから読み直す */
16
+ export async function resolveBlocker(ws: Workspace, rid: string): Promise<string | undefined> {
17
+ const col = ws.tasksOf(rid);
18
+ await col.load();
19
+ const broken = [...col.errors.keys()];
20
+ if (broken.length) return `読めないタスクファイルがあります: ${broken.join(", ")}(直してから対応済にしてください)`;
21
+ const tasks = col.list();
22
+ if (!tasks.length) return "タスクがありません(タスクの無い要望は対応済にできません)";
23
+ const open = tasks.filter((t) => t.status !== "done");
24
+ if (open.length) return `完了していないタスクがあります: ${open.map((t) => `${t.id}(${t.status})`).join(", ")}(完了させるか、不要ならアーカイブしてから対応済にしてください)`;
25
+ return undefined;
26
+ }
27
+
28
+ /** ステータスを対応済に変えるなら規則を確かめる(満たさなければ何も書かずに失敗する) */
29
+ export async function checkStatusChange(ws: Workspace, rid: string, next: RequestStatus | undefined): Promise<void> {
30
+ if (next !== "resolved") return;
31
+ const why = await resolveBlocker(ws, rid);
32
+ if (why) throw new StatusRuleError(`${rid} を対応済にできません: ${why}`);
33
+ }
34
+
35
+ /** 対応済なのに未完了のタスクがある(外部の直接編集など)。画面と CLI で知らせる */
36
+ export function resolvedIssue(ws: Workspace, r: Request): string | undefined {
37
+ if (r.status !== "resolved") return undefined;
38
+ const open = ws.tasksOf(r.id).list().filter((t) => t.status !== "done");
39
+ return open.length
40
+ ? `対応済ですが、完了していないタスクがあります: ${open.map((t) => t.id).join(", ")}(進行中に戻すには status=active)`
41
+ : undefined;
42
+ }
43
+
44
+ /**
45
+ * タスクを変えた後に呼ぶ: 対応済の要望に未完了のタスクがあれば進行中に戻す。戻したら true。
46
+ * タスクの変更は済んでいるので、要望の更新に失敗したら、そう分かるエラーにする(再試行は request set status=active)。
47
+ */
48
+ export async function reopenIfNeeded(ws: Workspace, rid: string, actor?: string): Promise<boolean> {
49
+ const r = ws.requests.get(rid);
50
+ if (!r || r.status !== "resolved") return false;
51
+ if (!ws.tasksOf(rid).list().some((t) => t.status !== "done")) return false;
52
+ try {
53
+ await ws.requests.update(rid, { status: "active" }, { actor });
54
+ return true;
55
+ } catch (e) {
56
+ throw new Error(`タスクは更新しましたが、要望 ${rid} を進行中に戻せませんでした: ${(e as Error).message}(p3 request set ${rid} status=active で直してください)`);
57
+ }
58
+ }
@@ -0,0 +1,228 @@
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, type Attachment, type AttachmentFormat, type FixedAttachment } from "../../shared/types.ts";
5
+ import { imageInfo, UI_LIMITS } from "../preflight/uiMaterials.ts";
6
+ import { nowIso, writeFileAtomic } from "./fsutil.ts";
7
+
8
+ export const ATTACHMENT_ID = /^A-\d{8}-\d{6}-[0-9a-f]{4}$/;
9
+
10
+ /** 上限(1つの要望あたり) */
11
+ export const ATTACHMENT_LIMITS = {
12
+ ...ATTACHMENT_FILE_LIMITS,
13
+ /** xlsx(ZIP)の項目数と、展開したときの合計(中身は読まない。一覧だけで断る) */
14
+ zipEntries: 10_000,
15
+ zipUncompressed: 200 * 1024 * 1024,
16
+ } as const;
17
+
18
+ export class AttachmentError extends Error {}
19
+
20
+ const EXT: Record<AttachmentFormat, string> = { png: "png", jpeg: "jpg", xlsx: "xlsx" };
21
+ export const ATTACHMENT_TYPES: Record<AttachmentFormat, string> = {
22
+ png: "image/png",
23
+ jpeg: "image/jpeg",
24
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
25
+ };
26
+
27
+ /**
28
+ * ZIP の一覧(中央ディレクトリ)だけを読む。展開はしない(中身の読み取りは xlsx の展開で、別に上限をかけて行う)。
29
+ * 読めなければ undefined
30
+ */
31
+ export function zipEntries(buf: Buffer): { name: string; uncompressed: number }[] | undefined {
32
+ const min = Math.max(0, buf.length - 65_557);
33
+ let eocd = -1;
34
+ for (let i = buf.length - 22; i >= min; i--) {
35
+ if (buf.readUInt32LE(i) === 0x06054b50) {
36
+ eocd = i;
37
+ break;
38
+ }
39
+ }
40
+ if (eocd < 0) return undefined;
41
+ const count = buf.readUInt16LE(eocd + 10);
42
+ let at = buf.readUInt32LE(eocd + 16);
43
+ const entries: { name: string; uncompressed: number }[] = [];
44
+ for (let i = 0; i < count; i++) {
45
+ if (at + 46 > buf.length || buf.readUInt32LE(at) !== 0x02014b50) return undefined;
46
+ const nameLen = buf.readUInt16LE(at + 28);
47
+ const extra = buf.readUInt16LE(at + 30);
48
+ const comment = buf.readUInt16LE(at + 32);
49
+ entries.push({ name: buf.toString("utf8", at + 46, at + 46 + nameLen), uncompressed: buf.readUInt32LE(at + 24) });
50
+ at += 46 + nameLen + extra + comment;
51
+ }
52
+ return entries;
53
+ }
54
+
55
+ /** 中身から形式を決めて確かめる。拡張子とも合わせる。だめなら AttachmentError */
56
+ export function inspectAttachment(data: Buffer, name: string): { format: AttachmentFormat; width?: number; height?: number } {
57
+ const ext = name.toLowerCase().split(".").pop() ?? "";
58
+ const want: AttachmentFormat | undefined = ext === "png" ? "png" : ext === "jpg" || ext === "jpeg" ? "jpeg" : ext === "xlsx" ? "xlsx" : undefined;
59
+ if (!want) throw new AttachmentError(`添付できるのは PNG / JPEG / xlsx です(${name})。xls や xlsm は xlsx で保存し直すか、画像にしてください`);
60
+ if (want === "xlsx") {
61
+ if (data.length > ATTACHMENT_LIMITS.xlsxBytes) throw new AttachmentError(`xlsx が大きすぎます(上限 ${ATTACHMENT_LIMITS.xlsxBytes} バイト)`);
62
+ if (data.readUInt32LE(0) !== 0x04034b50) throw new AttachmentError(`${name}: xlsx(ZIP)として読めません`);
63
+ const entries = zipEntries(data);
64
+ if (!entries) throw new AttachmentError(`${name}: xlsx(ZIP)の一覧が読めません`);
65
+ if (entries.length > ATTACHMENT_LIMITS.zipEntries) throw new AttachmentError(`${name}: 中のファイルが多すぎます(${entries.length})`);
66
+ const total = entries.reduce((n, e) => n + e.uncompressed, 0);
67
+ if (total > ATTACHMENT_LIMITS.zipUncompressed) throw new AttachmentError(`${name}: 展開すると大きすぎます(${total} バイト)`);
68
+ if (entries.some((e) => e.name.startsWith("/") || e.name.includes("\\") || e.name.split("/").includes(".."))) throw new AttachmentError(`${name}: 中に外を指すパスがあります`);
69
+ const names = new Set(entries.map((e) => e.name));
70
+ if (!names.has("[Content_Types].xml") || !names.has("xl/workbook.xml")) throw new AttachmentError(`${name}: xlsx のブックではありません`);
71
+ if ([...names].some((n) => /vbaProject\.bin$/i.test(n))) throw new AttachmentError(`${name}: マクロを含むブックは扱いません(マクロを外した xlsx にしてください)`);
72
+ return { format: "xlsx" };
73
+ }
74
+ if (data.length > ATTACHMENT_LIMITS.imageBytes) throw new AttachmentError(`画像が大きすぎます(上限 ${ATTACHMENT_LIMITS.imageBytes} バイト)`);
75
+ const info = imageInfo(data);
76
+ if (!info) throw new AttachmentError(`${name}: PNG / JPEG として読めません`);
77
+ if (info.format !== want) throw new AttachmentError(`${name}: 拡張子と中身の形式が合いません(中身は ${info.format})`);
78
+ if (info.width > UI_LIMITS.width || info.height > UI_LIMITS.height || info.width * info.height > UI_LIMITS.pixels) {
79
+ throw new AttachmentError(`${name}: 画像の大きさが上限を超えています(${info.width}x${info.height})`);
80
+ }
81
+ return info;
82
+ }
83
+
84
+ /** ダウンロードの名前(制御文字・パスの区切りを外す) */
85
+ export function safeFileName(name: string, format: AttachmentFormat): string {
86
+ // oxlint-disable-next-line no-control-regex -- 制御文字を外すのが目的
87
+ const base = name.replace(/[\u0000-\u001f\u007f/\\:*?"<>|]/g, "_").replace(/^\.+/, "").trim().slice(0, 120);
88
+ const ext = `.${EXT[format]}`;
89
+ const withExt = /\.(png|jpe?g|xlsx)$/i.test(base) ? base : `${base || "attachment"}${ext}`;
90
+ return withExt || `attachment${ext}`;
91
+ }
92
+
93
+ /**
94
+ * requests/<要望ID>/attachments/<ID>/
95
+ * meta.json 元の名前・説明・出典・形式・大きさ・sha256・追加した人と日時
96
+ * file.<拡張子> 原本(内部の名前)
97
+ *
98
+ * 1件1フォルダなので、複数人が同時に足しても衝突しない。書きかけ(.tmp-)と消しかけ(.del-)は一覧に出さない。
99
+ */
100
+ export class AttachmentStore {
101
+ constructor(readonly requestsDir: string) {}
102
+
103
+ dir(requestId: string) {
104
+ return join(this.requestsDir, requestId, "attachments");
105
+ }
106
+
107
+ private fileOf(requestId: string, a: Pick<Attachment, "id" | "format">) {
108
+ return join(this.dir(requestId), a.id, `file.${EXT[a.format]}`);
109
+ }
110
+
111
+ async add(requestId: string, input: { data: Buffer; name: string; description?: string; source?: string }, actor?: string): Promise<Attachment> {
112
+ const name = input.name.trim().split(/[\\/]/).pop() ?? "";
113
+ if (!name) throw new AttachmentError("ファイル名がありません");
114
+ const info = inspectAttachment(input.data, name);
115
+ const { items } = await this.list(requestId);
116
+ if (items.length >= ATTACHMENT_LIMITS.count) throw new AttachmentError(`添付は1つの要望に ${ATTACHMENT_LIMITS.count} 件までです`);
117
+ const total = items.reduce((n, a) => n + a.bytes, 0) + input.data.length;
118
+ if (total > ATTACHMENT_LIMITS.totalBytes) throw new AttachmentError(`添付の合計が上限(${ATTACHMENT_LIMITS.totalBytes} バイト)を超えます`);
119
+ const createdAt = nowIso();
120
+ const id = `A-${createdAt.replace(/[-:]/g, "").replace("T", "-").slice(0, 15)}-${randomBytes(2).toString("hex")}`;
121
+ const text = (v?: string) => (v?.trim() ? v.trim() : undefined);
122
+ const a: Attachment = {
123
+ id,
124
+ requestId,
125
+ name,
126
+ format: info.format,
127
+ bytes: input.data.length,
128
+ sha256: createHash("sha256").update(input.data).digest("hex"),
129
+ ...(text(input.description) ? { description: text(input.description) } : {}),
130
+ ...(text(input.source) ? { source: text(input.source) } : {}),
131
+ ...(info.width ? { width: info.width, height: info.height } : {}),
132
+ createdAt,
133
+ ...(actor ? { createdBy: actor } : {}),
134
+ };
135
+ // 書きかけのフォルダに全部書いてから名前を変える(途中で止まっても一覧に半端なものが出ない)
136
+ const tmp = join(this.dir(requestId), `.tmp-${id}`);
137
+ await mkdir(tmp, { recursive: true });
138
+ try {
139
+ await writeFile(join(tmp, `file.${EXT[a.format]}`), input.data);
140
+ await writeFile(join(tmp, "meta.json"), JSON.stringify(withoutRequest(a), null, 2) + "\n");
141
+ await rename(tmp, join(this.dir(requestId), id));
142
+ } catch (e) {
143
+ await rm(tmp, { recursive: true, force: true });
144
+ throw e;
145
+ }
146
+ return a;
147
+ }
148
+
149
+ /** 古い順。読めないものは invalid に理由(黙って捨てない) */
150
+ async list(requestId: string): Promise<{ items: Attachment[]; invalid: { id: string; error: string }[] }> {
151
+ const names = await readdir(this.dir(requestId)).catch(() => [] as string[]);
152
+ const items: Attachment[] = [];
153
+ const invalid: { id: string; error: string }[] = [];
154
+ for (const id of names.filter((n) => !n.startsWith("."))) {
155
+ try {
156
+ items.push(await this.read(requestId, id));
157
+ } catch (e) {
158
+ invalid.push({ id, error: (e as Error).message });
159
+ }
160
+ }
161
+ items.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
162
+ return { items, invalid };
163
+ }
164
+
165
+ private async read(requestId: string, id: string): Promise<Attachment> {
166
+ if (!ATTACHMENT_ID.test(id)) throw new AttachmentError("名前が A-YYYYMMDD-HHMMSS-xxxx ではありません");
167
+ const dir = join(this.dir(requestId), id);
168
+ const st = await lstat(dir);
169
+ if (!st.isDirectory()) throw new AttachmentError("フォルダではありません");
170
+ const meta = JSON.parse(await readFile(join(dir, "meta.json"), "utf8"));
171
+ if (meta.id !== id || !(meta.format in EXT) || typeof meta.name !== "string") throw new AttachmentError("meta.json が読めません");
172
+ return { ...meta, requestId };
173
+ }
174
+
175
+ async get(requestId: string, id: string): Promise<Attachment | undefined> {
176
+ if (!ATTACHMENT_ID.test(id)) return undefined;
177
+ return this.read(requestId, id).catch(() => undefined);
178
+ }
179
+
180
+ /** 原本を読む。保存したときの形式・大きさ・sha256 と合うかを確かめる(差し替えやシンボリックリンクは断る) */
181
+ async content(requestId: string, id: string): Promise<{ meta: Attachment; data: Buffer }> {
182
+ const meta = await this.get(requestId, id);
183
+ if (!meta) throw new AttachmentError(`添付 ${id} がありません`);
184
+ const file = this.fileOf(requestId, meta);
185
+ const st = await lstat(file).catch(() => undefined);
186
+ if (!st?.isFile()) throw new AttachmentError(`添付 ${id} の原本がありません`);
187
+ const data = await readFile(file);
188
+ if (data.length !== meta.bytes || createHash("sha256").update(data).digest("hex") !== meta.sha256) {
189
+ throw new AttachmentError(`添付 ${id} の原本が保存したときと変わっています`);
190
+ }
191
+ return { meta, data };
192
+ }
193
+
194
+ async remove(requestId: string, id: string): Promise<void> {
195
+ if (!(await this.get(requestId, id))) throw new AttachmentError(`添付 ${id} がありません`);
196
+ // 先に名前を変えて一覧から外してから消す(消しかけを開始時のコピーが読まない)
197
+ const del = join(this.dir(requestId), `.del-${id}-${randomBytes(2).toString("hex")}`);
198
+ await rename(join(this.dir(requestId), id), del);
199
+ await rm(del, { recursive: true, force: true });
200
+ }
201
+
202
+ /**
203
+ * Preflight を始めるときに、今の添付を run の中へコピーして固定する。画像は <runDir>/ui/current/、xlsx は
204
+ * <runDir>/attachments/ に置き、一覧を <runDir>/attachments.json に書く。コピーの途中で消された・変わったものがあれば
205
+ * AttachmentError(その Preflight は始めない。原本は残る)
206
+ */
207
+ async snapshot(requestId: string, runDir: string): Promise<FixedAttachment[]> {
208
+ const { items } = await this.list(requestId);
209
+ const fixed: FixedAttachment[] = [];
210
+ for (const a of items) {
211
+ let data: Buffer;
212
+ try {
213
+ ({ data } = await this.content(requestId, a.id));
214
+ } catch (e) {
215
+ throw new AttachmentError(`添付を固定できません(始める間に添付が変わりました。もう一度始めてください): ${(e as Error).message}`);
216
+ }
217
+ const path = a.format === "xlsx" ? `attachments/${a.id}.xlsx` : `ui/current/${a.id}.${EXT[a.format]}`;
218
+ await mkdir(join(runDir, path, ".."), { recursive: true });
219
+ await writeFile(join(runDir, path), data);
220
+ const { requestId: _, ...rest } = a;
221
+ fixed.push({ ...rest, path });
222
+ }
223
+ if (fixed.length) await writeFileAtomic(join(runDir, "attachments.json"), JSON.stringify(fixed, null, 2) + "\n");
224
+ return fixed;
225
+ }
226
+ }
227
+
228
+ const withoutRequest = ({ requestId: _, ...a }: Attachment) => a;