@infodb/p3 0.3.0 → 0.5.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/bin/p3.mjs +11 -5
  2. package/dist/web/assets/Outputs-C83ZDXvs.js +1 -0
  3. package/dist/web/assets/RequestStatus-GmiWYEcL.js +1 -0
  4. package/dist/web/assets/Tabs-CJn0Qy7W.js +1 -0
  5. package/dist/web/assets/TagInput-CtM8HM8Z.js +1 -0
  6. package/dist/web/assets/TaskDrawer-D5v36QoF.js +3 -0
  7. package/dist/web/assets/_requestId-BHUqLO-j.js +1 -0
  8. package/dist/web/assets/_requestId-DxwxbXY2.js +30 -0
  9. package/dist/web/assets/{ui-Sz7y5_TS.js → appCtx-B-VRVOyv.js} +1 -1
  10. package/dist/web/assets/board-DAaVR04x.js +1 -0
  11. package/dist/web/assets/copy-CKsXEjMi.js +1 -0
  12. package/dist/web/assets/done-CaqB_qTH.js +1 -0
  13. package/dist/web/assets/index-BF1xMdJo.css +2 -0
  14. package/dist/web/assets/index-BQYvKpjF.js +12 -0
  15. package/dist/web/assets/milestoneOrder-N7b5XFJP.js +1 -0
  16. package/dist/web/assets/new-DLVnRvrB.js +1 -0
  17. package/dist/web/assets/preflightInput-BAeEJYUK.js +2 -0
  18. package/dist/web/assets/preload-helper-B74h5i3O.js +1 -0
  19. package/dist/web/assets/progressTree-wp9mH4VF.js +1 -0
  20. package/dist/web/assets/release-notes-MTLcOcvZ.js +3 -0
  21. package/dist/web/assets/requestData-D-HXu-cy.js +1 -0
  22. package/dist/web/assets/routes-CI4Qfkjs.js +3 -0
  23. package/dist/web/assets/settings-CJMNgzi6.js +1 -0
  24. package/dist/web/index.html +4 -4
  25. package/docs/architecture.md +238 -9
  26. package/docs/development.md +16 -9
  27. package/docs/how-to-use.md +128 -12
  28. package/docs/installation.md +8 -6
  29. package/docs/publishing.md +4 -2
  30. package/lib/cli/args.js +172 -0
  31. package/lib/cli/chatgpt.js +70 -0
  32. package/lib/cli/codex.js +30 -0
  33. package/lib/cli/format.js +9 -0
  34. package/{src/cli/help.ts → lib/cli/help.js} +11 -8
  35. package/lib/cli/main.js +326 -0
  36. package/lib/cli/output.js +110 -0
  37. package/lib/cli/preflightCommands.js +301 -0
  38. package/lib/cli/project.js +649 -0
  39. package/lib/cli/readOnly.js +36 -0
  40. package/lib/cli/releaseNotesCommands.js +197 -0
  41. package/lib/cli/render.js +58 -0
  42. package/lib/cli/requestCommands.js +180 -0
  43. package/lib/cli/showView.js +100 -0
  44. package/lib/cli/taskCommands.js +152 -0
  45. package/lib/cli/userConfig.js +64 -0
  46. package/{src/core/chatgpt.ts → lib/core/chatgpt.js} +10 -16
  47. package/lib/core/context.js +41 -0
  48. package/lib/core/hierarchy.js +128 -0
  49. package/lib/core/machineSettings.js +146 -0
  50. package/lib/core/machineSettingsEdit.js +148 -0
  51. package/lib/core/ops.js +120 -0
  52. package/lib/core/preflight/carryover.js +105 -0
  53. package/lib/core/preflight/codexEngine.js +687 -0
  54. package/lib/core/preflight/codexImage.js +61 -0
  55. package/lib/core/preflight/diagnose.js +95 -0
  56. package/lib/core/preflight/engine.js +58 -0
  57. package/lib/core/preflight/input.js +83 -0
  58. package/lib/core/preflight/launch.js +68 -0
  59. package/lib/core/preflight/mockEngine.js +175 -0
  60. package/lib/core/preflight/render.js +304 -0
  61. package/lib/core/preflight/service.js +868 -0
  62. package/lib/core/preflight/split.js +83 -0
  63. package/lib/core/preflight/uiMaterials.js +281 -0
  64. package/lib/core/preflight/uiRender.js +89 -0
  65. package/lib/core/preflight/wireframe.js +63 -0
  66. package/lib/core/preflight/xlsx.js +324 -0
  67. package/lib/core/projectRegistry.js +207 -0
  68. package/lib/core/redact.js +28 -0
  69. package/lib/core/releaseNotes/completeRequests.js +106 -0
  70. package/lib/core/releaseNotes/generate.js +266 -0
  71. package/lib/core/releaseNotes/material.js +141 -0
  72. package/lib/core/releaseNotes/mockSummarizer.js +26 -0
  73. package/lib/core/releaseNotes/service.js +83 -0
  74. package/lib/core/releaseNotes/store.js +209 -0
  75. package/lib/core/repoAdmin.js +82 -0
  76. package/lib/core/repoRefs.js +72 -0
  77. package/lib/core/requestOps.js +154 -0
  78. package/lib/core/requestStatus.js +171 -0
  79. package/lib/core/store/attachments.js +242 -0
  80. package/lib/core/store/collection.js +254 -0
  81. package/lib/core/store/frontmatter.js +18 -0
  82. package/lib/core/store/fsutil.js +84 -0
  83. package/lib/core/store/locate.js +162 -0
  84. package/lib/core/store/normalize.js +150 -0
  85. package/lib/core/store/noteStore.js +59 -0
  86. package/lib/core/store/preflightStore.js +161 -0
  87. package/lib/core/store/projectFile.js +99 -0
  88. package/lib/core/store/workspace.js +320 -0
  89. package/lib/core/supersede.js +69 -0
  90. package/lib/core/userConfig.js +158 -0
  91. package/{src/core/userTheme.ts → lib/core/userTheme.js} +11 -13
  92. package/lib/core/workTargets.js +106 -0
  93. package/lib/server/api/chatgptRoutes.js +46 -0
  94. package/{src/server/api/local.ts → lib/server/api/local.js} +23 -22
  95. package/lib/server/api/manifest.js +140 -0
  96. package/lib/server/api/projectsRoutes.js +82 -0
  97. package/lib/server/api/releaseNoteRoutes.js +88 -0
  98. package/lib/server/api/repoRoutes.js +67 -0
  99. package/lib/server/api/routes.js +404 -0
  100. package/lib/server/api/userThemeRoutes.js +60 -0
  101. package/lib/server/server.js +85 -0
  102. package/lib/shared/dates.js +10 -0
  103. package/{src/shared/directTask.ts → lib/shared/directTask.js} +3 -11
  104. package/lib/shared/hierarchy.js +120 -0
  105. package/lib/shared/milestoneOrder.js +45 -0
  106. package/lib/shared/preflightInput.js +19 -0
  107. package/lib/shared/refs.js +44 -0
  108. package/lib/shared/repos.js +69 -0
  109. package/lib/shared/scopeView.js +39 -0
  110. package/{src/shared/tags.ts → lib/shared/tags.js} +9 -14
  111. package/lib/shared/types.js +74 -0
  112. package/lib/shared/workTarget.js +31 -0
  113. package/package.json +4 -7
  114. package/skills/p3/SKILL.md +29 -8
  115. package/dist/web/assets/Outputs-DqJdybkd.js +0 -1
  116. package/dist/web/assets/RequestStatus-DN-2iAM0.js +0 -1
  117. package/dist/web/assets/TagInput-D-1ILLDX.js +0 -1
  118. package/dist/web/assets/TaskDrawer-CHD7T-Su.js +0 -3
  119. package/dist/web/assets/_requestId-BzSepQIV.js +0 -30
  120. package/dist/web/assets/_requestId-pIds2tFU.js +0 -1
  121. package/dist/web/assets/board-BIkOpuC4.js +0 -1
  122. package/dist/web/assets/copy-B1ZbihKL.js +0 -2
  123. package/dist/web/assets/done-BUAUhIRr.js +0 -1
  124. package/dist/web/assets/index-Byv9j77D.js +0 -12
  125. package/dist/web/assets/index-DTfUhuQw.css +0 -2
  126. package/dist/web/assets/new-6kly4-PX.js +0 -1
  127. package/dist/web/assets/preload-helper-DlN0ouRj.js +0 -1
  128. package/dist/web/assets/release-notes-iwQWmfX6.js +0 -3
  129. package/dist/web/assets/requestData-DJ1Rlx-u.js +0 -1
  130. package/dist/web/assets/routes-Ciot9p4x.js +0 -2
  131. package/dist/web/assets/settings-DBCi6lAY.js +0 -1
  132. package/src/cli/args.ts +0 -186
  133. package/src/cli/chatgpt.ts +0 -74
  134. package/src/cli/codex.ts +0 -28
  135. package/src/cli/format.ts +0 -9
  136. package/src/cli/main.ts +0 -336
  137. package/src/cli/output.ts +0 -117
  138. package/src/cli/preflightCommands.ts +0 -245
  139. package/src/cli/project.ts +0 -672
  140. package/src/cli/readOnly.ts +0 -36
  141. package/src/cli/releaseNotesCommands.ts +0 -159
  142. package/src/cli/render.ts +0 -60
  143. package/src/cli/requestCommands.ts +0 -170
  144. package/src/cli/showView.ts +0 -110
  145. package/src/cli/taskCommands.ts +0 -167
  146. package/src/cli/userConfig.ts +0 -58
  147. package/src/core/context.ts +0 -58
  148. package/src/core/machineSettings.ts +0 -207
  149. package/src/core/machineSettingsEdit.ts +0 -156
  150. package/src/core/ops.ts +0 -114
  151. package/src/core/preflight/carryover.ts +0 -133
  152. package/src/core/preflight/codexEngine.ts +0 -703
  153. package/src/core/preflight/codexImage.ts +0 -98
  154. package/src/core/preflight/diagnose.ts +0 -124
  155. package/src/core/preflight/engine.ts +0 -92
  156. package/src/core/preflight/input.ts +0 -65
  157. package/src/core/preflight/launch.ts +0 -86
  158. package/src/core/preflight/mockEngine.ts +0 -145
  159. package/src/core/preflight/render.ts +0 -339
  160. package/src/core/preflight/service.ts +0 -707
  161. package/src/core/preflight/uiMaterials.ts +0 -272
  162. package/src/core/preflight/uiRender.ts +0 -84
  163. package/src/core/preflight/wireframe.ts +0 -69
  164. package/src/core/preflight/xlsx.ts +0 -328
  165. package/src/core/projectRegistry.ts +0 -264
  166. package/src/core/redact.ts +0 -31
  167. package/src/core/releaseNotes/generate.ts +0 -283
  168. package/src/core/releaseNotes/material.ts +0 -114
  169. package/src/core/releaseNotes/mockSummarizer.ts +0 -28
  170. package/src/core/releaseNotes/service.ts +0 -106
  171. package/src/core/releaseNotes/store.ts +0 -216
  172. package/src/core/repoAdmin.ts +0 -81
  173. package/src/core/repoRefs.ts +0 -90
  174. package/src/core/requestOps.ts +0 -140
  175. package/src/core/requestStatus.ts +0 -58
  176. package/src/core/store/attachments.ts +0 -228
  177. package/src/core/store/collection.ts +0 -282
  178. package/src/core/store/frontmatter.ts +0 -22
  179. package/src/core/store/fsutil.ts +0 -90
  180. package/src/core/store/locate.ts +0 -181
  181. package/src/core/store/normalize.ts +0 -155
  182. package/src/core/store/noteStore.ts +0 -56
  183. package/src/core/store/preflightStore.ts +0 -136
  184. package/src/core/store/projectFile.ts +0 -101
  185. package/src/core/store/workspace.ts +0 -328
  186. package/src/core/supersede.ts +0 -74
  187. package/src/core/userConfig.ts +0 -205
  188. package/src/core/workTargets.ts +0 -120
  189. package/src/server/api/chatgptRoutes.ts +0 -49
  190. package/src/server/api/manifest.ts +0 -128
  191. package/src/server/api/projectsRoutes.ts +0 -89
  192. package/src/server/api/releaseNoteRoutes.ts +0 -78
  193. package/src/server/api/repoRoutes.ts +0 -67
  194. package/src/server/api/routes.ts +0 -382
  195. package/src/server/api/userThemeRoutes.ts +0 -62
  196. package/src/server/server.ts +0 -108
  197. package/src/shared/dates.ts +0 -12
  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 -700
  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
