@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
@@ -0,0 +1,152 @@
1
+ import { relative } from "node:path";
2
+ import { listTasks, resolve, resolveRef } from "../core/ops.js";
3
+ import { archiveTask, createTask, updateTask } from "../core/requestOps.js";
4
+ import { supersededMarks } from "../core/supersede.js";
5
+ import { table } from "./format.js";
6
+ import { taskRepo } from "../shared/workTarget.js";
7
+ import { addRepoOutputs, parseRepoOutput, repoArg } from "../core/workTargets.js";
8
+ import { briefTask, formatBriefTask, taskExtras } from "./showView.js";
9
+ import { UsageError } from "./project.js";
10
+ import { parseTaskAssignments, checkStatus, readBody } from "./args.js";
11
+ import { dependentsOf, formatEntity, ambiguous, replacedBy, reopenedNote, warn, deps, workHint } from "./output.js";
12
+ import { requestCommand } from "./requestCommands.js";
13
+ /** タスクのコマンド(ls / show / find / impact / new / set / move / check / link / unlink / archive)。変更は server/requestOps.ts を通す。扱わないコマンドは undefined */
14
+ const RECORD_REQUIRED = "AI が完了にするときは --record で変更の記録を残してください(何を変えたか・なぜ・入れた決まり・やめたもの。Markdown。- で標準入力)\n" +
15
+ " 例: p3 move T003 done --output <成果物(変えたファイルや説明。URL は後から足せます)> --record - < record.md";
16
+ export async function taskCommand(cmd, env) {
17
+ const { ctx, out, args, o, actor, current, expectedRev, requestArg, taskArg, split, cwd } = env;
18
+ switch (cmd) {
19
+ // --- タスク -------------------------------------------------------------
20
+ case "ls":
21
+ case "list": {
22
+ if (o.repo !== undefined && o.repo !== "none" && !ctx.ws.project.repos.some((r) => r.name === o.repo)) {
23
+ throw new UsageError(`参照先「${o.repo}」は登録されていません(p3 repo ls)`);
24
+ }
25
+ const filter = { status: o.status?.split(","), area: o.area?.[0], q: o.q, repo: o.repo };
26
+ const tasks = listTasks(ctx, { ...filter, request: o.all ? undefined : requestArg(undefined) });
27
+ const marks = supersededMarks(ctx.ws);
28
+ const items = tasks.map((t) => (marks.has(t.ref) ? { ...t, superseded: marks.get(t.ref) } : t));
29
+ // 共有の参照先があるときは作業先の列を出す
30
+ const multi = ctx.ws.project.repos.length > 0;
31
+ return out.result(items, () => table(tasks.map((t) => [
32
+ o.all ? t.ref : t.id,
33
+ t.status,
34
+ ...(multi ? [taskRepo(t) ?? "(なし)"] : []),
35
+ t.title,
36
+ [deps(t), replacedBy(t, marks)].filter(Boolean).join(" "),
37
+ ])) || "タスクはありません");
38
+ }
39
+ case "show": {
40
+ const query = args.join(" ");
41
+ const ref = resolveRef(ctx, query, current) ?? resolve(ctx, query, current).match;
42
+ if (!ref)
43
+ return ambiguous(out, ctx, query, current);
44
+ if (!ref.includes("/"))
45
+ return requestCommand(ctx, out, ["show", ref], o, actor, requestArg, expectedRev);
46
+ const item = ctx.ws.requireTask(ref);
47
+ const marks = supersededMarks(ctx.ws);
48
+ if (o.brief) {
49
+ const view = briefTask(ctx, item, marks);
50
+ return out.result(view, () => formatBriefTask(view));
51
+ }
52
+ const file = relative(cwd, split(ref).col.path(item.id));
53
+ const { superseded, dependencies, warnings } = taskExtras(ctx, item, marks);
54
+ const dependents = dependentsOf(ctx, item).map((t) => ({ ref: t.ref, title: t.title, status: t.status }));
55
+ return out.result({ item, file, superseded, dependencies, dependents, warnings }, () => [superseded.length ? `※ 置き換えられています: ${superseded.map((m) => `${m.from}${m.note ? `(${m.note})` : ""}`).join(" / ")}\n` : "", formatEntity(ctx, item, file)].join(""));
56
+ }
57
+ case "find":
58
+ case "resolve": {
59
+ const r = resolve(ctx, args.join(" "), current);
60
+ return out.result(r, () => table(r.candidates.map((c) => [c.ref, c.score.toFixed(2), c.title, c.reasons.join(" / ")])) || "見つかりません");
61
+ }
62
+ case "new":
63
+ case "add": {
64
+ // 互換: new task <タイトル> / new request <タイトル>
65
+ if (args[0] === "request" || args[0] === "req")
66
+ return requestCommand(ctx, out, ["new", ...args.slice(1)], o, actor, requestArg, expectedRev);
67
+ const title = (args[0] === "task" ? args.slice(1) : args).join(" ").trim();
68
+ if (!title)
69
+ throw new UsageError("タイトルを指定してください");
70
+ const rid = requestArg(undefined);
71
+ const status = o.status ?? "todo";
72
+ checkStatus(status);
73
+ // 作業先(--repo <名前>|none)。作業先にできるものだけ。書く前に確かめる
74
+ const repo = repoArg(o.repo);
75
+ const repoOutputs = (o["repo-output"] ?? []).map((x) => parseRepoOutput(ctx.ws, x));
76
+ const r = await createTask(ctx, rid, {
77
+ title,
78
+ status,
79
+ ...(repo !== undefined ? { repo } : {}),
80
+ labels: o.label ?? [],
81
+ areas: o.area ?? [],
82
+ outputs: o.output ?? [],
83
+ ...(repoOutputs.length ? { repoOutputs: addRepoOutputs([], repoOutputs) } : {}),
84
+ body: readBody(o.body),
85
+ }, actor);
86
+ const t = r.task;
87
+ warn(r.warnings);
88
+ const reopened = reopenedNote(r.reopened, r.reopenedAncestors);
89
+ return out.result({ ...t, ...(reopened ? { reopened } : {}), ...(r.reopenedAncestors ? { reopenedAncestors: r.reopenedAncestors } : {}), ...(r.warnings.length ? { warnings: r.warnings } : {}) }, () => [`作成: ${t.ref} ${t.title}`, workHint(ctx, t)].filter(Boolean).join("\n"));
90
+ }
91
+ case "set": {
92
+ const ref = taskArg(args[0]);
93
+ const patch = parseTaskAssignments(args.slice(1));
94
+ if (o.body !== undefined)
95
+ patch.body = readBody(o.body);
96
+ if (o.record !== undefined)
97
+ patch.record = readBody(o.record).trim() || undefined;
98
+ const { col, tid } = split(ref);
99
+ if (patch.status === "done" && actor.startsWith("ai:") && !patch.record && !col.require(tid).record)
100
+ throw new UsageError(RECORD_REQUIRED);
101
+ if (o["repo-output"]?.length) {
102
+ const add = o["repo-output"].map((x) => parseRepoOutput(ctx.ws, x));
103
+ patch.repoOutputs = addRepoOutputs(patch.repoOutputs ?? col.require(tid).repoOutputs ?? [], add);
104
+ }
105
+ if (!Object.keys(patch).length)
106
+ throw new UsageError("キー=値 を指定してください");
107
+ const r = await updateTask(ctx, ref.split("/")[0], tid, patch, { expectedRev, actor });
108
+ const { task: next, warnings } = r;
109
+ warn(warnings);
110
+ const reopened = reopenedNote(r.reopened, r.reopenedAncestors);
111
+ return out.result({ ...next, ...(warnings.length ? { warnings } : {}), ...(reopened ? { reopened } : {}), ...(r.reopenedAncestors ? { reopenedAncestors: r.reopenedAncestors } : {}) }, () => [`更新: ${next.ref} (rev ${next.rev}) ${Object.keys(patch).join(", ")}`, "repo" in patch ? workHint(ctx, next) : ""].filter(Boolean).join("\n"));
112
+ }
113
+ case "move": {
114
+ const ref = taskArg(args[0]);
115
+ const status = args[1];
116
+ if (!status)
117
+ throw new UsageError("移動先のステータスを指定してください");
118
+ checkStatus(status);
119
+ const { col, tid } = split(ref);
120
+ const cur = col.require(tid);
121
+ const patch = { status };
122
+ if (o.record !== undefined)
123
+ patch.record = readBody(o.record).trim() || undefined;
124
+ // AI が完了にするときは変更の記録を残す(後の Preflight・タスク解析・リリースノートが読む)
125
+ if (status === "done" && actor.startsWith("ai:") && !patch.record && !cur.record)
126
+ throw new UsageError(RECORD_REQUIRED);
127
+ if (o.output?.length)
128
+ patch.outputs = [...new Set([...cur.outputs, ...o.output])];
129
+ // リポジトリごとの成果物(最後のタスクに、関係するリポジトリの PR を全部残せる)
130
+ if (o["repo-output"]?.length)
131
+ patch.repoOutputs = addRepoOutputs(cur.repoOutputs ?? [], o["repo-output"].map((x) => parseRepoOutput(ctx.ws, x)));
132
+ const r = await updateTask(ctx, cur.request, tid, patch, { expectedRev, actor });
133
+ const { task: next, warnings } = r;
134
+ warn(warnings);
135
+ const reopened = reopenedNote(r.reopened, r.reopenedAncestors);
136
+ return out.result({ ...next, ...(warnings.length ? { warnings } : {}), ...(reopened ? { reopened } : {}), ...(r.reopenedAncestors ? { reopenedAncestors: r.reopenedAncestors } : {}) }, () => `${next.ref} → ${status}${[...(o.output ?? []), ...(o["repo-output"] ?? [])].length ? ` (${[...(o.output ?? []), ...(o["repo-output"] ?? [])].join(", ")})` : ""}`);
137
+ }
138
+ case "check": {
139
+ const ref = taskArg(args[0]);
140
+ const { tid } = split(ref);
141
+ const { task: next } = await updateTask(ctx, ref.split("/")[0], tid, { checked: !o.off }, { expectedRev, actor });
142
+ return out.result(next, () => `${next.ref} ${o.off ? "の済みを外しました" : "を済みにしました"}`);
143
+ }
144
+ case "archive": {
145
+ const ref = taskArg(args[0]);
146
+ const { tid } = split(ref);
147
+ await archiveTask(ctx, ref.split("/")[0], tid);
148
+ return out.result({ archived: ref }, () => `アーカイブ: ${ref}`);
149
+ }
150
+ }
151
+ return undefined;
152
+ }
@@ -0,0 +1,64 @@
1
+ import { THEMES } from "../shared/types.js";
2
+ import { describeSettings, parseSettingChange, SETTING_KEY_LIST, SettingsInputError, writeMachineSettings } from "../core/machineSettingsEdit.js";
3
+ import { loadUserConfig, UserConfigError, userConfigPath } from "../core/userConfig.js";
4
+ import { readTheme, ThemeInputError, writeTheme } from "../core/userTheme.js";
5
+ import { UsageError } from "./project.js";
6
+ const USAGE = [
7
+ "p3 user-config 個人設定の値と出どころ(環境変数 / 個人設定 / 既定)",
8
+ `p3 user-config set キー=値 ... ui.theme=${THEMES.join("|")} / ${SETTING_KEY_LIST.filter((k) => k !== "codex.pathMap").join(" ")}(キー= で消す)`,
9
+ "p3 user-config set codex.pathMap+=<このマシンのパス>=<Docker デーモンから見たパス> パスの対応を足す",
10
+ "p3 user-config set codex.pathMap-=<このマシンのパス> パスの対応を外す(codex.pathMap= で全部)",
11
+ ].join("\n");
12
+ /**
13
+ * p3 user-config [set ...]。個人設定(このマシン・この人)のうち、画面のテーマとマシンごとの設定(codex / preflight / serve)を
14
+ * 見せ・変える。プロジェクトの登録は p3 project、プロジェクトの設定は p3 config。プロジェクトを決める前に動く。
15
+ */
16
+ export async function userConfigCommand(args, env = process.env) {
17
+ const [sub, ...pairs] = args;
18
+ const path = userConfigPath();
19
+ if (sub === undefined || sub === "ls" || sub === "show") {
20
+ const theme = await readTheme(path);
21
+ const user = await loadUserConfig(path).catch((e) => {
22
+ if (e instanceof UserConfigError)
23
+ throw new UsageError(e.message);
24
+ throw e;
25
+ });
26
+ const { rows, error } = describeSettings(user, env);
27
+ const width = Math.max(...rows.map((r) => r.key.length), "ui.theme".length) + 2;
28
+ const text = [
29
+ `${"ui.theme".padEnd(width)}${theme}`,
30
+ ...rows.map((r) => `${r.key.padEnd(width)}${r.value}${r.from === "既定" ? " (既定)" : r.from === "環境変数" ? ` (環境変数 ${r.env})` : ""}`),
31
+ ...(error ? ["", `読めない値があります: ${error}`] : []),
32
+ "",
33
+ `ファイル: ${path}`,
34
+ "変えるとき: p3 user-config set キー=値(例: p3 user-config set codex.pathMap+=/workspaces=/home/me/workspaces)",
35
+ ].join("\n");
36
+ return { data: { ui: { theme }, settings: rows, ...(error ? { error } : {}), path }, text };
37
+ }
38
+ if (sub !== "set" || !pairs.length)
39
+ throw new UsageError(USAGE);
40
+ let theme;
41
+ const changes = [];
42
+ try {
43
+ for (const pair of pairs) {
44
+ if (pair === "ui.theme" || pair.startsWith("ui.theme="))
45
+ theme = pair.slice("ui.theme=".length);
46
+ else
47
+ changes.push(parseSettingChange(pair));
48
+ }
49
+ // 読めない値があれば何も書かない(テーマも書く前に確かめる)
50
+ if (theme !== undefined && !THEMES.includes(theme))
51
+ throw new ThemeInputError(`ui.theme は ${THEMES.join(" / ")} のどれか: ${theme}`);
52
+ if (changes.length)
53
+ await writeMachineSettings(changes, path);
54
+ if (theme !== undefined)
55
+ await writeTheme(theme, path);
56
+ }
57
+ catch (e) {
58
+ if (e instanceof SettingsInputError || e instanceof ThemeInputError || e instanceof UserConfigError)
59
+ throw new UsageError(e.message);
60
+ throw e;
61
+ }
62
+ const keys = pairs.map((p) => p.replace(/^(codex\.pathMap[+-]?)=.*$/s, "$1").replace(/=.*$/s, ""));
63
+ return { data: { changed: keys, path }, text: `個人設定を変えました: ${keys.join(", ")}(${path})\n効いている値は p3 user-config で確かめられます` };
64
+ }
@@ -1,7 +1,6 @@
1
1
  import { dirname, join } from "node:path";
