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