@@ -1,181 +0,0 @@
1
- import { execFileSync } from "node:child_process";
2
- import { existsSync } from "node:fs";
3
- import { stat } from "node:fs/promises";
4
- import { dirname, join, resolve, sep } from "node:path";
5
- import type { UserConfig } from "../userConfig.ts";
6
-
7
- /** p3 init がデータを置く既定のフォルダ名(リポジトリのルートの直下) */
8
- export const DATA_DIR_NAME = ".p3";
9
-
10
- export interface ResolvedProject {
11
- /** 個人設定に登録したプロジェクト名(登録していないフォルダを --dir で指したときは無い) */
12
- name?: string;
13
- dataDir: string;
14
- /** 個人設定の参照先の名前 → このマシンのパス(Preflight が読む。全部) */
15
- repos: Record<string, string>;
16
- /** どうやって決まったか */
17
- via: "dir" | "project" | "cwd" | "legacy" | "only";
18
- }
19
-
20
- /** プロジェクトの決まり方の説明(whoami の表)。cwd 以外は今いる場所で決まっていない */
21
- export const VIA_LABEL: Record<ResolvedProject["via"], string> = {
22
- dir: "--dir で指定",
23
- project: "--project で指定",
24
- cwd: "今いる場所",
25
- legacy: "リポジトリの中の .p3/",
26
- only: "登録が1つだけ。今いる場所では決まっていない",
27
- };
28
-
29
- /** 操作するプロジェクトが決まらない(次に何をすればよいかをメッセージに含める) */
30
- export class ProjectNotResolvedError extends Error {}
31
-
32
- /** データのフォルダが無い・project.yaml が無い・読めない(次にすることをメッセージに含める)。ファイルは何も変えていない */
33
- export class DataDirError extends Error {}
34
-
35
- /**
36
- * データのフォルダとその project.yaml があるかを確かめる(プロジェクトを開く前。CLI と serve の共通の入口 openProject から)。
37
- * 無いのに空のプロジェクトとして続けると、書く操作がフォルダを新しく作って別の場所に書いてしまう(移した・共有ドライブが
38
- * つながっていない・パスの誤り)。無い(ENOENT)と読めない(権限・入出力)は分けて伝える。フォルダもファイルも作らない。
39
- * requests/ は無くてよい(作ったばかりのプロジェクト)
40
- */
41
- export async function checkDataDir(dataDir: string, projectName?: string): Promise<void> {
42
- const yaml = join(dataDir, "project.yaml");
43
- const problem = async (): Promise<string | undefined> => {
44
- const dir = await stat(dataDir).catch((e: NodeJS.ErrnoException) => e);
45
- if (dir instanceof Error) {
46
- return dir.code === "ENOENT" ? `データのフォルダがありません: ${dataDir}` : `データのフォルダを読めません: ${dataDir}(${dir.code ?? dir.message})`;
47
- }
48
- if (!dir.isDirectory()) return `データのフォルダがフォルダではありません: ${dataDir}`;
49
- const file = await stat(yaml).catch((e: NodeJS.ErrnoException) => e);
50
- if (file instanceof Error) {
51
- return file.code === "ENOENT" ? `データのフォルダに project.yaml がありません: ${yaml}` : `project.yaml を読めません: ${yaml}(${file.code ?? file.message})`;
52
- }
53
- if (!file.isFile()) return `project.yaml がファイルではありません: ${yaml}`;
54
- return undefined;
55
- };
56
- const head = await problem();
57
- if (!head) return;
58
- const name = projectName ?? "<名前>";
59
- throw new DataDirError(
60
- [
61
- head,
62
- projectName ? ` (個人設定のプロジェクト「${projectName}」の登録先)` : "",
63
- " 既にあるデータなら: パスの誤り・フォルダの移動・共有ドライブ(同期するフォルダ)がつながっているかを確かめる",
64
- projectName
65
- ? ` 登録の場所を直すとき: p3 project ls で確かめ、p3 project rm ${name} → p3 project add ${name} <正しいフォルダ>(rm はデータを消さない)`
66
- : " --dir で指すときは、project.yaml のあるフォルダを指す",
67
- ` 新しく作るなら: 管理したいリポジトリの中で p3 init --project ${name} --dir <フォルダ>(ほかの人が作ったものに参加するなら p3 join)`,
68
- ]
69
- .filter(Boolean)
70
- .join("\n"),
71
- );
72
- }
73
-
74
- /**
75
- * 登録が1つだけで決まった(via: only)ときの案内。今いる場所とは関係なく決まるので、p3 を使わないフォルダでも当たる。
76
- * 変える操作は止め(write)、読むだけの操作は警告して続ける。どちらも、プロジェクトを明示する方法と移る先を示す
77
- */
78
- export function onlyRegistrationNotice(p: ResolvedProject, write: boolean): string {
79
- const name = p.name ?? "<名前>";
80
- return [
81
- write
82
- ? `今いる場所ではプロジェクトが決まりません(登録が1つだけなので「${name}」になりますが、変える操作はしません)。`
83
- : `※ 今いる場所ではプロジェクトが決まらず、登録が1つだけなので「${name}」を表示しています。変える操作の前には対象を明示してください。`,
84
- ` プロジェクト: ${name} ${p.dataDir}`,
85
- ` → p3 --project ${name} <コマンド> で明示する`,
86
- ` → または登録したリポジトリ(p3 --project ${name} repo ls)かデータのフォルダの中で実行する`,
87
- ].join("\n");
88
- }
89
-
90
- /**
91
- * 操作するプロジェクトを決める。環境変数では切り替えない(同じ人が複数のプロジェクトを行き来するため)。
92
- *
93
- * 1. --dir <フォルダ> データのフォルダを直接指す
94
- * 2. --project <名前> 個人設定に登録したプロジェクト
95
- * 3. 今いる場所 登録したプロジェクトのデータのフォルダか、そのリポジトリ(作業ツリーを含む)の中
96
- * 4. リポジトリの中の .p3/ 個人設定に登録していないとき(git のメインの作業ツリー → 上へ辿る。デモ・登録前の clone など)
97
- * 5. 登録が1つだけ それを使う
98
- */
99
- export function resolveProject(o: { cwd: string; dir?: string; project?: string; user: UserConfig }): ResolvedProject {
100
- const entries = Object.entries(o.user.projects);
101
- const named = ([name, p]: (typeof entries)[number], via: ResolvedProject["via"]): ResolvedProject => ({
102
- name,
103
- dataDir: p.dir,
104
- repos: { ...p.repos },
105
- via,
106
- });
107
-
108
- if (o.dir) {
109
- const dataDir = resolve(o.cwd, o.dir);
110
- const hit = entries.find(([, p]) => p.dir === dataDir);
111
- return hit ? named(hit, "dir") : { dataDir, repos: {}, via: "dir" };
112
- }
113
- if (o.project) {
114
- const hit = entries.find(([name]) => name === o.project);
115
- if (!hit) throw new ProjectNotResolvedError(`プロジェクト「${o.project}」は登録されていません。\n${listing(o.user)}`);
116
- return named(hit, "project");
117
- }
118
-
119
- const places = [...new Set([resolve(o.cwd), mainWorktree(o.cwd)].filter((x): x is string => !!x))];
120
- const hits = entries.filter(([, p]) => places.some((pl) => inside(pl, p.dir) || Object.values(p.repos).some((r) => inside(pl, r))));
121
- if (hits.length === 1) return named(hits[0], "cwd");
122
- if (hits.length > 1) {
123
- throw new ProjectNotResolvedError(
124
- `この場所は複数のプロジェクトに登録されています: ${hits.map(([n]) => n).join(", ")}\n → p3 --project <名前> <コマンド> で選んでください`,
125
- );
126
- }
127
-
128
- const legacy = findDataDir(o.cwd);
129
- if (legacy) {
130
- const hit = entries.find(([, p]) => p.dir === legacy);
131
- return hit ? named(hit, "legacy") : { dataDir: legacy, repos: {}, via: "legacy" };
132
- }
133
- if (entries.length === 1) return named(entries[0], "only");
134
-
135
- throw new ProjectNotResolvedError(
136
- entries.length
137
- ? `操作するプロジェクトが決まりません(今いる場所: ${o.cwd})。\n${listing(o.user)}`
138
- : "プロジェクトがまだありません。管理したいリポジトリの中で次のどちらかを実行してください:\n 新しく作る: p3 init --project <名前>(データはリポジトリのルートの .p3。外に置くなら --dir <フォルダ>)\n 共有されたものに参加する: p3 join --project <名前>(ルートの .p3 に無ければ --dir <データのフォルダ>)",
139
- );
140
- }
141
-
142
- function listing(user: UserConfig): string {
143
- const entries = Object.entries(user.projects);
144
- if (!entries.length) return " (登録済みのプロジェクトはありません。p3 init で作るか、p3 join で参加してください)";
145
- const w = Math.max(...entries.map(([n]) => n.length));
146
- return [
147
- " 登録済みのプロジェクト:",
148
- ...entries.map(([n, p]) => ` ${n.padEnd(w)} ${p.dir}`),
149
- " → p3 --project <名前> <コマンド>、またはプロジェクトのリポジトリの中で実行してください",
150
- ].join("\n");
151
- }
152
-
153
- const inside = (path: string, dir: string) => path === dir || path.startsWith(dir.endsWith(sep) ? dir : dir + sep);
154
-
155
- /**
156
- * リポジトリの中の .p3/ を探す(個人設定に登録していないとき。登録していれば 3. の今いる場所で決まる)。
157
- * 要望ごとの作業ツリーの中で実行しても、git のメインの作業ツリーの .p3/ を使う(各作業ツリーの .p3/ はブランチ時点の写し)。
158
- */
159
- export function findDataDir(cwd: string): string | undefined {
160
- const main = mainWorktree(cwd);
161
- if (main && existsSync(join(main, DATA_DIR_NAME, "project.yaml"))) return join(main, DATA_DIR_NAME);
162
- for (let dir = resolve(cwd); ; dir = dirname(dir)) {
163
- if (existsSync(join(dir, DATA_DIR_NAME, "project.yaml"))) return join(dir, DATA_DIR_NAME);
164
- if (dirname(dir) === dir) return undefined;
165
- }
166
- }
167
-
168
- /** git のメインの作業ツリー(要望の作業ツリーの中からでもメインを返す) */
169
- export function mainWorktree(cwd: string): string | undefined {
170
- try {
171
- const common = execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
172
- cwd,
173
- encoding: "utf8",
174
- stdio: ["ignore", "pipe", "ignore"],
175
- }).trim();
176
- // 通常は <main>/.git。bare リポジトリなどはメインの作業ツリーが無いので対象外
177
- return common.endsWith("/.git") ? dirname(common) : undefined;
178
- } catch {
179
- return undefined;
180
- }
181
- }
@@ -1,155 +0,0 @@
1
- import { repoNameProblem, type CodeMapEntry, type RepoRef } from "../../shared/repos.ts";
2
- import { isTaskStatus, RELATION_TYPES, REQUEST_STATUSES, type ProjectConfig, type Relation, type RepoOutput, type Request, type RequestStatus, type Task, type Workstream } from "../../shared/types.ts";
3
-
4
- const str = (v: unknown): string | undefined => (v === undefined || v === null || v === "" ? undefined : String(v));
5
- const num = (v: unknown): number | undefined => (v === undefined || v === null || v === "" ? undefined : Number(v));
6
- const strs = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : typeof v === "string" ? [v] : []);
7
- /** YAML は日付を Date にしてしまうので YYYY-MM-DD に戻す */
8
- const date = (v: unknown): string | undefined => (v instanceof Date ? v.toISOString().slice(0, 10) : str(v));
9
- const iso = (v: unknown): string => (v instanceof Date ? v.toISOString() : (str(v) ?? new Date(0).toISOString()));
10
-
11
- export function normalizeRelations(v: unknown): Relation[] {
12
- if (!Array.isArray(v)) return [];
13
- return v
14
- .filter((r): r is Record<string, unknown> => !!r && typeof r === "object")
15
- .filter((r) => typeof r.type === "string" && r.type in RELATION_TYPES && typeof r.target === "string")
16
- .map((r) => ({
17
- type: r.type as Relation["type"],
18
- target: String(r.target),
19
- note: str(r.note),
20
- origin: str(r.origin) as Relation["origin"],
21
- }));
22
- }
23
-
24
- /** 要望 requestId のタスクとして読む(request / ref は場所から決まる) */
25
- export const normalizeTaskIn =
26
- (requestId: string) =>
27
- (d: Record<string, unknown>, body: string, id: string): Task => ({
28
- id,
29
- request: requestId,
30
- ref: `${requestId}/${id}`,
31
- title: str(d.title) ?? id,
32
- // 3つ以外(古い設定の列など)は未着手として読む
33
- status: isTaskStatus(d.status) ? d.status : "todo",
34
- labels: strs(d.labels),
35
- areas: strs(d.areas),
36
- outputs: strs(d.outputs),
37
- // 作業先(null / "" / 無いは作業先なし)
38
- repo: str(d.repo) ?? null,
39
- ...(Array.isArray(d.repoOutputs) ? { repoOutputs: normalizeRepoOutputs(d.repoOutputs) } : {}),
40
- startedAt: d.startedAt ? iso(d.startedAt) : undefined,
41
- doneAt: d.doneAt ? iso(d.doneAt) : undefined,
42
- checkedAt: d.checkedAt ? iso(d.checkedAt) : undefined,
43
- record: str(d.record)?.trim() || undefined,
44
- relations: normalizeRelations(d.relations),
45
- rev: num(d.rev) ?? 1,
46
- createdAt: iso(d.createdAt),
47
- updatedAt: iso(d.updatedAt),
48
- updatedBy: str(d.updatedBy),
49
- body,
50
- });
51
-
52
- export const TASK_KEY_ORDER: (keyof Task)[] = [
53
- "id", "title", "status", "repo", "labels", "areas", "outputs", "repoOutputs", "record",
54
- "relations", "rev", "createdAt", "startedAt", "doneAt", "checkedAt", "updatedAt", "updatedBy",
55
- ];
56
-
57
- export function normalizeRequest(d: Record<string, unknown>, body: string, id: string): Request {
58
- const status = str(d.status) as RequestStatus;
59
- return {
60
- id,
61
- title: str(d.title) ?? id,
62
- status: REQUEST_STATUSES.includes(status) ? status : "draft",
63
- areas: strs(d.areas),
64
- due: date(d.due),
65
- milestone: str(d.milestone),
66
- tags: strs(d.tags),
67
- ...(d.workstreams && typeof d.workstreams === "object" ? { workstreams: normalizeWorkstreams(d.workstreams) } : {}),
68
- lastPreflight: str(d.lastPreflight),
69
- rev: num(d.rev) ?? 1,
70
- createdAt: iso(d.createdAt),
71
- updatedAt: iso(d.updatedAt),
72
- updatedBy: str(d.updatedBy),
73
- body,
74
- };
75
- }
76
-
77
- export const REQUEST_KEY_ORDER: (keyof Request)[] = [
78
- "id", "title", "status", "due", "milestone", "tags", "areas", "workstreams", "lastPreflight",
79
- "rev", "createdAt", "updatedAt", "updatedBy",
80
- ];
81
-
82
- export function normalizeProject(d: Record<string, unknown>): ProjectConfig {
83
- const preflight = (d.preflight ?? {}) as Record<string, unknown>;
84
- return {
85
- name: str(d.name) ?? "p3 project",
86
- description: str(d.description) ?? "",
87
- repos: normalizeRepos(d.repos),
88
- milestones: Array.isArray(d.milestones)
89
- ? (d.milestones as unknown[])
90
- .filter((m): m is Record<string, unknown> => !!m && typeof m === "object" && !!(m as Record<string, unknown>).id)
91
- .map((m) => ({ id: String(m.id), title: str(m.title) ?? String(m.id), due: date(m.due), done: m.done === true ? true : undefined }))
92
- : [],
93
- branchPattern: str(d.branchPattern) ?? "req/{id}-{slug}",
94
- preflight: { instructions: str(preflight.instructions) ?? "" },
95
- };
96
- }
97
-
98
- /**
99
- * project.yaml の repos。名前をキーにした対応(推奨)か、name を持つ項目の並び。名前が使えない項目・重複は読まない
100
- * (書き戻すときも p3 repo で変えた項目のほかは触らないので、ファイルからは消えない)。
101
- * map は「パス: 役割」か「パス: { role, entry }」の対応、または { path, role, entry } の並び
102
- */
103
- export function normalizeRepos(v: unknown): RepoRef[] {
104
- const entries: [string, Record<string, unknown>][] = Array.isArray(v)
105
- ? v.filter((x): x is Record<string, unknown> => !!x && typeof x === "object").map((x) => [String(x.name ?? ""), x])
106
- : v && typeof v === "object"
107
- ? Object.entries(v as Record<string, unknown>).map(([k, x]) => [k, x && typeof x === "object" ? (x as Record<string, unknown>) : { role: x }])
108
- : [];
109
- const out: RepoRef[] = [];
110
- for (const [name, x] of entries) {
111
- if (repoNameProblem(name) || out.some((r) => r.name === name)) continue;
112
- out.push({
113
- name,
114
- role: str(x.role) ?? "",
115
- readFirst: x.readFirst === true,
116
- writable: x.writable === true,
117
- map: normalizeCodeMap(x.map),
118
- });
119
- }
120
- return out;
121
- }
122
-
123
- function normalizeCodeMap(v: unknown): CodeMapEntry[] {
124
- const one = (path: string, x: unknown): CodeMapEntry | undefined => {
125
- if (!path) return undefined;
126
- if (typeof x === "string") return { path, role: x };
127
- if (x && typeof x === "object") {
128
- const o = x as Record<string, unknown>;
129
- return { path, role: str(o.role) ?? "", ...(str(o.entry) ? { entry: str(o.entry) } : {}) };
130
- }
131
- return { path, role: "" };
132
- };
133
- const list = Array.isArray(v)
134
- ? v.map((x) => (x && typeof x === "object" ? one(String((x as Record<string, unknown>).path ?? ""), x) : undefined))
135
- : v && typeof v === "object"
136
- ? Object.entries(v as Record<string, unknown>).map(([k, x]) => one(k, x))
137
- : [];
138
- return list.filter((x): x is CodeMapEntry => !!x);
139
- }
140
-
141
- /** リポジトリごとの成果物。repo と output のどちらかが無い項目は読まない */
142
- export function normalizeRepoOutputs(v: unknown): RepoOutput[] {
143
- return (Array.isArray(v) ? v : [])
144
- .filter((x): x is Record<string, unknown> => !!x && typeof x === "object")
145
- .flatMap((x) => (str(x.repo) && str(x.output) ? [{ repo: str(x.repo)!, output: str(x.output)! }] : []));
146
- }
147
-
148
- function normalizeWorkstreams(v: object): Record<string, Workstream> {
149
- const out: Record<string, Workstream> = {};
150
- for (const [name, w] of Object.entries(v as Record<string, unknown>)) {
151
- const o = w && typeof w === "object" ? (w as Record<string, unknown>) : {};
152
- if (!repoNameProblem(name) && str(o.branch)) out[name] = { branch: str(o.branch)! };
153
- }
154
- return out;
155
- }
@@ -1,56 +0,0 @@
1
- import { readdir, readFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { randomBytes } from "node:crypto";
4
- import type { PreflightNote } from "../../shared/types.ts";
5
- import { parseFrontmatter, stringifyFrontmatter } from "./frontmatter.ts";
6
- import { createExclusive, nowIso } from "./fsutil.ts";
7
-
8
- export const NOTE_ID = /^N-\d{8}-\d{6}-[0-9a-f]{4}$/;
9
-
10
- /**
11
- * requests/<要望ID>/notes/N-....md Preflight へのメモ(1件1ファイル。書き足すだけで、直さない)
12
- *
13
- * 誰がいつ書いたかを frontmatter に残す。ファイルを分けるので、複数人が同時に書いても衝突しない。
14
- */
15
- export class NoteStore {
16
- /** requestsDir: .p3/requests */
17
- constructor(readonly requestsDir: string) {}
18
-
19
- dir(requestId: string) {
20
- return join(this.requestsDir, requestId, "notes");
21
- }
22
-
23
- async add(requestId: string, body: string, actor?: string): Promise<PreflightNote> {
24
- const text = body.trim();
25
- if (!text) throw new Error("メモが空です");
26
- for (;;) {
27
- const createdAt = nowIso();
28
- const stamp = createdAt.replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
29
- const note: PreflightNote = { id: `N-${stamp}-${randomBytes(2).toString("hex")}`, requestId, createdAt, createdBy: actor, body: text };
30
- const file = stringifyFrontmatter({ id: note.id, createdAt, createdBy: actor }, text);
31
- if (await createExclusive(join(this.dir(requestId), `${note.id}.md`), file)) return note;
32
- }
33
- }
34
-
35
- /** 古い順(作成日時、同じなら ID)。読めないファイルは invalid に理由を返す(黙って捨てない) */
36
- async list(requestId: string): Promise<{ notes: PreflightNote[]; invalid: { file: string; error: string }[] }> {
37
- const files = (await readdir(this.dir(requestId)).catch(() => [] as string[])).filter((f) => f.endsWith(".md"));
38
- const notes: PreflightNote[] = [];
39
- const invalid: { file: string; error: string }[] = [];
40
- for (const f of files) {
41
- const id = f.slice(0, -3);
42
- try {
43
- if (!NOTE_ID.test(id)) throw new Error("ファイル名が N-YYYYMMDD-HHMMSS-xxxx.md ではありません");
44
- const { data, body } = parseFrontmatter(await readFile(join(this.dir(requestId), f), "utf8"));
45
- if (!body.trim()) throw new Error("本文が空です");
46
- const createdAt = typeof data.createdAt === "string" ? data.createdAt : "";
47
- if (!createdAt) throw new Error("createdAt がありません");
48
- notes.push({ id, requestId, createdAt, createdBy: typeof data.createdBy === "string" ? data.createdBy : undefined, body: body.trim() });
49
- } catch (e) {
50
- invalid.push({ file: `notes/${f}`, error: (e as Error).message });
51
- }
52
- }
53
- notes.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
54
- return { notes, invalid };
55
- }
56
- }
@@ -1,136 +0,0 @@
1
- import { readdir, readFile, mkdir, rm, stat } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import type { PreflightRun, ProposedTask, RunPulse } from "../../shared/types.ts";
4
- import { parseFrontmatter, stringifyFrontmatter } from "./frontmatter.ts";
5
- import { writeFileAtomic } from "./fsutil.ts";
6
-
7
- /**
8
- * requests/<要望ID>/preflight/<RUN-ID>/
9
- * run.json 評価結果・ログ・文脈(機械向け)
10
- * drafts/D1.md ... 細分化されたタスク案(1案 = 1ファイル。人や AI が直接編集できる)
11
- */
12
- export class PreflightStore {
13
- /** requestsDir: .p3/requests */
14
- constructor(readonly requestsDir: string) {}
15
-
16
- runDir(requestId: string, runId: string) {
17
- return join(this.requestsDir, requestId, "preflight", runId);
18
- }
19
-
20
- async save(run: PreflightRun): Promise<void> {
21
- const { drafts, ...meta } = run;
22
- await writeFileAtomic(join(this.runDir(run.requestId, run.id), "run.json"), JSON.stringify(meta, null, 2) + "\n");
23
- }
24
-
25
- async saveDrafts(requestId: string, runId: string, drafts: ProposedTask[]): Promise<void> {
26
- const dir = join(this.runDir(requestId, runId), "drafts");
27
- await rm(dir, { recursive: true, force: true });
28
- await mkdir(dir, { recursive: true });
29
- for (const d of drafts) await this.saveDraft(requestId, runId, d);
30
- }
31
-
32
- async saveDraft(requestId: string, runId: string, d: ProposedTask): Promise<void> {
33
- const { description, ...meta } = d;
34
- await writeFileAtomic(
35
- join(this.runDir(requestId, runId), "drafts", `${d.key}.md`),
36
- stringifyFrontmatter({ ...meta, include: d.include }, description),
37
- );
38
- }
39
-
40
- async loadDrafts(requestId: string, runId: string): Promise<ProposedTask[]> {
41
- const dir = join(this.runDir(requestId, runId), "drafts");
42
- const files = await readdir(dir).catch(() => [] as string[]);
43
- const drafts: ProposedTask[] = [];
44
- for (const f of files.filter((f) => f.endsWith(".md"))) {
45
- const { data, body } = parseFrontmatter(await readFile(join(dir, f), "utf8"));
46
- drafts.push({
47
- key: String(data.key ?? f.replace(/\.md$/, "")),
48
- title: String(data.title ?? ""),
49
- description: body.trim(),
50
- areas: Array.isArray(data.areas) ? data.areas.map(String) : [],
51
- dependsOn: Array.isArray(data.dependsOn) ? data.dependsOn.map(String) : [],
52
- supersedes: Array.isArray(data.supersedes) ? data.supersedes.map(String) : [],
53
- include: data.include !== false,
54
- ...("repo" in data ? { repo: data.repo === null || data.repo === "" || data.repo === "none" ? null : String(data.repo) } : {}),
55
- });
56
- }
57
- return drafts.sort((a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }));
58
- }
59
-
60
- async get(requestId: string, runId: string): Promise<PreflightRun | undefined> {
61
- try {
62
- const meta = JSON.parse(await readFile(join(this.runDir(requestId, runId), "run.json"), "utf8"));
63
- return { ...meta, drafts: await this.loadDrafts(requestId, runId) };
64
- } catch {
65
- return undefined;
66
- }
67
- }
68
-
69
- /** run の今の状態だけ(run.json の状態と日時。案・ログは返さない)。ファイルは変えない */
70
- async pulse(requestId: string, runId: string): Promise<RunPulse> {
71
- const file = join(this.runDir(requestId, runId), "run.json");
72
- const info = await stat(file).catch((e: NodeJS.ErrnoException) => e);
73
- if (info instanceof Error) {
74
- if (info.code !== "ENOENT") return { id: runId, state: "broken" };
75
- const dir = await stat(this.runDir(requestId, runId)).catch(() => undefined);
76
- return { id: runId, state: dir?.isDirectory() ? "pending" : "missing" };
77
- }
78
- try {
79
- const meta = JSON.parse(await readFile(file, "utf8")) as Partial<PreflightRun>;
80
- if (!meta || typeof meta !== "object" || typeof meta.status !== "string") return { id: runId, state: "broken" };
81
- return {
82
- id: runId,
83
- state: "ready",
84
- status: meta.status,
85
- ...(meta.startedAt ? { startedAt: meta.startedAt } : {}),
86
- ...(meta.finishedAt ? { finishedAt: meta.finishedAt } : {}),
87
- version: `${info.mtimeMs}:${info.size}`,
88
- };
89
- } catch {
90
- return { id: runId, state: "broken" };
91
- }
92
- }
93
-
94
- async list(requestId: string): Promise<PreflightRun[]> {
95
- const ids = await readdir(join(this.requestsDir, requestId, "preflight")).catch(() => [] as string[]);
96
- const runs = await Promise.all(ids.filter((i) => i.startsWith("PF-")).map((i) => this.get(requestId, i)));
97
- return newestFirst(runs.filter((r): r is PreflightRun => !!r));
98
- }
99
- }
100
-
101
- /**
102
- * run を新しい順に並べる。基本は開始時刻だが、時計は戻ることがある(WSL2 の時刻の補正など)ので、
103
- * 前回を引き継いだ run(previous)は、引き継いだ相手より必ず新しいとする。
104
- */
105
- export function newestFirst<T extends Pick<PreflightRun, "id" | "startedAt" | "previous">>(runs: T[]): T[] {
106
- const byTime = [...runs].sort((a, b) => b.startedAt.localeCompare(a.startedAt) || b.id.localeCompare(a.id));
107
- // previous の鎖の長さ(引き継いだ回数)。鎖でつながる run どうしは、長い方が新しい
108
- const ids = new Map(runs.map((r) => [r.id, r]));
109
- const depth = new Map<string, number>();
110
- const chain = (r: T, seen = new Set<string>()): number => {
111
- if (depth.has(r.id)) return depth.get(r.id)!;
112
- const prev = r.previous && !seen.has(r.id) ? ids.get(r.previous) : undefined;
113
- const d = prev ? chain(prev, seen.add(r.id)) + 1 : 0;
114
- depth.set(r.id, d);
115
- return d;
116
- };
117
- const root = (r: T): string => {
118
- let cur = r;
119
- for (const seen = new Set<string>(); cur.previous && ids.has(cur.previous) && !seen.has(cur.id); ) {
120
- seen.add(cur.id);
121
- cur = ids.get(cur.previous)!;
122
- }
123
- return cur.id;
124
- };
125
- // 時刻順の並びで各鎖が占める位置はそのままにし、その位置に鎖の run を引き継いだ順(新しい方から)で入れ直す
126
- const groups = new Map<string, T[]>();
127
- for (const r of byTime) (groups.get(root(r)) ?? groups.set(root(r), []).get(root(r))!).push(r);
128
- for (const g of groups.values()) g.sort((a, b) => chain(b) - chain(a));
129
- const next = new Map([...groups].map(([k]) => [k, 0]));
130
- return byTime.map((r) => {
131
- const k = root(r);
132
- const i = next.get(k)!;
133
- next.set(k, i + 1);
134
- return groups.get(k)![i];
135
- });
136
- }
@@ -1,101 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import YAML from "yaml";
3
- import type { RepoRef } from "../../shared/repos.ts";
4
- import type { ProjectConfig } from "../../shared/types.ts";
5
- import { writeFileAtomic } from "./fsutil.ts";
6
-
7
- /** 設定の保存(画面・p3 config)で書き換える項目。repos は p3 repo だけが項目ごとに書く(writeRepoEntry) */
8
- const ORDER: (keyof ProjectConfig)[] = ["name", "description", "milestones", "branchPattern", "preflight"];
9
- /** ファイルの中の並び */
10
- const RANK: (keyof ProjectConfig)[] = ["name", "description", "repos", "milestones", "branchPattern", "preflight"];
11
-
12
- /** project.yaml に書く形。既定値のままの項目や空の項目は省き、人が読み書きしやすく保つ */
13
- function toPlain(cfg: ProjectConfig): Partial<Record<keyof ProjectConfig, unknown>> {
14
- return {
15
- name: cfg.name,
16
- description: cfg.description || undefined,
17
- milestones: cfg.milestones.length
18
- ? cfg.milestones.map((m) => Object.fromEntries(Object.entries({ id: m.id, title: m.title, due: m.due, done: m.done || undefined }).filter(([, v]) => v !== undefined)))
19
- : undefined,
20
- branchPattern: cfg.branchPattern,
21
- preflight: cfg.preflight.instructions ? { instructions: cfg.preflight.instructions } : undefined,
22
- };
23
- }
24
-
25
- /**
26
- * project.yaml を書く。既存のファイルがあれば YAML の文書として更新し、人が書いたコメントを残す。
27
- */
28
- export async function writeProjectFile(path: string, cfg: ProjectConfig): Promise<void> {
29
- const text = await readFile(path, "utf8").catch(() => "");
30
- const doc = text.trim() ? YAML.parseDocument(text) : new YAML.Document({});
31
- const plain = toPlain(cfg);
32
- doc.delete("statuses"); // 以前は列を設定できた。今は未着手 / 作業中 / 完了で固定
33
- dropLegacy(doc);
34
- for (const key of ORDER) {
35
- const value = plain[key];
36
- if (value === undefined) doc.delete(key);
37
- else doc.set(key, doc.createNode(value));
38
- }
39
- sortKeys(doc);
40
- await writeFileAtomic(path, doc.toString({ lineWidth: 0 }));
41
- }
42
-
43
- /** 以前のプロジェクトの docs(どの保存でも消す)。今は参照先の主なフォルダ(入口)で示す */
44
- function dropLegacy(doc: YAML.Document) {
45
- doc.delete("docs");
46
- }
47
-
48
- /** 後から足した項目も決まった順に並べる(コメントは項目に付いているので一緒に動く) */
49
- function sortKeys(doc: YAML.Document) {
50
- if (!YAML.isMap(doc.contents)) return;
51
- const rank = (k: unknown) => {
52
- const i = RANK.indexOf(String(YAML.isScalar(k) ? k.value : k) as keyof ProjectConfig);
53
- return i < 0 ? RANK.length : i;
54
- };
55
- doc.contents.items.sort((x, y) => rank(x.key) - rank(y.key));
56
- }
57
-
58
- /** project.yaml の repos の1件の形(既定のままの項目は省く) */
59
- function repoPlain(r: RepoRef): Record<string, unknown> {
60
- const map = r.map.length
61
- ? Object.fromEntries(r.map.map((m) => [m.path, m.entry ? { role: m.role, entry: m.entry } : m.role]))
62
- : undefined;
63
- return Object.fromEntries(
64
- Object.entries({ role: r.role || undefined, readFirst: r.readFirst || undefined, writable: r.writable || undefined, map }).filter(
65
- ([, v]) => v !== undefined,
66
- ),
67
- );
68
- }
69
-
70
- /**
71
- * project.yaml の repos の1件だけを書く(null で消す)。ほかの参照先・項目・コメントは変えない。
72
- * repos が無ければ作る(名前をキーにした対応で書く)
73
- */
74
- export async function writeRepoEntry(path: string, name: string, entry: RepoRef | null): Promise<void> {
75
- const text = await readFile(path, "utf8").catch(() => "");
76
- const doc = text.trim() ? YAML.parseDocument(text) : new YAML.Document({});
77
- if (doc.errors.length) throw new Error(`project.yaml が壊れています: ${path}(${doc.errors[0].message.split("\n")[0]})`);
78
- const repos = doc.get("repos");
79
- if (repos !== undefined && !YAML.isMap(repos)) {
80
- throw new Error(`project.yaml の repos は「名前: 定義」の対応で書いてください(今の形では p3 repo で書き換えられません): ${path}`);
81
- }
82
- dropLegacy(doc);
83
- if (entry === null) {
84
- doc.deleteIn(["repos", name]);
85
- if (YAML.isMap(doc.get("repos")) && !(doc.get("repos") as YAML.YAMLMap).items.length) doc.delete("repos");
86
- } else {
87
- if (!YAML.isMap(doc.get("repos"))) doc.set("repos", doc.createNode({}));
88
- const node = doc.getIn(["repos", name]);
89
- const plain = repoPlain(entry);
90
- if (YAML.isMap(node)) {
91
- // 既にあれば項目ごとに書く(人が書いたコメントや、ここで扱わない項目を残す)
92
- node.delete("mapFile"); // 以前の構成の説明。今は主なフォルダの入口で示す
93
- for (const key of ["role", "readFirst", "writable", "map"]) {
94
- if (plain[key] === undefined) node.delete(key);
95
- else node.set(key, doc.createNode(plain[key]));
96
- }
97
- } else doc.setIn(["repos", name], doc.createNode(plain));
98
- }
99
- sortKeys(doc);
100
- await writeFileAtomic(path, doc.toString({ lineWidth: 0 }));
101
- }