2
- import { ChatGptAccount, OAuthError, type OAuthDeps } from "@infodb/chatgpt-plan";
3
- import { userConfigPath } from "./userConfig.ts";
4
-
2
+ import { ChatGptAccount, OAuthError } from "@infodb/chatgpt-plan";
3
+ import { userConfigPath } from "./userConfig.js";
5
4
  /**
6
5
  * ChatGPT(Sign in with ChatGPT のプラン利用)との接続。サインイン・トークンの保存と更新・解除は
7
6
  * @infodb/chatgpt-plan(llmcs の chatgpt-plan-ts)が行い、ここには P3 の決まりだけを置く。設計: docs/chatgpt-sign-in.md
@@ -9,25 +8,20 @@ import { userConfigPath } from "./userConfig.ts";
9
8
  * ~/.config/infodb-p3/chatgpt.json 0600。秘密(トークン)を含む。個人設定(config.yaml)とは別のファイル
10
9
  * ~/.config/infodb-p3/chatgpt.lock トークンの更新の排他(CLI・serve・並行する Preflight で1つずつ)
11
10
  */
12
- export { ChatGptAccount, ChatGptAuthError, OAuthError, type ChatGptStatus } from "@infodb/chatgpt-plan";
13
-
11
+ export { ChatGptAccount, ChatGptAuthError, OAuthError } from "@infodb/chatgpt-plan";
14
12
  /** アプリの名前。初回の登録の agent_name_hint と、app-server の initialize の clientInfo.name をそろえる */
