@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,328 +0,0 @@
1
- import { readdir, readFile, watch } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import YAML from "yaml";
4
- import { parseRef, REQUEST_ID, TASK_ID, taskId } from "../../shared/refs.ts";
5
- import type { ProjectConfig, Request, ServerEvent, Task } from "../../shared/types.ts";
6
- import { fileLayout, folderLayout, MarkdownCollection, NotFoundError, type PreparedLoad } from "./collection.ts";
7
- import { newRequestId } from "./fsutil.ts";
8
- import { normalizeProject, normalizeRequest, normalizeTaskIn, REQUEST_KEY_ORDER, TASK_KEY_ORDER } from "./normalize.ts";
9
- import { AttachmentStore } from "./attachments.ts";
10
- import { NoteStore } from "./noteStore.ts";
11
- import { PreflightStore } from "./preflightStore.ts";
12
- import { writeProjectFile } from "./projectFile.ts";
13
- import { resolveRefs, type ResolvedRef } from "../repoRefs.ts";
14
- import { RELEASE_NOTES_DIR, ReleaseNoteStore } from "../releaseNotes/store.ts";
15
-
16
- type Listener = (e: ServerEvent) => void;
17
-
18
- /** 全件の読み直しの結果 */
19
- export interface ReloadResult {
20
- requests: number;
21
- tasks: number;
22
- /** 読めなかったファイルの数(中身は GET /api/project の errors) */
23
- errors: number;
24
- loadedAt: string;
25
- }
26
-
27
- /** 全件の読み直しができなかった(project.yaml やデータのフォルダが読めない)。メモリ上の状態は変えていない */
28
- export class ReloadError extends Error {}
29
-
30
- /**
31
- * ステータスを変えた日時を記録する(予定ではなく事実)。
32
- * 未着手以外にした → startedAt(未着手に戻したら消す)
33
- * 完了にした → doneAt(完了から戻したら消す)
34
- * 完了から戻した → 人の「済み」(checkedAt)も消す
35
- */
36
- export function stampStatus(prev: Task | undefined, next: Task): Task {
37
- if (prev && prev.status === next.status) return next;
38
- const now = next.updatedAt;
39
- const done = next.status === "done";
40
- return {
41
- ...next,
42
- startedAt: next.status === "todo" ? undefined : (prev?.startedAt ?? next.startedAt ?? now),
43
- doneAt: done ? now : undefined,
44
- checkedAt: done ? next.checkedAt : undefined,
45
- };
46
- }
47
-
48
- /**
49
- * 1リポジトリ = 1プロジェクト。データディレクトリ配下がすべての状態で、要望ごとにフォルダを分ける。
50
- *
51
- * <data>/project.yaml
52
- * <data>/requests/<要望ID>/request.md
53
- * <data>/requests/<要望ID>/tasks/T001.md
54
- * <data>/requests/<要望ID>/preflight/PF-.../{run.json, assessment.json, carryover.md, drafts/D1.md}
55
- * <data>/requests/<要望ID>/notes/N-....md Preflight へのメモ
56
- * <data>/requests/<要望ID>/attachments/A-.../{meta.json, file.*} 添付(画像・xlsx)
57
- * <data>/release-notes/<マイルストーンID>.md リリースノート(マイルストーンごとに1件。releaseNotes/store.ts)
58
- *
59
- * 共有(git / ファイル共有)も要望のフォルダ単位で行える。
60
- */
61
- export class Workspace {
62
- project!: ProjectConfig;
63
- readonly requests: MarkdownCollection<Request>;
64
- readonly preflight: PreflightStore;
65
- readonly notes: NoteStore;
66
- readonly attachments: AttachmentStore;
67
- readonly releaseNotes: ReleaseNoteStore;
68
- private taskCollections = new Map<string, MarkdownCollection<Task>>();
69
- private listeners = new Set<Listener>();
70
- private abort = new AbortController();
71
-
72
- /** localRepos: 個人設定の参照先の名前 → このマシンのパス(repoRefs.ts) */
73
- constructor(
74
- readonly dataDir: string,
75
- private localRepos: Record<string, string> = {},
76
- ) {
77
- this.requests = new MarkdownCollection<Request>({
78
- layout: folderLayout(this.requestsDir, "request.md", REQUEST_ID, () => newRequestId()),
79
- normalize: normalizeRequest,
80
- keyOrder: REQUEST_KEY_ORDER,
81
- });
82
- this.preflight = new PreflightStore(this.requestsDir);
83
- this.notes = new NoteStore(this.requestsDir);
84
- this.attachments = new AttachmentStore(this.requestsDir);
85
- this.releaseNotes = new ReleaseNoteStore(dataDir);
86
- }
87
-
88
- get requestsDir() {
89
- return join(this.dataDir, "requests");
90
- }
91
-
92
- /** このマシンのパスを変えた(個人設定に書いた後に呼ぶ) */
93
- setLocalRepo(name: string, path: string | null) {
94
- const next = { ...this.localRepos };
95
- if (path === null) delete next[name];
96
- else next[name] = path;
97
- this.localRepos = next;
98
- this.emit({ type: "changed", kind: "project" });
99
- }
100
-
101
- /** project.yaml を読み直して知らせる(参照先を書いた後) */
102
- async refreshProject() {
103
- await this.loadProject();
104
- this.emit({ type: "changed", kind: "project" });
105
- }
106
-
107
- /** Preflight が読む参照先(共有の定義と、このマシンのパス)。呼ぶたびにパスがあるかを確かめる */
108
- refs(): ResolvedRef[] {
109
- return resolveRefs(this.project, { localRepos: this.localRepos });
110
- }
111
-
112
- async load(): Promise<void> {
113
- await this.loadAll(false);
114
- }
115
-
116
- /**
117
- * データのフォルダを全部読み直す(画面の「再読み込み」)。ファイル監視に頼らず、外での変更を取り込む。
118
- * - project.yaml・要望・全タスクを読み、読み終えてから入れ替える(途中の状態は見せない)
119
- * - 同時には走らせない。読み込み中に呼ばれたら、今のものが終わってからもう1回だけ読む(待っている呼び出しはまとめる)
120
- * - project.yaml やデータのフォルダが読めなければ ReloadError(何も変えない)。個々の Markdown が壊れていても続け、errors() に出す
121
- * - ファイルは書かない。Preflight の履歴・メモ・リリースノートは問い合わせのたびにディスクを読むので、ここでは扱わない
122
- * 終えたら変更通知(kind: "reload")を出す。関係・検索の索引はこれを受けて作り直す
123
- */
124
- reloadAll(): Promise<ReloadResult> {
125
- if (this.reloadNext) return this.reloadNext;
126
- if (!this.reloadRun) return this.startReload();
127
- this.reloadNext = this.reloadRun
128
- .catch(() => undefined)
129
- .then(() => {
130
- this.reloadNext = undefined;
131
- return this.startReload();
132
- });
133
- return this.reloadNext;
134
- }
135
-
136
- private reloadRun?: Promise<ReloadResult>;
137
- private reloadNext?: Promise<ReloadResult>;
138
-
139
- private startReload(): Promise<ReloadResult> {
140
- const run = (async () => {
141
- await this.loadAll(true);
142
- this.emit({ type: "changed", kind: "reload" });
143
- return {
144
- requests: this.requests.list().length,
145
- tasks: this.allTasks().length,
146
- errors: Object.keys(this.errors()).length,
147
- loadedAt: new Date().toISOString(),
148
- };
149
- })().finally(() => {
150
- if (this.reloadRun === run) this.reloadRun = undefined;
151
- });
152
- this.reloadRun = run;
153
- return run;
154
- }
155
-
156
- /** strict: project.yaml とデータのフォルダが読めなければ失敗にする(起動時は無くても空として続ける) */
157
- private async loadAll(strict: boolean): Promise<void> {
158
- const project = strict ? await this.readProjectStrict() : await this.readProject();
159
- if (strict) {
160
- await readdir(this.requestsDir).catch((e: NodeJS.ErrnoException) => {
161
- if (e.code !== "ENOENT") throw new ReloadError(`データのフォルダを読めません: ${this.requestsDir}: ${e.message}`);
162
- });
163
- }
164
- const loads: PreparedLoad[] = [];
165
- try {
166
- const requests = await this.requests.prepareLoad();
167
- loads.push(requests);
168
- const tasks = await Promise.allSettled(requests.ids.map((id) => this.tasksOf(id).prepareLoad()));
169
- for (const t of tasks) if (t.status === "fulfilled") loads.push(t.value);
170
- const failed = tasks.find((t) => t.status === "rejected");
171
- if (failed) throw failed.reason;
172
- } catch (e) {
173
- for (const l of loads) l.abort();
174
- throw e;
175
- }
176
- // 公開: ここから同期でまとめて入れ替える。タスクのコレクションは作り直さない(処理中の操作が持っている参照を生かす)
177
- this.project = project;
178
- for (const l of loads) l.commit();
179
- for (const rid of this.taskCollections.keys()) if (!this.requests.get(rid)) this.taskCollections.delete(rid);
180
- }
181
-
182
- /** 要望のタスク(要望の中で T001, T002, ... と連番) */
183
- tasksOf(requestId: string): MarkdownCollection<Task> {
184
- let col = this.taskCollections.get(requestId);
185
- if (!col) {
186
- col = new MarkdownCollection<Task>({
187
- layout: fileLayout(join(this.requestsDir, requestId, "tasks"), TASK_ID, taskId),
188
- normalize: normalizeTaskIn(requestId),
189
- keyOrder: TASK_KEY_ORDER,
190
- derived: ["request", "ref"],
191
- beforeWrite: (prev, next) => stampStatus(prev, next),
192
- });
193
- this.taskCollections.set(requestId, col);
194
- }
195
- return col;
196
- }
197
-
198
- /** 全要望のタスク */
199
- allTasks(): Task[] {
200
- return this.requests.list().flatMap((r) => this.tasksOf(r.id).list());
201
- }
202
-
203
- /** 絶対参照(<要望ID>/T003)でタスクを引く */
204
- task(ref: string): Task | undefined {
205
- const r = parseRef(ref);
206
- return r?.task ? this.taskCollections.get(r.request)?.get(r.task) : undefined;
207
- }
208
-
209
- requireTask(ref: string): Task {
210
- const t = this.task(ref);
211
- if (!t) throw new NotFoundError(ref);
212
- return t;
213
- }
214
-
215
- /** 参照先が存在するか(要望かタスク) */
216
- exists(ref: string): boolean {
217
- const r = parseRef(ref);
218
- if (!r) return false;
219
- return r.task ? !!this.task(ref) : !!this.requests.get(r.request);
220
- }
221
-
222
- /** 読めなかったファイル(データディレクトリからの相対パス → エラー) */
223
- errors(): Record<string, string> {
224
- const out: Record<string, string> = {};
225
- for (const [id, e] of this.requests.errors) out[`requests/${id}/request.md`] = e;
226
- for (const [rid, col] of this.taskCollections) for (const [id, e] of col.errors) out[`requests/${rid}/tasks/${id}.md`] = e;
227
- return out;
228
- }
229
-
230
- /** プロジェクト設定を更新して project.yaml に書く(コメントは残す) */
231
- async saveProject(patch: Partial<ProjectConfig>): Promise<ProjectConfig> {
232
- await this.loadProject();
233
- const next = { ...this.project, ...patch };
234
- await writeProjectFile(join(this.dataDir, "project.yaml"), next);
235
- await this.loadProject();
236
- this.emit({ type: "changed", kind: "project" });
237
- return this.project;
238
- }
239
-
240
- private async loadProject() {
241
- this.project = await this.readProject();
242
- }
243
-
244
- private async readProject(): Promise<ProjectConfig> {
245
- const text = await readFile(join(this.dataDir, "project.yaml"), "utf8").catch(() => "");
246
- return normalizeProject((YAML.parse(text) ?? {}) as Record<string, unknown>);
247
- }
248
-
249
- private async readProjectStrict(): Promise<ProjectConfig> {
250
- const path = join(this.dataDir, "project.yaml");
251
- try {
252
- return normalizeProject((YAML.parse(await readFile(path, "utf8")) ?? {}) as Record<string, unknown>);
253
- } catch (e) {
254
- throw new ReloadError(`project.yaml を読めません(${path}): ${(e as Error).message}`);
255
- }
256
- }
257
-
258
- on(l: Listener): () => void {
259
- this.listeners.add(l);
260
- return () => this.listeners.delete(l);
261
- }
262
-
263
- emit(e: ServerEvent) {
264
- for (const l of this.listeners) l(e);
265
- }
266
-
267
- /**
268
- * データディレクトリを監視し、外部からのファイル編集(エディタ・AI・Codex・git pull)を取り込む(補助)。
269
- * NFS などでは通知が届かず、Node の再帰的な監視は置き換えて保存したファイルの2回目以降の変更を通知しないことがある。
270
- * 正しさはこれに頼らず、画面の「再読み込み」(reloadAll)で保証する。
271
- */
272
- async watch(): Promise<void> {
273
- const pending = new Map<string, NodeJS.Timeout>();
274
- try {
275
- for await (const ev of watch(this.dataDir, { recursive: true, signal: this.abort.signal })) {
276
- const f = ev.filename;
277
- if (!f || f.endsWith(".tmp") || f.includes(".archive")) continue;
278
- clearTimeout(pending.get(f));
279
- pending.set(
280
- f,
281
- setTimeout(() => {
282
- pending.delete(f);
283
- void this.onFileChanged(f);
284
- }, 80),
285
- );
286
- }
287
- } catch (e) {
288
- if ((e as Error).name !== "AbortError") console.error("[watch]", e);
289
- }
290
- }
291
-
292
- private async onFileChanged(rel: string) {
293
- const [top, rid, kind, file] = rel.split(/[\\/]/);
294
- if (top === RELEASE_NOTES_DIR) {
295
- // リリースノートの作成・更新・削除(ロックのファイル .<ID>.lock は除く)
296
- if (rid?.endsWith(".md") && !rid.startsWith(".") && kind === undefined) this.emit({ type: "changed", kind: "release-note", milestone: rid.slice(0, -3) });
297
- return;
298
- }
299
- if (top === "project.yaml") {
300
- await this.loadProject();
301
- this.emit({ type: "changed", kind: "project" });
302
- return;
303
- }
304
- if (top !== "requests" || !rid || !REQUEST_ID.test(rid)) return;
305
- if (kind === undefined || kind === "request.md") {
306
- // 要望の作成・削除(git pull でフォルダごと増減することもある)
307
- const known = !!this.requests.get(rid);
308
- await this.requests.reload(rid);
309
- if (!known && this.requests.get(rid)) await this.tasksOf(rid).load();
310
- this.emit({ type: "changed", kind: "request", request: rid });
311
- } else if (kind === "tasks" && file?.endsWith(".md")) {
312
- const id = file.slice(0, -3);
313
- if (!TASK_ID.test(id)) return;
314
- await this.tasksOf(rid).reload(id);
315
- this.emit({ type: "changed", kind: "task", request: rid, ref: `${rid}/${id}` });
316
- } else if (kind === "preflight") {
317
- this.emit({ type: "changed", kind: "preflight", request: rid });
318
- } else if (kind === "notes") {
319
- this.emit({ type: "changed", kind: "note", request: rid });
320
- } else if (kind === "attachments") {
321
- this.emit({ type: "changed", kind: "attachment", request: rid });
322
- }
323
- }
324
-
325
- close() {
326
- this.abort.abort();
327
- }
328
- }
@@ -1,74 +0,0 @@
1
- import { absRef, parseRef } from "../shared/refs.ts";
2
- import type { PreflightRun, SupersedeCandidate, SupersededMark } from "../shared/types.ts";
3
- import type { Workspace } from "./store/workspace.ts";
4
-
5
- /**
6
- * 置き換え(supersedes)の判定。どこで使っても同じ規則にするため、ここにまとめる。
7
- *
8
- * 印(一覧・詳細・ボード・着手の警告): 保存済みのタスクの relations にある supersedes だけを見る。
9
- */
10
- export function supersededMarks(ws: Workspace): Map<string, SupersededMark[]> {
11
- const marks = new Map<string, SupersededMark[]>();
12
- const add = (from: string, base: string, target: string, note?: string) => {
13
- const ref = absRef(target, base);
14
- // 今あるタスクだけ(アーカイブしたタスクには印を付けない)
15
- if (!ref || !parseRef(ref)?.task || ref === from || !ws.task(ref)) return;
16
- const list = marks.get(ref) ?? [];
17
- if (!list.some((m) => m.from === from)) list.push({ from, note });
18
- marks.set(ref, list);
19
- };
20
- for (const r of ws.requests.list()) {
21
- for (const t of ws.tasksOf(r.id).list()) {
22
- for (const rel of t.relations) if (rel.type === "supersedes") add(t.ref, r.id, rel.target, rel.note);
23
- }
24
- }
25
- return marks;
26
- }
27
-
28
- /**
29
- * タスク化で知らせる置き換えられるタスク: 採用したタスク案の supersedes のうち、同じ要望にある未完了(todo / doing)の
30
- * タスク。不採用の案だけにあるもの・完了したタスク・無いタスク・別の要望は含めない。
31
- */
32
- export function supersedeCandidates(ws: Workspace, run: PreflightRun): SupersedeCandidate[] {
33
- const rid = run.requestId;
34
- const found = new Map<string, SupersedeCandidate>();
35
- const add = (target: string, reason: SupersedeCandidate["reasons"][number]) => {
36
- const ref = absRef(target, rid);
37
- const p = ref ? parseRef(ref) : undefined;
38
- if (!ref || !p?.task || p.request !== rid) return;
39
- const t = ws.task(ref);
40
- if (!t || t.status === "done") return;
41
- const c = found.get(ref) ?? { id: t.id, ref, title: t.title, status: t.status, rev: t.rev, reasons: [] };
42
- c.reasons.push(reason);
43
- found.set(ref, c);
44
- };
45
- for (const d of run.drafts) if (d.include) for (const target of d.supersedes) add(target, { draft: d.key });
46
- return [...found.values()].sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true }));
47
- }
48
-
49
- /** 操作は続けたうえで知らせる注意(CLI は stderr と --json の warnings、API は warnings) */
50
- export interface Warning {
51
- code: "superseded";
52
- /** 対象のタスク(<要望ID>/T001) */
53
- target: string;
54
- /** 置き換えた側 */
55
- from: string[];
56
- message: string;
57
- }
58
-
59
- /**
60
- * 置き換えられたタスクに着手したときの警告。状態が作業中に変わったときだけ出す(作業中のままの再指定では出さない)。
61
- * 着手は止めない(置き換えが誤りのこともあるので、判断は人と AI に任せる)。
62
- */
63
- export function startWarnings(ws: Workspace, ref: string, prevStatus: string, nextStatus: string | undefined): Warning[] {
64
- if (nextStatus !== "doing" || prevStatus === "doing") return [];
65
- return supersededWarnings(supersededMarks(ws).get(ref) ?? [], ref);
66
- }
67
-
68
- /** 置き換えの印から作る注意。着手のとき(startWarnings)と詳細を読むとき(show の warnings)で同じ形にする */
69
- export function supersededWarnings(marks: SupersededMark[], ref: string): Warning[] {
70
- if (!marks.length) return [];
71
- const from = marks.map((m) => m.from);
72
- const by = from.join(", ");
73
- return [{ code: "superseded", target: ref, from, message: `${ref} は ${by} で置き換えられています。置き換え先を確かめてから進めてください` }];
74
- }
@@ -1,205 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import { homedir } from "node:os";
3
- import { join, resolve } from "node:path";
4
- import YAML from "yaml";
5
- import { isTheme, type Theme } from "../shared/types.ts";
6
- import { withFileLock, writeFileAtomic } from "./store/fsutil.ts";
7
-
8
- /**
9
- * 個人設定(このマシン・この人だけのもの。共有しない)。
10
- *
11
- * ~/.config/infodb-p3/config.yaml
12
- *
13
- * projects:
14
- * myapp: # プロジェクト名 → データを置くフォルダ(場所は自由)
15
- * dir: /home/me/p3-data/myapp
16
- * repos: # 手元のリポジトリの場所(マシンごとに違うのでプロジェクトのデータには書かない)
17
- * main: /home/me/src/myapp
18
- * other:
19
- * dir: /home/me/p3-data/other
20
- * ui:
21
- * theme: system # 画面の表示(system / light / dark)
22
- * codex: { ... } # マシンごとの設定(Codex・Preflight・serve。→ machineSettings.ts)
23
- * preflight: { ... }
24
- * serve: { ... }
25
- *
26
- * 操作するプロジェクトは、ここに登録した内容と「今いる場所」から決める(環境変数では切り替えない)。
27
- * ChatGPT の接続(トークン)はここに置かない(同じフォルダの chatgpt.json)。
28
- */
29
- export interface UserProject {
30
- /** データを置くフォルダ(project.yaml と requests/ がある場所) */
31
- dir: string;
32
- /** 手元のリポジトリの場所(リポジトリの名前 → 絶対パス)。今は main の1つ */
33
- repos: Record<string, string>;
34
- }
35
-
36
- export type { Theme };
37
-
38
- export interface UserConfig {
39
- projects: Record<string, UserProject>;
40
- ui: { theme: Theme };
41
- /** マシンごとの設定。書かれたままの値(読むときに machineSettings.ts で確かめる)。保存では書き換えない */
42
- settings: Partial<Record<SettingsSection, Record<string, unknown>>>;
43
- }
44
-
45
- export const SETTINGS_SECTIONS = ["codex", "preflight", "serve"] as const;
46
- export type SettingsSection = (typeof SETTINGS_SECTIONS)[number];
47
-
48
- export const PROJECT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
49
-
50
- /** 個人設定のファイル。XDG_CONFIG_HOME があればそれに従う(設定ファイルの置き場所を決めるだけで、プロジェクトの切り替えには使わない) */
51
- export function userConfigPath(): string {
52
- return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "infodb-p3", "config.yaml");
53
- }
54
-
55
- /** Preflight の記録(共有)に残す文から、個人設定のファイルのパス(このマシンのもの)を外す */
56
- export function hideConfigPath(e: unknown): string {
57
- const text = (e as Error)?.message ?? String(e);
58
- const path = (e as { configPath?: string })?.configPath ?? userConfigPath();
59
- return text.split(path).join("個人設定(config.yaml)");
60
- }
61
-
62
- /** 個人設定を読めない・壊れている。ファイルは変えていない */
63
- export class UserConfigError extends Error {}
64
-
65
- /** ファイルが無ければ空。権限や I/O の失敗は、無いのと区別してエラーにする */
66
- async function readText(path: string): Promise<string> {
67
- try {
68
- return await readFile(path, "utf8");
69
- } catch (e) {
70
- const code = (e as NodeJS.ErrnoException).code;
71
- if (code === "ENOENT") return "";
72
- throw new UserConfigError(`個人設定を読めません: ${path}(${code ?? (e as Error).message})。ファイルの権限と種類を確かめてください`);
73
- }
74
- }
75
-
76
- function parse(text: string, path: string): YAML.Document {
77
- const doc = text.trim() ? YAML.parseDocument(text) : new YAML.Document({});
78
- if (doc.errors.length) {
79
- const e = doc.errors[0];
80
- const at = e.linePos?.[0] ? `${e.linePos[0].line} 行目: ` : "";
81
- throw new UserConfigError(`個人設定の YAML が壊れています: ${path}(${at}${e.message.split("\n")[0]})。直してからやり直してください(ファイルは変えていません)`);
82
- }
83
- if (!text.trim()) doc.commentBefore = " infodb p3 の個人設定(このマシン・この人だけ。共有しない)";
84
- return doc;
85
- }
86
-
87
- export async function loadUserConfig(path = userConfigPath()): Promise<UserConfig> {
88
- return normalizeUserConfig(asRecord(parse(await readText(path), path).toJS()));
89
- }
90
-
91
- /**
92
- * マシンごとの設定(codex / preflight / serve)のために、個人設定を厳密に読む(Preflight を始めるたび・エンジンの状態を見るたび)。
93
- * ファイルが無ければ空(既定値)。読めない・壊れた YAML・ファイル全体や項目の形が違うときは、空にせずエラーにする。
94
- */
95
- export async function loadUserSettings(path = userConfigPath()): Promise<Pick<UserConfig, "settings">> {
96
- const js = parse(await readText(path), path).toJS() as unknown;
97
- if (js !== null && js !== undefined && (typeof js !== "object" || Array.isArray(js))) {
98
- throw new UserConfigError(`個人設定の形が違います: ${path}(「項目: 値」の対応で書いてください)`);
99
- }
100
- const d = (js ?? {}) as Record<string, unknown>;
101
- const settings: UserConfig["settings"] = {};
102
- for (const s of SETTINGS_SECTIONS) {
103
- const v = d[s];
104
- if (v === undefined || v === null) continue;
105
- if (typeof v !== "object" || Array.isArray(v)) throw new UserConfigError(`個人設定の ${s} の形が違います: ${path}(「項目: 値」の対応で書いてください)`);
106
- settings[s] = v as Record<string, unknown>;
107
- }
108
- return { settings };
109
- }
110
-
111
- /** 一覧に入れられなかった登録(名前の形・dir が無いなど)。normalizeUserConfig は黙って外すので、プロジェクトを跨ぐ serve の一覧で知らせる */
112
- export interface InvalidProjectEntry {
113
- name: string;
114
- reason: string;
115
- }
116
-
117
- /**
118
- * プロジェクトを跨ぐ serve のために、個人設定の projects を診断つきで読む。読めない・壊れた YAML は UserConfigError
119
- * (登録0件とは区別する)。projects の形が違う・名前や dir が不正な登録は invalid に理由を付けて返し、ほかの登録は使えるようにする
120
- */
121
- export async function inspectUserProjects(path = userConfigPath()): Promise<{ projects: Record<string, UserProject>; invalid: InvalidProjectEntry[] }> {
122
- const d = asRecord(parse(await readText(path), path).toJS());
123
- const invalid: InvalidProjectEntry[] = [];
124
- if (d.projects !== undefined && d.projects !== null && (typeof d.projects !== "object" || Array.isArray(d.projects))) {
125
- throw new UserConfigError(`個人設定の projects の形が違います: ${path}(「名前: { dir: フォルダ }」の対応で書いてください)`);
126
- }
127
- for (const [name, v] of Object.entries(asRecord(d.projects))) {
128
- const p = typeof v === "string" ? { dir: v } : v;
129
- if (!PROJECT_NAME.test(name)) invalid.push({ name, reason: "名前に使えない文字があります(英数字で始まり、英数字と . _ -)" });
130
- else if (!p || typeof p !== "object" || Array.isArray(p)) invalid.push({ name, reason: "登録の形が違います(dir: <データのフォルダ>)" });
131
- else if (typeof (p as Record<string, unknown>).dir !== "string" || !(p as Record<string, unknown>).dir) invalid.push({ name, reason: "dir(データのフォルダ)がありません" });
132
- }
133
- return { projects: normalizeUserConfig(d).projects, invalid };
134
- }
135
-
136
- const asRecord = (v: unknown): Record<string, unknown> => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
137
-
138
- /**
139
- * 個人設定を書き換える。ロックの中で最新のファイルを読み、change で対象の項目だけを変えて、まとめて書く。
140
- * 別のプロセス(CLI・serve)が同時に別の項目を変えても、互いに消し合わない。コメントと、ここで扱わない項目は残す。
141
- * 壊れた YAML や読めないファイルは、書かずにエラーにする。change は今の内容(cfg)を見て、変えてよいか確かめてもよい。
142
- */
143
- export async function updateUserConfig<T>(change: (doc: YAML.Document, cfg: UserConfig) => T | Promise<T>, path = userConfigPath()): Promise<T> {
144
- return withFileLock(
145
- `${path}.lock`,
146
- async () => {
147
- const doc = parse(await readText(path), path);
148
- const result = await change(doc, normalizeUserConfig(asRecord(doc.toJS())));
149
- await writeFileAtomic(path, doc.toString({ lineWidth: 0 }));
150
- return result;
151
- },
152
- { busyMessage: `個人設定の更新を待ちきれませんでした(別のプロセスが更新中です。${path}.lock が残っていれば消してください)` },
153
- );
154
- }
155
-
156
- /** プロジェクト1つの登録を書く(null で外す)。ほかのプロジェクトと項目は変えない */
157
- export function setProjectNode(doc: YAML.Document, name: string, p: UserProject | null) {
158
- if (p === null) {
159
- doc.deleteIn(["projects", name]);
160
- return;
161
- }
162
- if (!doc.has("projects") || !YAML.isMap(doc.get("projects"))) doc.set("projects", doc.createNode({}));
163
- doc.setIn(["projects", name], doc.createNode(Object.keys(p.repos).length ? { dir: p.dir, repos: p.repos } : { dir: p.dir }));
164
- }
165
-
166
- /** 画面のテーマを書く。ui のほかの項目は残す */
167
- export function setThemeNode(doc: YAML.Document, theme: Theme) {
168
- if (!doc.has("ui") || !YAML.isMap(doc.get("ui"))) doc.set("ui", doc.createNode({}));
169
- doc.setIn(["ui", "theme"], theme);
170
- }
171
-
172
- export function normalizeUserConfig(d: Record<string, unknown>): UserConfig {
173
- const projects: Record<string, UserProject> = {};
174
- const raw = d.projects && typeof d.projects === "object" ? (d.projects as Record<string, unknown>) : {};
175
- for (const [name, v] of Object.entries(raw)) {
176
- const p = (typeof v === "string" ? { dir: v } : (v ?? {})) as Record<string, unknown>;
177
- if (!PROJECT_NAME.test(name) || typeof p.dir !== "string" || !p.dir) continue;
178
- const repos = p.repos && typeof p.repos === "object" ? (p.repos as Record<string, unknown>) : {};
179
- projects[name] = {
180
- dir: resolve(p.dir),
181
- repos: Object.fromEntries(Object.entries(repos).filter(([, r]) => typeof r === "string" && r).map(([k, r]) => [k, resolve(r as string)])),
182
- };
183
- }
184
- // 書かれたテーマが読めないときは system として扱う(画面は起動できるように。新しく書くときは CLI・API が確かめる)
185
- const ui = asRecord(d.ui);
186
- const theme: Theme = isTheme(ui.theme) ? ui.theme : "system";
187
- const settings: UserConfig["settings"] = {};
188
- for (const s of SETTINGS_SECTIONS) {
189
- const v = d[s];
190
- if (v && typeof v === "object" && !Array.isArray(v)) settings[s] = v as Record<string, unknown>;
191
- }
192
- return { projects, ui: { theme }, settings };
193
- }
194
-
195
- /**
196
- * 個人設定の projects と ui.theme を、渡した内容に置き換える(テストや一括の書き換え用)。
197
- * いつもの操作は updateUserConfig で対象の項目だけを変える(同時に別の項目を変えても消し合わないように)
198
- */
199
- export async function saveUserConfig(cfg: UserConfig, path = userConfigPath()): Promise<void> {
200
- await updateUserConfig((doc, now) => {
201
- for (const name of Object.keys(now.projects)) if (!cfg.projects[name]) setProjectNode(doc, name, null);
202
- for (const [name, p] of Object.entries(cfg.projects)) setProjectNode(doc, name, p);
203
- if (cfg.ui.theme !== "system" || doc.has("ui")) setThemeNode(doc, cfg.ui.theme);
204
- }, path);
205
- }