15
13
  export const APP_NAME = "infodb_p3";
16
-
17
14
  /** Codex に渡す access token の残りの長さ(1 ターンの途中で切れないように、部品の既定の 5 分より長く取る) */
18
15
  export const CODEX_TOKEN_MIN_VALID_MS = 35 * 60_000;
19
-
20
16
  export const connectionPath = () => join(dirname(userConfigPath()), "chatgpt.json");
21
-
22
17
  /** P3 の接続(CLI と serve で同じファイルを使う)。file と deps はテストで差し替える */
23
- export function chatgptAccount(file = connectionPath(), deps?: OAuthDeps): ChatGptAccount {
24
- return new ChatGptAccount({ file, appName: APP_NAME, appLabel: "P3", ...(deps ? { deps } : {}) });
18
+ export function chatgptAccount(file = connectionPath(), deps) {
19
+ return new ChatGptAccount({ file, appName: APP_NAME, appLabel: "P3", ...(deps ? { deps } : {}) });
25
20
  }
26
-
27
21
  /** サインインの失敗を CLI で次にすることが分かる文言にする(部品の文言は呼び方が P3 のものではない) */
28
- export function signInFailure(e: unknown): Error {
29
- if (e instanceof OAuthError && e.code === "account_mismatch") {
30
- return new Error(`${e.message.replace(/(登録ごと消す: .*)$/, "")}(p3 chatgpt logout --forget で登録ごと解除してから、サインインし直してください)`);
31
- }
32
- return e instanceof Error ? e : new Error(String(e));
22
+ export function signInFailure(e) {
23
+ if (e instanceof OAuthError && e.code === "account_mismatch") {
24
+ return new Error(`${e.message.replace(/(登録ごと消す: .*)$/, "")}(p3 chatgpt logout --forget で登録ごと解除してから、サインインし直してください)`);
25
+ }
26
+ return e instanceof Error ? e : new Error(String(e));
33
27
  }
@@ -0,0 +1,41 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { chatgptAccount } from "./chatgpt.js";
3
+ import { CodexWorkspaceEngine, codexConfig } from "./preflight/codexEngine.js";
4
+ import { fixedSettings, machineSettingsSource } from "./machineSettings.js";
5
+ import { MockEngine } from "./preflight/mockEngine.js";
6
+ import { PreflightService } from "./preflight/service.js";
7
+ import { checkDataDir } from "./store/locate.js";
8
+ import { Workspace } from "./store/workspace.js";
9
+ import { ReleaseGenerator } from "./releaseNotes/generate.js";
10
+ import { MockSummarizer } from "./releaseNotes/mockSummarizer.js";
11
+ /** p3 本体(パッケージ)のルート */
12
+ export const P3_ROOT = fileURLToPath(new URL("../../", import.meta.url));
13
+ /**
14
+ * サーバと CLI が共有する組み立て。どちらもデータのフォルダのファイルを直接読み書きする。
15
+ * repos: 参照先の名前 → このマシンのパス(個人設定)
16
+ * settings: マシンごとの設定(環境変数と個人設定から。.env は読まない)。省くと個人設定から、Preflight を始めるたび・
17
+ * エンジンの状態を見るたびに読み直す(serve を起動し直さずに効く)。MachineSettings を渡すとその値に決める(テストなど)。
18
+ * プロジェクト(データのフォルダ)側には置かない: 認証情報をプロジェクトの git に入れないため
19
+ */
20
+ export async function openProject(dataDir, opts = {}) {
21
+ // データのフォルダと project.yaml が無ければ、空のプロジェクトとして開かずに止める(何も作らない)
22
+ await checkDataDir(dataDir, opts.projectName);
23
+ const source = !opts.settings ? machineSettingsSource() : "get" in opts.settings ? opts.settings : fixedSettings(opts.settings);
24
+ // 初めの値(画面の表示の既定エンジン)。読めなくても開ける(Preflight を始めるときに設定のエラーとして知らせる)
25
+ const initial = await source.get().catch(() => undefined);
26
+ const ws = new Workspace(dataDir, opts.repos);
27
+ await ws.load();
28
+ // 既定は Codex(ChatGPT プランか旧来の auth.json。どちらも無ければ使えない理由と次にすることを出す)。
29
+ // Mock は preflight.engine: mock(P3_PREFLIGHT_ENGINE=mock)か --engine mock で明示したときだけ(認証の失敗を Mock の成功に見せない)
30
+ // プロジェクトを跨ぐ serve では、サインインの待ち受けを全プロジェクトで1つにするため外から渡す
31
+ const chatgpt = opts.chatgpt ?? chatgptAccount();
32
+ const codex = new CodexWorkspaceEngine({ load: async () => codexConfig(await source.get()), account: chatgpt });
33
+ const engines = { codex, mock: new MockEngine() };
34
+ const preflight = new PreflightService(ws, engines, {
35
+ initial: initial?.preflight.engine ?? "codex",
36
+ load: async () => (await source.get()).preflight.engine,
37
+ });
38
+ // 要約の生成も Preflight と同じ接続と既定のエンジン(preflight.engine)を使う
39
+ const releaseGenerator = new ReleaseGenerator(ws, { codex, mock: new MockSummarizer() }, { engine: async () => (await source.get()).preflight.engine });
40
+ return { ws, preflight, releaseGenerator, chatgpt, projectName: opts.projectName };
41
+ }
@@ -0,0 +1,128 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { Hierarchy } from "../shared/hierarchy.js";
4
+ import { REQUEST_ID } from "../shared/refs.js";
5
+ import { withFileLock } from "./store/fsutil.js";
6
+ /** 親子の規則に合わない・ロックを取れない(何も書いていない) */
7
+ export class HierarchyError extends Error {
8
+ code;
9
+ detail;
10
+ constructor(code, message, detail = {}) {
11
+ super(message);
12
+ this.code = code;
13
+ this.detail = detail;
14
+ }
15
+ }
16
+ /** ロックを待つ時間(越えたら hierarchy_busy。何も書いていないので、そのままやり直せる) */
17
+ const LOCK_TIMEOUT_MS = 10_000;
18
+ const BUSY = "p3:hierarchy-busy";
19
+ /** アーカイブした要望の ID(requests/.archive/ のフォルダ名) */
20
+ export async function archivedRequestIds(ws) {
21
+ return (await readdir(join(ws.requestsDir, ".archive"), { withFileTypes: true }).catch(() => []))
22
+ .filter((d) => d.isDirectory() && REQUEST_ID.test(d.name))
23
+ .map((d) => d.name);
24
+ }
25
+ /** 今読み込んでいる要望から親子を作る(アーカイブ済みはディスクから読む) */
26
+ export async function hierarchyOf(ws) {
27
+ return new Hierarchy({ requests: ws.requests.list(), unreadable: ws.requests.errors.keys(), archived: await archivedRequestIds(ws) });
28
+ }
29
+ /** 関係の操作を1つずつにする。取れなければ hierarchy_busy */
30
+ export async function withHierarchyLock(ws, fn) {
31
+ try {
32
+ return await withFileLock(join(ws.requestsDir, ".hierarchy.lock"), fn, { timeoutMs: LOCK_TIMEOUT_MS, busyMessage: BUSY });
33
+ }
34
+ catch (e) {
35
+ if (e.message === BUSY) {
36
+ throw new HierarchyError("hierarchy_busy", "ほかの操作が要望の親子を変えています(何も変えていません。もう一度やり直してください)");
37
+ }
38
+ throw e;
39
+ }
40
+ }
41
+ /** ロックの中で: 要望の一覧をディスクから読み直す(ほかのプロセスが変えた親を取り込む) */
42
+ async function fresh(ws) {
43
+ await ws.requests.load();
44
+ return hierarchyOf(ws);
45
+ }
46
+ /**
47
+ * child(作るときは undefined)の親を parent にしてよいかを確かめる。ロックの中で呼ぶ。
48
+ * 合わなければ HierarchyError(hierarchy_invalid)
49
+ */
50
+ async function checkParent(ws, h, child, parent) {
51
+ const invalid = (reason, message) => new HierarchyError("hierarchy_invalid", message, { reason });
52
+ if (!REQUEST_ID.test(parent))
53
+ throw invalid("invalid_id", `親の ID の形が違います: ${parent}(例: 261009-k7m3x。ほかのプロジェクトの要望は親にできません)`);
54
+ if (child === parent)
55
+ throw invalid("self", `${parent} は自分自身を親にできません`);
56
+ if (ws.requests.errors.has(parent))
57
+ throw invalid("unreadable", `親 ${parent} のファイルが読めません(直してから指定してください)`);
58
+ const p = h.get(parent);
59
+ if (!p) {
60
+ if ((await archivedRequestIds(ws)).includes(parent))
61
+ throw invalid("archived", `親 ${parent} はアーカイブ済みです`);
62
+ throw invalid("not_found", `親の要望がありません: ${parent}`);
63
+ }
64
+ if (child && h.ancestors(parent).some((a) => a.id === child)) {
65
+ throw invalid("cycle", `${parent} は ${child} の子孫なので親にできません(循環します)`);
66
+ }
67
+ // 親の側が既に循環しているなら、その下に付けない
68
+ const broken = h.issueOf(p);
69
+ if (broken?.code === "parent_cycle")
70
+ throw invalid("cycle", `親 ${parent} の祖先が循環しています(${broken.message})`);
71
+ return p;
72
+ }
73
+ /**
74
+ * 子を作る前に: ロックの中で親を確かめ、作成の入力に親の管理情報(期限・マイルストーン・タグ)を写して fn に渡す。
75
+ * 写すのは入力で指定していない項目だけ(タグは空なら写す)。作った後は親と子で別々に変えてよい
76
+ */
77
+ export async function withNewChild(ws, parent, input, fn) {
78
+ return withHierarchyLock(ws, async () => {
79
+ const p = await checkParent(ws, await fresh(ws), undefined, parent);
80
+ return fn(inheritFrom(p, input));
81
+ });
82
+ }
83
+ /** 子の作成の入力に、指定していない期限・マイルストーン・タグを親から写す(作るときだけ) */
84
+ export function inheritFrom(p, input) {
85
+ return {
86
+ ...input,
87
+ parent: p.id,
88
+ due: input.due ?? p.due,
89
+ milestone: input.milestone ?? p.milestone,
90
+ tags: input.tags?.length ? input.tags : [...p.tags],
91
+ };
92
+ }
93
+ /** 親を付け替える・外す(parent が undefined)前に: ロックの中で確かめてから fn(保存)を呼ぶ。前の親を返す */
94
+ export async function withParentChange(ws, rid, parent, fn) {
95
+ return withHierarchyLock(ws, async () => {
96
+ const h = await fresh(ws);
97
+ const cur = ws.requests.require(rid);
98
+ if (parent !== undefined)
99
+ await checkParent(ws, h, rid, parent);
100
+ return { result: await fn(), previous: cur.parent };
101
+ });
102
+ }
103
+ /** アーカイブの前に: 子のある要望・親のある要望は断る(未完了の子を暗黙に外さない)。ロックの中で fn を呼ぶ */
104
+ export async function withArchiveCheck(ws, rid, fn) {
105
+ return withHierarchyLock(ws, async () => {
106
+ const h = await fresh(ws);
107
+ const r = ws.requests.require(rid);
108
+ const kids = h.children(rid).map((c) => c.id);
109
+ if (kids.length) {
110
+ throw new HierarchyError("has_children", `${rid} には子の要望があります: ${kids.join(", ")}(子の親を外す(p3 request set <子> parent=)か、子を先に片付けてからアーカイブしてください)`, { ids: kids });
111
+ }
112
+ if (r.parent) {
113
+ throw new HierarchyError("has_parent", `${rid} は ${r.parent} の子です(p3 request set ${rid} parent= で親を外してからアーカイブしてください)`, { ids: [r.parent] });
114
+ }
115
+ return fn();
116
+ });
117
+ }
118
+ /** 詳細・show --brief に添える親子(子にはタスクの数を付ける) */
119
+ export async function hierarchyView(ws, rid) {
120
+ const v = (await hierarchyOf(ws)).view(rid);
121
+ return {
122
+ ...v,
123
+ children: v.children.map((c) => {
124
+ const tasks = ws.tasksOf(c.id).list();
125
+ return { ...c, tasks: { total: tasks.length, done: tasks.filter((t) => t.status === "done").length } };
126
+ }),
127
+ };
128
+ }
@@ -0,0 +1,146 @@
1
+ import { isAbsolute } from "node:path";
2
+ import { loadUserSettings, userConfigPath, UserConfigError } from "./userConfig.js";
3
+ /** 環境変数と個人設定の対応(docs/installation.md の「設定の決まり」の表と同じ) */
4
+ export const SETTING_KEYS = {
5
+ "codex.auth": "P3_CODEX_AUTH",
6
+ "codex.authVolume": "P3_CODEX_AUTH_VOLUME",
7
+ "codex.authFile": "P3_CODEX_AUTH_FILE",
8
+ "codex.pathMap": "P3_CODEX_PATH_MAP",
9
+ "codex.model": "P3_CODEX_MODEL",
10
+ "codex.effort": "P3_CODEX_EFFORT",
11
+ "codex.ensureImage": "P3_CODEX_ENSURE_IMAGE",
12
+ "preflight.engine": "P3_PREFLIGHT_ENGINE",
13
+ "serve.host": "P3_HOST",
14
+ "serve.port": "P3_PORT",
15
+ };
16
+ export const DEFAULT_SETTINGS = {
17
+ codex: { auth: "auto", pathMap: [], ensureImage: true },
18
+ preflight: { engine: "codex" },
19
+ serve: { host: "0.0.0.0", port: 4310 },
20
+ };
21
+ /** 設定の値が読めない(CLI は使い方の誤りと同じく終了コード 1)。configPath: 読んだ個人設定のファイル(共有の記録から外すため) */
22
+ export class SettingsError extends Error {
23
+ configPath;
24
+ }
25
+ export function machineSettingsSource(opts = {}) {
26
+ const path = opts.path ?? userConfigPath();
27
+ return {
28
+ path,
29
+ async get() {
30
+ try {
31
+ return resolveMachineSettings(await loadUserSettings(path), opts.env ?? process.env, opts.cli ?? {});
32
+ }
33
+ catch (e) {
34
+ const err = e instanceof UserConfigError
35
+ ? new SettingsError(e.message)
36
+ : e instanceof SettingsError && e.message.includes("個人設定")
37
+ ? new SettingsError(`${e.message}(${path})`)
38
+ : e;
39
+ if (err instanceof SettingsError)
40
+ err.configPath = path;
41
+ throw err;
42
+ }
43
+ },
44
+ };
45
+ }
46
+ /** 決まった設定(テストや、起動のときに一度だけ決めたいとき) */
47
+ export const fixedSettings = (settings, path = userConfigPath()) => ({ path, get: async () => settings });
48
+ export function resolveMachineSettings(user, env = process.env, cli = {}) {
49
+ const pick = (key, flag) => {
50
+ if (flag !== undefined)
51
+ return { value: flag, from: `--${key.split(".")[1]}` };
52
+ const name = SETTING_KEYS[key];
53
+ const e = env[name];
54
+ if (e !== undefined)
55
+ return e === "" ? { value: undefined, from: "default" } : { value: e, from: `環境変数 ${name}` };
56
+ const [section, field] = key.split(".");
57
+ const v = user.settings[section]?.[field];
58
+ return v === undefined || v === null || v === "" ? { value: undefined, from: "default" } : { value: v, from: `個人設定 ${key}` };
59
+ };
60
+ const text = (key) => {
61
+ const r = pick(key);
62
+ if (r.value === undefined)
63
+ return undefined;
64
+ if (typeof r.value !== "string" && typeof r.value !== "number")
65
+ throw new SettingsError(`${r.from} は文字列で指定してください`);
66
+ return String(r.value);
67
+ };
68
+ const oneOf = (key, choices, def) => {
69
+ const v = text(key);
70
+ if (v === undefined)
71
+ return def;
72
+ if (!choices.includes(v))
73
+ throw new SettingsError(`${pick(key).from} が読めません: ${v}(${choices.join(" / ")})`);
74
+ return v;
75
+ };
76
+ const ensure = pick("codex.ensureImage");
77
+ const port = pick("serve.port", cli.port);
78
+ const host = pick("serve.host", cli.host);
79
+ return {
80
+ codex: {
81
+ auth: oneOf("codex.auth", ["auto", "legacy"], DEFAULT_SETTINGS.codex.auth),
82
+ authVolume: text("codex.authVolume"),
83
+ authFile: text("codex.authFile"),
84
+ pathMap: parsePathMap(pick("codex.pathMap")),
85
+ model: text("codex.model"),
86
+ effort: text("codex.effort"),
87
+ ensureImage: ensure.value === undefined ? DEFAULT_SETTINGS.codex.ensureImage : parseBool(ensure),
88
+ },
89
+ preflight: { engine: oneOf("preflight.engine", ["codex", "mock"], DEFAULT_SETTINGS.preflight.engine) },
90
+ serve: {
91
+ host: host.value === undefined ? DEFAULT_SETTINGS.serve.host : String(host.value),
92
+ port: port.value === undefined ? DEFAULT_SETTINGS.serve.port : parsePort(port),
93
+ },
94
+ };
95
+ }
96
+ function parseBool(r) {
97
+ if (typeof r.value === "boolean")
98
+ return r.value;
99
+ const v = String(r.value).toLowerCase();
100
+ if (["1", "true", "yes", "on"].includes(v))
101
+ return true;
102
+ if (["0", "false", "no", "off"].includes(v))
103
+ return false;
104
+ throw new SettingsError(`${r.from} が読めません: ${String(r.value)}(true / false。環境変数なら 1 / 0 も可)`);
105
+ }
106
+ function parsePort(r) {
107
+ const n = Number(r.value);
108
+ if (!Number.isInteger(n) || n < 1 || n > 65535)
109
+ throw new SettingsError(`${r.from} が読めません: ${String(r.value)}(1〜65535 のポート番号)`);
110
+ return n;
111
+ }
112
+ const PATH_MAP_HINT = "個人設定は p3 user-config set codex.pathMap+=<このマシンのパス>=<Docker デーモンから見たパス> で1件ずつ。環境変数は <このマシンのパス>=<Docker デーモンから見たパス> をカンマ区切りで。例: /workspaces=/home/me/workspaces";
113
+ /** "ローカル=ホスト,..."(環境変数)か { ローカル: ホスト }(個人設定)。どちらも絶対パス */
114
+ function parsePathMap(r) {
115
+ if (r.value === undefined)
116
+ return [];
117
+ let pairs;
118
+ if (typeof r.value === "string") {
119
+ pairs = r.value
120
+ .split(",")
121
+ .map((s) => s.trim())
122
+ .filter(Boolean)
123
+ .map((s) => {
124
+ const at = s.indexOf("=");
125
+ if (at < 0)
126
+ throw new SettingsError(`${r.from} の「${s}」が読めません(${PATH_MAP_HINT})`);
127
+ return [s.slice(0, at).trim(), s.slice(at + 1).trim()];
128
+ });
129
+ }
130
+ else if (typeof r.value === "object" && !Array.isArray(r.value)) {
131
+ pairs = Object.entries(r.value).map(([k, v]) => {
132
+ if (typeof v !== "string")
133
+ throw new SettingsError(`${r.from} の「${k}」の値はパスの文字列で指定してください`);
134
+ return [k, v];
135
+ });
136
+ }
137
+ else {
138
+ throw new SettingsError(`${r.from} は「このマシンのパス: Docker デーモンから見たパス」の対応で指定してください`);
139
+ }
140
+ for (const [local, host] of pairs) {
141
+ if (!isAbsolute(local) || !host || !(isAbsolute(host) || /^[A-Za-z]:[\\/]/.test(host))) {
142
+ throw new SettingsError(`${r.from} の「${local}=${host}」が読めません。どちらも絶対パスにしてください(${PATH_MAP_HINT})`);
143
+ }
144
+ }
145
+ return pairs;
146
+ }