@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.
- package/bin/p3.mjs +11 -5
- package/dist/web/assets/Outputs-C83ZDXvs.js +1 -0
- package/dist/web/assets/RequestStatus-GmiWYEcL.js +1 -0
- package/dist/web/assets/Tabs-CJn0Qy7W.js +1 -0
- package/dist/web/assets/TagInput-CtM8HM8Z.js +1 -0
- package/dist/web/assets/TaskDrawer-D5v36QoF.js +3 -0
- package/dist/web/assets/_requestId-BHUqLO-j.js +1 -0
- package/dist/web/assets/_requestId-DxwxbXY2.js +30 -0
- package/dist/web/assets/{ui-DdOGYj9z.js → appCtx-B-VRVOyv.js} +1 -1
- package/dist/web/assets/board-DAaVR04x.js +1 -0
- package/dist/web/assets/done-CaqB_qTH.js +1 -0
- package/dist/web/assets/index-BF1xMdJo.css +2 -0
- package/dist/web/assets/index-BQYvKpjF.js +12 -0
- package/dist/web/assets/new-DLVnRvrB.js +1 -0
- package/dist/web/assets/{preflightInput-DMxqnvF8.js → preflightInput-BAeEJYUK.js} +1 -1
- package/dist/web/assets/preload-helper-B74h5i3O.js +1 -0
- package/dist/web/assets/progressTree-wp9mH4VF.js +1 -0
- package/dist/web/assets/release-notes-MTLcOcvZ.js +3 -0
- package/dist/web/assets/requestData-D-HXu-cy.js +1 -0
- package/dist/web/assets/routes-CI4Qfkjs.js +3 -0
- package/dist/web/assets/settings-CJMNgzi6.js +1 -0
- package/dist/web/index.html +4 -4
- package/docs/architecture.md +220 -3
- package/docs/development.md +16 -9
- package/docs/how-to-use.md +72 -7
- package/docs/installation.md +8 -6
- package/docs/publishing.md +4 -2
- package/lib/cli/args.js +172 -0
- package/lib/cli/chatgpt.js +70 -0
- package/lib/cli/codex.js +30 -0
- package/lib/cli/format.js +9 -0
- package/{src/cli/help.ts → lib/cli/help.js} +8 -8
- package/lib/cli/main.js +326 -0
- package/lib/cli/output.js +110 -0
- package/lib/cli/preflightCommands.js +301 -0
- package/lib/cli/project.js +649 -0
- package/lib/cli/readOnly.js +36 -0
- package/lib/cli/releaseNotesCommands.js +197 -0
- package/lib/cli/render.js +58 -0
- package/lib/cli/requestCommands.js +180 -0
- package/lib/cli/showView.js +100 -0
- package/lib/cli/taskCommands.js +152 -0
- package/lib/cli/userConfig.js +64 -0
- package/{src/core/chatgpt.ts → lib/core/chatgpt.js} +10 -16
- package/lib/core/context.js +41 -0
- package/lib/core/hierarchy.js +128 -0
- package/lib/core/machineSettings.js +146 -0
- package/lib/core/machineSettingsEdit.js +148 -0
- package/lib/core/ops.js +120 -0
- package/lib/core/preflight/carryover.js +105 -0
- package/lib/core/preflight/codexEngine.js +687 -0
- package/lib/core/preflight/codexImage.js +61 -0
- package/lib/core/preflight/diagnose.js +95 -0
- package/lib/core/preflight/engine.js +58 -0
- package/lib/core/preflight/input.js +83 -0
- package/lib/core/preflight/launch.js +68 -0
- package/lib/core/preflight/mockEngine.js +175 -0
- package/lib/core/preflight/render.js +304 -0
- package/lib/core/preflight/service.js +868 -0
- package/lib/core/preflight/split.js +83 -0
- package/lib/core/preflight/uiMaterials.js +281 -0
- package/lib/core/preflight/uiRender.js +89 -0
- package/lib/core/preflight/wireframe.js +63 -0
- package/lib/core/preflight/xlsx.js +324 -0
- package/lib/core/projectRegistry.js +207 -0
- package/lib/core/redact.js +28 -0
- package/lib/core/releaseNotes/completeRequests.js +106 -0
- package/lib/core/releaseNotes/generate.js +266 -0
- package/lib/core/releaseNotes/material.js +141 -0
- package/lib/core/releaseNotes/mockSummarizer.js +26 -0
- package/lib/core/releaseNotes/service.js +83 -0
- package/lib/core/releaseNotes/store.js +209 -0
- package/lib/core/repoAdmin.js +82 -0
- package/lib/core/repoRefs.js +72 -0
- package/lib/core/requestOps.js +154 -0
- package/lib/core/requestStatus.js +171 -0
- package/lib/core/store/attachments.js +242 -0
- package/lib/core/store/collection.js +254 -0
- package/lib/core/store/frontmatter.js +18 -0
- package/lib/core/store/fsutil.js +84 -0
- package/lib/core/store/locate.js +162 -0
- package/lib/core/store/normalize.js +150 -0
- package/lib/core/store/noteStore.js +59 -0
- package/lib/core/store/preflightStore.js +161 -0
- package/lib/core/store/projectFile.js +99 -0
- package/lib/core/store/workspace.js +320 -0
- package/lib/core/supersede.js +69 -0
- package/lib/core/userConfig.js +158 -0
- package/{src/core/userTheme.ts → lib/core/userTheme.js} +11 -13
- package/lib/core/workTargets.js +106 -0
- package/lib/server/api/chatgptRoutes.js +46 -0
- package/{src/server/api/local.ts → lib/server/api/local.js} +23 -22
- package/lib/server/api/manifest.js +140 -0
- package/lib/server/api/projectsRoutes.js +82 -0
- package/lib/server/api/releaseNoteRoutes.js +88 -0
- package/lib/server/api/repoRoutes.js +67 -0
- package/lib/server/api/routes.js +404 -0
- package/lib/server/api/userThemeRoutes.js +60 -0
- package/lib/server/server.js +85 -0
- package/lib/shared/dates.js +10 -0
- package/{src/shared/directTask.ts → lib/shared/directTask.js} +3 -11
- package/lib/shared/hierarchy.js +120 -0
- package/lib/shared/milestoneOrder.js +45 -0
- package/lib/shared/preflightInput.js +19 -0
- package/lib/shared/refs.js +44 -0
- package/lib/shared/repos.js +69 -0
- package/lib/shared/scopeView.js +39 -0
- package/{src/shared/tags.ts → lib/shared/tags.js} +9 -14
- package/lib/shared/types.js +74 -0
- package/lib/shared/workTarget.js +31 -0
- package/package.json +4 -7
- package/skills/p3/SKILL.md +10 -0
- package/dist/web/assets/Outputs-5Hby-S5Q.js +0 -1
- package/dist/web/assets/RequestStatus-CTkGjT02.js +0 -1
- package/dist/web/assets/TagInput-Rj3PNOAF.js +0 -1
- package/dist/web/assets/TaskDrawer-DtPhiYxP.js +0 -3
- package/dist/web/assets/_requestId-CGvAfIkB.js +0 -30
- package/dist/web/assets/_requestId-DxfYhgAq.js +0 -1
- package/dist/web/assets/board-wt47lfrE.js +0 -1
- package/dist/web/assets/done-C9Ct7ssb.js +0 -1
- package/dist/web/assets/index-BTFL2rpp.js +0 -12
- package/dist/web/assets/index-DAyBsvua.css +0 -2
- package/dist/web/assets/new-e4ID2vQV.js +0 -1
- package/dist/web/assets/preload-helper-DhIyFaOW.js +0 -1
- package/dist/web/assets/release-notes-CQ0d2r0k.js +0 -3
- package/dist/web/assets/requestData-BDZqyl35.js +0 -1
- package/dist/web/assets/routes-Bipv3lwJ.js +0 -2
- package/dist/web/assets/settings-Dwh8fj6p.js +0 -1
- package/src/cli/args.ts +0 -186
- package/src/cli/chatgpt.ts +0 -74
- package/src/cli/codex.ts +0 -28
- package/src/cli/format.ts +0 -9
- package/src/cli/main.ts +0 -337
- package/src/cli/output.ts +0 -117
- package/src/cli/preflightCommands.ts +0 -245
- package/src/cli/project.ts +0 -675
- package/src/cli/readOnly.ts +0 -36
- package/src/cli/releaseNotesCommands.ts +0 -198
- package/src/cli/render.ts +0 -60
- package/src/cli/requestCommands.ts +0 -172
- package/src/cli/showView.ts +0 -110
- package/src/cli/taskCommands.ts +0 -167
- package/src/cli/userConfig.ts +0 -58
- package/src/core/context.ts +0 -58
- package/src/core/machineSettings.ts +0 -207
- package/src/core/machineSettingsEdit.ts +0 -156
- package/src/core/ops.ts +0 -114
- package/src/core/preflight/carryover.ts +0 -133
- package/src/core/preflight/codexEngine.ts +0 -703
- package/src/core/preflight/codexImage.ts +0 -98
- package/src/core/preflight/diagnose.ts +0 -124
- package/src/core/preflight/engine.ts +0 -92
- package/src/core/preflight/input.ts +0 -65
- package/src/core/preflight/launch.ts +0 -86
- package/src/core/preflight/mockEngine.ts +0 -145
- package/src/core/preflight/render.ts +0 -339
- package/src/core/preflight/service.ts +0 -707
- package/src/core/preflight/uiMaterials.ts +0 -272
- package/src/core/preflight/uiRender.ts +0 -84
- package/src/core/preflight/wireframe.ts +0 -69
- package/src/core/preflight/xlsx.ts +0 -328
- package/src/core/projectRegistry.ts +0 -264
- package/src/core/redact.ts +0 -31
- package/src/core/releaseNotes/completeRequests.ts +0 -102
- package/src/core/releaseNotes/generate.ts +0 -283
- package/src/core/releaseNotes/material.ts +0 -114
- package/src/core/releaseNotes/mockSummarizer.ts +0 -28
- package/src/core/releaseNotes/service.ts +0 -110
- package/src/core/releaseNotes/store.ts +0 -216
- package/src/core/repoAdmin.ts +0 -81
- package/src/core/repoRefs.ts +0 -90
- package/src/core/requestOps.ts +0 -140
- package/src/core/requestStatus.ts +0 -58
- package/src/core/store/attachments.ts +0 -228
- package/src/core/store/collection.ts +0 -282
- package/src/core/store/frontmatter.ts +0 -22
- package/src/core/store/fsutil.ts +0 -90
- package/src/core/store/locate.ts +0 -181
- package/src/core/store/normalize.ts +0 -155
- package/src/core/store/noteStore.ts +0 -56
- package/src/core/store/preflightStore.ts +0 -136
- package/src/core/store/projectFile.ts +0 -101
- package/src/core/store/workspace.ts +0 -328
- package/src/core/supersede.ts +0 -74
- package/src/core/userConfig.ts +0 -205
- package/src/core/workTargets.ts +0 -120
- package/src/server/api/chatgptRoutes.ts +0 -49
- package/src/server/api/manifest.ts +0 -135
- package/src/server/api/projectsRoutes.ts +0 -89
- package/src/server/api/releaseNoteRoutes.ts +0 -89
- package/src/server/api/repoRoutes.ts +0 -67
- package/src/server/api/routes.ts +0 -382
- package/src/server/api/userThemeRoutes.ts +0 -62
- package/src/server/server.ts +0 -108
- package/src/shared/dates.ts +0 -12
- package/src/shared/milestoneOrder.ts +0 -44
- package/src/shared/preflightInput.ts +0 -27
- package/src/shared/refs.ts +0 -55
- package/src/shared/repos.ts +0 -113
- package/src/shared/scopeView.ts +0 -48
- package/src/shared/types.ts +0 -730
- package/src/shared/workTarget.ts +0 -44
- /package/{src → lib}/core/preflight/launcher.mjs +0 -0
- /package/{src → lib}/core/preflight/mock-ui.html +0 -0
- /package/{src → lib}/core/preflight/mock-ui.png +0 -0
- /package/{src → lib}/core/preflight/render-image/Dockerfile +0 -0
- /package/{src → lib}/core/preflight/render-image/fonts-ja.conf +0 -0
- /package/{src → lib}/core/preflight/render-image/render.mjs +0 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import YAML from "yaml";
|
|
2
|
+
const FENCE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
|
|
3
|
+
/** `---\nyaml\n---\nbody` 形式を分解する。frontmatter が無ければ空オブジェクト。 */
|
|
4
|
+
export function parseFrontmatter(text) {
|
|
5
|
+
const m = FENCE.exec(text);
|
|
6
|
+
if (!m)
|
|
7
|
+
return { data: {}, body: text };
|
|
8
|
+
const data = (YAML.parse(m[1]) ?? {});
|
|
9
|
+
// stringify は frontmatter と本文の間に空行を1つ入れるので、それを取り除く
|
|
10
|
+
return { data, body: text.slice(m[0].length).replace(/^\r?\n/, "") };
|
|
11
|
+
}
|
|
12
|
+
export function stringifyFrontmatter(data, body) {
|
|
13
|
+
// undefined / 空配列は書かない(差分を小さく、人が読みやすく保つ)
|
|
14
|
+
const clean = Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined && !(Array.isArray(v) && v.length === 0)));
|
|
15
|
+
const yaml = YAML.stringify(clean, { lineWidth: 0 }).trimEnd();
|
|
16
|
+
const text = body.trim();
|
|
17
|
+
return `---\n${yaml}\n---\n${text ? `\n${text}\n` : ""}`;
|
|
18
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { mkdir, rename, writeFile, open, stat, unlink } from "node:fs/promises";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { randomBytes, randomInt } from "node:crypto";
|
|
4
|
+
/** tmp に書いてから rename する。外部エディタ/AI が途中状態を読まないように。 */
|
|
5
|
+
export async function writeFileAtomic(path, content) {
|
|
6
|
+
await mkdir(dirname(path), { recursive: true });
|
|
7
|
+
const tmp = `${path}.${randomBytes(4).toString("hex")}.tmp`;
|
|
8
|
+
await writeFile(tmp, content, "utf8");
|
|
9
|
+
await rename(tmp, path);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* ロックのファイル(O_EXCL で作る)で、同じマシンの別のプロセス(CLI・serve)と処理を1つずつにする。
|
|
13
|
+
* 取れなければ少し待つ。古いロック(staleMs より前)は落ちたプロセスのものとして取り直す。
|
|
14
|
+
*/
|
|
15
|
+
export async function withFileLock(lock, fn, opts = {}) {
|
|
16
|
+
const { timeoutMs = 30_000, staleMs = 60_000, busyMessage = `${lock} を待ちきれませんでした(別のプロセスが使っています)` } = opts;
|
|
17
|
+
await mkdir(dirname(lock), { recursive: true, mode: 0o700 });
|
|
18
|
+
const until = Date.now() + timeoutMs;
|
|
19
|
+
for (;;) {
|
|
20
|
+
try {
|
|
21
|
+
const fh = await open(lock, "wx", opts.mode ?? 0o600);
|
|
22
|
+
await fh.writeFile(String(process.pid));
|
|
23
|
+
await fh.close();
|
|
24
|
+
break;
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
if (e.code !== "EEXIST")
|
|
28
|
+
throw e;
|
|
29
|
+
const st = await stat(lock).catch(() => undefined);
|
|
30
|
+
if (st && Date.now() - st.mtimeMs > staleMs) {
|
|
31
|
+
await unlink(lock).catch(() => { });
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (Date.now() > until)
|
|
35
|
+
throw new Error(busyMessage);
|
|
36
|
+
await new Promise((r) => setTimeout(r, 20 + Math.random() * 80));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
return await fn();
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
await unlink(lock).catch(() => { });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** 既に存在する場合は false を返す(ID 採番の競合検出用) */
|
|
47
|
+
export async function createExclusive(path, content) {
|
|
48
|
+
await mkdir(dirname(path), { recursive: true });
|
|
49
|
+
try {
|
|
50
|
+
const fh = await open(path, "wx");
|
|
51
|
+
await fh.writeFile(content, "utf8");
|
|
52
|
+
await fh.close();
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
catch (e) {
|
|
56
|
+
if (e.code === "EEXIST")
|
|
57
|
+
return false;
|
|
58
|
+
throw e;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export const nowIso = () => new Date().toISOString();
|
|
62
|
+
export function slugify(s) {
|
|
63
|
+
return (s
|
|
64
|
+
.toLowerCase()
|
|
65
|
+
.normalize("NFKC")
|
|
66
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
67
|
+
.replace(/^-+|-+$/g, "")
|
|
68
|
+
.slice(0, 40));
|
|
69
|
+
}
|
|
70
|
+
const BASE32 = "0123456789abcdefghjkmnpqrstvwxyz"; // Crockford(i l o u を除く)
|
|
71
|
+
/**
|
|
72
|
+
* 要望の ID(= フォルダ名)。作成日 + 乱数5文字(例: 261009-k7m3x)。
|
|
73
|
+
* 時刻順に並び、人が読み書きでき、複数人が同時に作っても実用上衝突しない(1日あたり約3,300万通り)。
|
|
74
|
+
* タイトルは後から変わるので含めない。
|
|
75
|
+
*/
|
|
76
|
+
export function newRequestId(now = new Date()) {
|
|
77
|
+
// 作った人の日付(ローカル時刻)で付ける
|
|
78
|
+
const p2 = (n) => String(n).padStart(2, "0");
|
|
79
|
+
const d = `${p2(now.getFullYear() % 100)}${p2(now.getMonth() + 1)}${p2(now.getDate())}`;
|
|
80
|
+
let rand = "";
|
|
81
|
+
for (let i = 0; i < 5; i++)
|
|
82
|
+
rand += BASE32[randomInt(32)];
|
|
83
|
+
return `${d}-${rand}`;
|
|
84
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { stat } from "node:fs/promises";
|
|
4
|
+
import { dirname, join, resolve, sep } from "node:path";
|
|
5
|
+
/** p3 init がデータを置く既定のフォルダ名(リポジトリのルートの直下) */
|
|
6
|
+
export const DATA_DIR_NAME = ".p3";
|
|
7
|
+
/** プロジェクトの決まり方の説明(whoami の表)。cwd 以外は今いる場所で決まっていない */
|
|
8
|
+
export const VIA_LABEL = {
|
|
9
|
+
dir: "--dir で指定",
|
|
10
|
+
project: "--project で指定",
|
|
11
|
+
cwd: "今いる場所",
|
|
12
|
+
legacy: "リポジトリの中の .p3/",
|
|
13
|
+
only: "登録が1つだけ。今いる場所では決まっていない",
|
|
14
|
+
};
|
|
15
|
+
/** 操作するプロジェクトが決まらない(次に何をすればよいかをメッセージに含める) */
|
|
16
|
+
export class ProjectNotResolvedError extends Error {
|
|
17
|
+
}
|
|
18
|
+
/** データのフォルダが無い・project.yaml が無い・読めない(次にすることをメッセージに含める)。ファイルは何も変えていない */
|
|
19
|
+
export class DataDirError extends Error {
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* データのフォルダとその project.yaml があるかを確かめる(プロジェクトを開く前。CLI と serve の共通の入口 openProject から)。
|
|
23
|
+
* 無いのに空のプロジェクトとして続けると、書く操作がフォルダを新しく作って別の場所に書いてしまう(移した・共有ドライブが
|
|
24
|
+
* つながっていない・パスの誤り)。無い(ENOENT)と読めない(権限・入出力)は分けて伝える。フォルダもファイルも作らない。
|
|
25
|
+
* requests/ は無くてよい(作ったばかりのプロジェクト)
|
|
26
|
+
*/
|
|
27
|
+
export async function checkDataDir(dataDir, projectName) {
|
|
28
|
+
const yaml = join(dataDir, "project.yaml");
|
|
29
|
+
const problem = async () => {
|
|
30
|
+
const dir = await stat(dataDir).catch((e) => e);
|
|
31
|
+
if (dir instanceof Error) {
|
|
32
|
+
return dir.code === "ENOENT" ? `データのフォルダがありません: ${dataDir}` : `データのフォルダを読めません: ${dataDir}(${dir.code ?? dir.message})`;
|
|
33
|
+
}
|
|
34
|
+
if (!dir.isDirectory())
|
|
35
|
+
return `データのフォルダがフォルダではありません: ${dataDir}`;
|
|
36
|
+
const file = await stat(yaml).catch((e) => e);
|
|
37
|
+
if (file instanceof Error) {
|
|
38
|
+
return file.code === "ENOENT" ? `データのフォルダに project.yaml がありません: ${yaml}` : `project.yaml を読めません: ${yaml}(${file.code ?? file.message})`;
|
|
39
|
+
}
|
|
40
|
+
if (!file.isFile())
|
|
41
|
+
return `project.yaml がファイルではありません: ${yaml}`;
|
|
42
|
+
return undefined;
|
|
43
|
+
};
|
|
44
|
+
const head = await problem();
|
|
45
|
+
if (!head)
|
|
46
|
+
return;
|
|
47
|
+
const name = projectName ?? "<名前>";
|
|
48
|
+
throw new DataDirError([
|
|
49
|
+
head,
|
|
50
|
+
projectName ? ` (個人設定のプロジェクト「${projectName}」の登録先)` : "",
|
|
51
|
+
" 既にあるデータなら: パスの誤り・フォルダの移動・共有ドライブ(同期するフォルダ)がつながっているかを確かめる",
|
|
52
|
+
projectName
|
|
53
|
+
? ` 登録の場所を直すとき: p3 project ls で確かめ、p3 project rm ${name} → p3 project add ${name} <正しいフォルダ>(rm はデータを消さない)`
|
|
54
|
+
: " --dir で指すときは、project.yaml のあるフォルダを指す",
|
|
55
|
+
` 新しく作るなら: 管理したいリポジトリの中で p3 init --project ${name} --dir <フォルダ>(ほかの人が作ったものに参加するなら p3 join)`,
|
|
56
|
+
]
|
|
57
|
+
.filter(Boolean)
|
|
58
|
+
.join("\n"));
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* 登録が1つだけで決まった(via: only)ときの案内。今いる場所とは関係なく決まるので、p3 を使わないフォルダでも当たる。
|
|
62
|
+
* 変える操作は止め(write)、読むだけの操作は警告して続ける。どちらも、プロジェクトを明示する方法と移る先を示す
|
|
63
|
+
*/
|
|
64
|
+
export function onlyRegistrationNotice(p, write) {
|
|
65
|
+
const name = p.name ?? "<名前>";
|
|
66
|
+
return [
|
|
67
|
+
write
|
|
68
|
+
? `今いる場所ではプロジェクトが決まりません(登録が1つだけなので「${name}」になりますが、変える操作はしません)。`
|
|
69
|
+
: `※ 今いる場所ではプロジェクトが決まらず、登録が1つだけなので「${name}」を表示しています。変える操作の前には対象を明示してください。`,
|
|
70
|
+
` プロジェクト: ${name} ${p.dataDir}`,
|
|
71
|
+
` → p3 --project ${name} <コマンド> で明示する`,
|
|
72
|
+
` → または登録したリポジトリ(p3 --project ${name} repo ls)かデータのフォルダの中で実行する`,
|
|
73
|
+
].join("\n");
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* 操作するプロジェクトを決める。環境変数では切り替えない(同じ人が複数のプロジェクトを行き来するため)。
|
|
77
|
+
*
|
|
78
|
+
* 1. --dir <フォルダ> データのフォルダを直接指す
|
|
79
|
+
* 2. --project <名前> 個人設定に登録したプロジェクト
|
|
80
|
+
* 3. 今いる場所 登録したプロジェクトのデータのフォルダか、そのリポジトリ(作業ツリーを含む)の中
|
|
81
|
+
* 4. リポジトリの中の .p3/ 個人設定に登録していないとき(git のメインの作業ツリー → 上へ辿る。デモ・登録前の clone など)
|
|
82
|
+
* 5. 登録が1つだけ それを使う
|
|
83
|
+
*/
|
|
84
|
+
export function resolveProject(o) {
|
|
85
|
+
const entries = Object.entries(o.user.projects);
|
|
86
|
+
const named = ([name, p], via) => ({
|
|
87
|
+
name,
|
|
88
|
+
dataDir: p.dir,
|
|
89
|
+
repos: { ...p.repos },
|
|
90
|
+
via,
|
|
91
|
+
});
|
|
92
|
+
if (o.dir) {
|
|
93
|
+
const dataDir = resolve(o.cwd, o.dir);
|
|
94
|
+
const hit = entries.find(([, p]) => p.dir === dataDir);
|
|
95
|
+
return hit ? named(hit, "dir") : { dataDir, repos: {}, via: "dir" };
|
|
96
|
+
}
|
|
97
|
+
if (o.project) {
|
|
98
|
+
const hit = entries.find(([name]) => name === o.project);
|
|
99
|
+
if (!hit)
|
|
100
|
+
throw new ProjectNotResolvedError(`プロジェクト「${o.project}」は登録されていません。\n${listing(o.user)}`);
|
|
101
|
+
return named(hit, "project");
|
|
102
|
+
}
|
|
103
|
+
const places = [...new Set([resolve(o.cwd), mainWorktree(o.cwd)].filter((x) => !!x))];
|
|
104
|
+
const hits = entries.filter(([, p]) => places.some((pl) => inside(pl, p.dir) || Object.values(p.repos).some((r) => inside(pl, r))));
|
|
105
|
+
if (hits.length === 1)
|
|
106
|
+
return named(hits[0], "cwd");
|
|
107
|
+
if (hits.length > 1) {
|
|
108
|
+
throw new ProjectNotResolvedError(`この場所は複数のプロジェクトに登録されています: ${hits.map(([n]) => n).join(", ")}\n → p3 --project <名前> <コマンド> で選んでください`);
|
|
109
|
+
}
|
|
110
|
+
const legacy = findDataDir(o.cwd);
|
|
111
|
+
if (legacy) {
|
|
112
|
+
const hit = entries.find(([, p]) => p.dir === legacy);
|
|
113
|
+
return hit ? named(hit, "legacy") : { dataDir: legacy, repos: {}, via: "legacy" };
|
|
114
|
+
}
|
|
115
|
+
if (entries.length === 1)
|
|
116
|
+
return named(entries[0], "only");
|
|
117
|
+
throw new ProjectNotResolvedError(entries.length
|
|
118
|
+
? `操作するプロジェクトが決まりません(今いる場所: ${o.cwd})。\n${listing(o.user)}`
|
|
119
|
+
: "プロジェクトがまだありません。管理したいリポジトリの中で次のどちらかを実行してください:\n 新しく作る: p3 init --project <名前>(データはリポジトリのルートの .p3。外に置くなら --dir <フォルダ>)\n 共有されたものに参加する: p3 join --project <名前>(ルートの .p3 に無ければ --dir <データのフォルダ>)");
|
|
120
|
+
}
|
|
121
|
+
function listing(user) {
|
|
122
|
+
const entries = Object.entries(user.projects);
|
|
123
|
+
if (!entries.length)
|
|
124
|
+
return " (登録済みのプロジェクトはありません。p3 init で作るか、p3 join で参加してください)";
|
|
125
|
+
const w = Math.max(...entries.map(([n]) => n.length));
|
|
126
|
+
return [
|
|
127
|
+
" 登録済みのプロジェクト:",
|
|
128
|
+
...entries.map(([n, p]) => ` ${n.padEnd(w)} ${p.dir}`),
|
|
129
|
+
" → p3 --project <名前> <コマンド>、またはプロジェクトのリポジトリの中で実行してください",
|
|
130
|
+
].join("\n");
|
|
131
|
+
}
|
|
132
|
+
const inside = (path, dir) => path === dir || path.startsWith(dir.endsWith(sep) ? dir : dir + sep);
|
|
133
|
+
/**
|
|
134
|
+
* リポジトリの中の .p3/ を探す(個人設定に登録していないとき。登録していれば 3. の今いる場所で決まる)。
|
|
135
|
+
* 要望ごとの作業ツリーの中で実行しても、git のメインの作業ツリーの .p3/ を使う(各作業ツリーの .p3/ はブランチ時点の写し)。
|
|
136
|
+
*/
|
|
137
|
+
export function findDataDir(cwd) {
|
|
138
|
+
const main = mainWorktree(cwd);
|
|
139
|
+
if (main && existsSync(join(main, DATA_DIR_NAME, "project.yaml")))
|
|
140
|
+
return join(main, DATA_DIR_NAME);
|
|
141
|
+
for (let dir = resolve(cwd);; dir = dirname(dir)) {
|
|
142
|
+
if (existsSync(join(dir, DATA_DIR_NAME, "project.yaml")))
|
|
143
|
+
return join(dir, DATA_DIR_NAME);
|
|
144
|
+
if (dirname(dir) === dir)
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** git のメインの作業ツリー(要望の作業ツリーの中からでもメインを返す) */
|
|
149
|
+
export function mainWorktree(cwd) {
|
|
150
|
+
try {
|
|
151
|
+
const common = execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
|
|
152
|
+
cwd,
|
|
153
|
+
encoding: "utf8",
|
|
154
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
155
|
+
}).trim();
|
|
156
|
+
// 通常は <main>/.git。bare リポジトリなどはメインの作業ツリーが無いので対象外
|
|
157
|
+
return common.endsWith("/.git") ? dirname(common) : undefined;
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { repoNameProblem } from "../../shared/repos.js";
|
|
2
|
+
import { isTaskStatus, RELATION_TYPES, REQUEST_STATUSES } from "../../shared/types.js";
|
|
3
|
+
const str = (v) => (v === undefined || v === null || v === "" ? undefined : String(v));
|
|
4
|
+
const num = (v) => (v === undefined || v === null || v === "" ? undefined : Number(v));
|
|
5
|
+
const strs = (v) => (Array.isArray(v) ? v.map(String) : typeof v === "string" ? [v] : []);
|
|
6
|
+
/** YAML は日付を Date にしてしまうので YYYY-MM-DD に戻す */
|
|
7
|
+
const date = (v) => (v instanceof Date ? v.toISOString().slice(0, 10) : str(v));
|
|
8
|
+
const iso = (v) => (v instanceof Date ? v.toISOString() : (str(v) ?? new Date(0).toISOString()));
|
|
9
|
+
export function normalizeRelations(v) {
|
|
10
|
+
if (!Array.isArray(v))
|
|
11
|
+
return [];
|
|
12
|
+
return v
|
|
13
|
+
.filter((r) => !!r && typeof r === "object")
|
|
14
|
+
.filter((r) => typeof r.type === "string" && r.type in RELATION_TYPES && typeof r.target === "string")
|
|
15
|
+
.map((r) => ({
|
|
16
|
+
type: r.type,
|
|
17
|
+
target: String(r.target),
|
|
18
|
+
note: str(r.note),
|
|
19
|
+
origin: str(r.origin),
|
|
20
|
+
}));
|
|
21
|
+
}
|
|
22
|
+
/** 要望 requestId のタスクとして読む(request / ref は場所から決まる) */
|
|
23
|
+
export const normalizeTaskIn = (requestId) => (d, body, id) => ({
|
|
24
|
+
id,
|
|
25
|
+
request: requestId,
|
|
26
|
+
ref: `${requestId}/${id}`,
|
|
27
|
+
title: str(d.title) ?? id,
|
|
28
|
+
// 3つ以外(古い設定の列など)は未着手として読む
|
|
29
|
+
status: isTaskStatus(d.status) ? d.status : "todo",
|
|
30
|
+
labels: strs(d.labels),
|
|
31
|
+
areas: strs(d.areas),
|
|
32
|
+
outputs: strs(d.outputs),
|
|
33
|
+
// 作業先(null / "" / 無いは作業先なし)
|
|
34
|
+
repo: str(d.repo) ?? null,
|
|
35
|
+
...(Array.isArray(d.repoOutputs) ? { repoOutputs: normalizeRepoOutputs(d.repoOutputs) } : {}),
|
|
36
|
+
startedAt: d.startedAt ? iso(d.startedAt) : undefined,
|
|
37
|
+
doneAt: d.doneAt ? iso(d.doneAt) : undefined,
|
|
38
|
+
checkedAt: d.checkedAt ? iso(d.checkedAt) : undefined,
|
|
39
|
+
record: str(d.record)?.trim() || undefined,
|
|
40
|
+
relations: normalizeRelations(d.relations),
|
|
41
|
+
rev: num(d.rev) ?? 1,
|
|
42
|
+
createdAt: iso(d.createdAt),
|
|
43
|
+
updatedAt: iso(d.updatedAt),
|
|
44
|
+
updatedBy: str(d.updatedBy),
|
|
45
|
+
body,
|
|
46
|
+
});
|
|
47
|
+
export const TASK_KEY_ORDER = [
|
|
48
|
+
"id", "title", "status", "repo", "labels", "areas", "outputs", "repoOutputs", "record",
|
|
49
|
+
"relations", "rev", "createdAt", "startedAt", "doneAt", "checkedAt", "updatedAt", "updatedBy",
|
|
50
|
+
];
|
|
51
|
+
export function normalizeRequest(d, body, id) {
|
|
52
|
+
const status = str(d.status);
|
|
53
|
+
return {
|
|
54
|
+
id,
|
|
55
|
+
title: str(d.title) ?? id,
|
|
56
|
+
status: REQUEST_STATUSES.includes(status) ? status : "draft",
|
|
57
|
+
// 形の違う親もそのまま読む(直そうとせず、親子の問題として知らせる)
|
|
58
|
+
...(str(d.parent) ? { parent: str(d.parent) } : {}),
|
|
59
|
+
...(str(d.splitFrom) ? { splitFrom: str(d.splitFrom) } : {}),
|
|
60
|
+
areas: strs(d.areas),
|
|
61
|
+
due: date(d.due),
|
|
62
|
+
milestone: str(d.milestone),
|
|
63
|
+
tags: strs(d.tags),
|
|
64
|
+
...(d.workstreams && typeof d.workstreams === "object" ? { workstreams: normalizeWorkstreams(d.workstreams) } : {}),
|
|
65
|
+
lastPreflight: str(d.lastPreflight),
|
|
66
|
+
rev: num(d.rev) ?? 1,
|
|
67
|
+
createdAt: iso(d.createdAt),
|
|
68
|
+
updatedAt: iso(d.updatedAt),
|
|
69
|
+
updatedBy: str(d.updatedBy),
|
|
70
|
+
body,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
export const REQUEST_KEY_ORDER = [
|
|
74
|
+
"id", "title", "status", "parent", "splitFrom", "due", "milestone", "tags", "areas", "workstreams", "lastPreflight",
|
|
75
|
+
"rev", "createdAt", "updatedAt", "updatedBy",
|
|
76
|
+
];
|
|
77
|
+
export function normalizeProject(d) {
|
|
78
|
+
const preflight = (d.preflight ?? {});
|
|
79
|
+
return {
|
|
80
|
+
name: str(d.name) ?? "p3 project",
|
|
81
|
+
description: str(d.description) ?? "",
|
|
82
|
+
repos: normalizeRepos(d.repos),
|
|
83
|
+
milestones: Array.isArray(d.milestones)
|
|
84
|
+
? d.milestones
|
|
85
|
+
.filter((m) => !!m && typeof m === "object" && !!m.id)
|
|
86
|
+
.map((m) => ({ id: String(m.id), title: str(m.title) ?? String(m.id), due: date(m.due), done: m.done === true ? true : undefined }))
|
|
87
|
+
: [],
|
|
88
|
+
branchPattern: str(d.branchPattern) ?? "req/{id}-{slug}",
|
|
89
|
+
preflight: { instructions: str(preflight.instructions) ?? "" },
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* project.yaml の repos。名前をキーにした対応(推奨)か、name を持つ項目の並び。名前が使えない項目・重複は読まない
|
|
94
|
+
* (書き戻すときも p3 repo で変えた項目のほかは触らないので、ファイルからは消えない)。
|
|
95
|
+
* map は「パス: 役割」か「パス: { role, entry }」の対応、または { path, role, entry } の並び
|
|
96
|
+
*/
|
|
97
|
+
export function normalizeRepos(v) {
|
|
98
|
+
const entries = Array.isArray(v)
|
|
99
|
+
? v.filter((x) => !!x && typeof x === "object").map((x) => [String(x.name ?? ""), x])
|
|
100
|
+
: v && typeof v === "object"
|
|
101
|
+
? Object.entries(v).map(([k, x]) => [k, x && typeof x === "object" ? x : { role: x }])
|
|
102
|
+
: [];
|
|
103
|
+
const out = [];
|
|
104
|
+
for (const [name, x] of entries) {
|
|
105
|
+
if (repoNameProblem(name) || out.some((r) => r.name === name))
|
|
106
|
+
continue;
|
|
107
|
+
out.push({
|
|
108
|
+
name,
|
|
109
|
+
role: str(x.role) ?? "",
|
|
110
|
+
readFirst: x.readFirst === true,
|
|
111
|
+
writable: x.writable === true,
|
|
112
|
+
map: normalizeCodeMap(x.map),
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
function normalizeCodeMap(v) {
|
|
118
|
+
const one = (path, x) => {
|
|
119
|
+
if (!path)
|
|
120
|
+
return undefined;
|
|
121
|
+
if (typeof x === "string")
|
|
122
|
+
return { path, role: x };
|
|
123
|
+
if (x && typeof x === "object") {
|
|
124
|
+
const o = x;
|
|
125
|
+
return { path, role: str(o.role) ?? "", ...(str(o.entry) ? { entry: str(o.entry) } : {}) };
|
|
126
|
+
}
|
|
127
|
+
return { path, role: "" };
|
|
128
|
+
};
|
|
129
|
+
const list = Array.isArray(v)
|
|
130
|
+
? v.map((x) => (x && typeof x === "object" ? one(String(x.path ?? ""), x) : undefined))
|
|
131
|
+
: v && typeof v === "object"
|
|
132
|
+
? Object.entries(v).map(([k, x]) => one(k, x))
|
|
133
|
+
: [];
|
|
134
|
+
return list.filter((x) => !!x);
|
|
135
|
+
}
|
|
136
|
+
/** リポジトリごとの成果物。repo と output のどちらかが無い項目は読まない */
|
|
137
|
+
export function normalizeRepoOutputs(v) {
|
|
138
|
+
return (Array.isArray(v) ? v : [])
|
|
139
|
+
.filter((x) => !!x && typeof x === "object")
|
|
140
|
+
.flatMap((x) => (str(x.repo) && str(x.output) ? [{ repo: str(x.repo), output: str(x.output) }] : []));
|
|
141
|
+
}
|
|
142
|
+
function normalizeWorkstreams(v) {
|
|
143
|
+
const out = {};
|
|
144
|
+
for (const [name, w] of Object.entries(v)) {
|
|
145
|
+
const o = w && typeof w === "object" ? w : {};
|
|
146
|
+
if (!repoNameProblem(name) && str(o.branch))
|
|
147
|
+
out[name] = { branch: str(o.branch) };
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { parseFrontmatter, stringifyFrontmatter } from "./frontmatter.js";
|
|
5
|
+
import { createExclusive, nowIso } from "./fsutil.js";
|
|
6
|
+
export const NOTE_ID = /^N-\d{8}-\d{6}-[0-9a-f]{4}$/;
|
|
7
|
+
/**
|
|
8
|
+
* requests/<要望ID>/notes/N-....md Preflight へのメモ(1件1ファイル。書き足すだけで、直さない)
|
|
9
|
+
*
|
|
10
|
+
* 誰がいつ書いたかを frontmatter に残す。ファイルを分けるので、複数人が同時に書いても衝突しない。
|
|
11
|
+
*/
|
|
12
|
+
export class NoteStore {
|
|
13
|
+
requestsDir;
|
|
14
|
+
/** requestsDir: .p3/requests */
|
|
15
|
+
constructor(requestsDir) {
|
|
16
|
+
this.requestsDir = requestsDir;
|
|
17
|
+
}
|
|
18
|
+
dir(requestId) {
|
|
19
|
+
return join(this.requestsDir, requestId, "notes");
|
|
20
|
+
}
|
|
21
|
+
async add(requestId, body, actor) {
|
|
22
|
+
const text = body.trim();
|
|
23
|
+
if (!text)
|
|
24
|
+
throw new Error("メモが空です");
|
|
25
|
+
for (;;) {
|
|
26
|
+
const createdAt = nowIso();
|
|
27
|
+
const stamp = createdAt.replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
|
|
28
|
+
const note = { id: `N-${stamp}-${randomBytes(2).toString("hex")}`, requestId, createdAt, createdBy: actor, body: text };
|
|
29
|
+
const file = stringifyFrontmatter({ id: note.id, createdAt, createdBy: actor }, text);
|
|
30
|
+
if (await createExclusive(join(this.dir(requestId), `${note.id}.md`), file))
|
|
31
|
+
return note;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** 古い順(作成日時、同じなら ID)。読めないファイルは invalid に理由を返す(黙って捨てない) */
|
|
35
|
+
async list(requestId) {
|
|
36
|
+
const files = (await readdir(this.dir(requestId)).catch(() => [])).filter((f) => f.endsWith(".md"));
|
|
37
|
+
const notes = [];
|
|
38
|
+
const invalid = [];
|
|
39
|
+
for (const f of files) {
|
|
40
|
+
const id = f.slice(0, -3);
|
|
41
|
+
try {
|
|
42
|
+
if (!NOTE_ID.test(id))
|
|
43
|
+
throw new Error("ファイル名が N-YYYYMMDD-HHMMSS-xxxx.md ではありません");
|
|
44
|
+
const { data, body } = parseFrontmatter(await readFile(join(this.dir(requestId), f), "utf8"));
|
|
45
|
+
if (!body.trim())
|
|
46
|
+
throw new Error("本文が空です");
|
|
47
|
+
const createdAt = typeof data.createdAt === "string" ? data.createdAt : "";
|
|
48
|
+
if (!createdAt)
|
|
49
|
+
throw new Error("createdAt がありません");
|
|
50
|
+
notes.push({ id, requestId, createdAt, createdBy: typeof data.createdBy === "string" ? data.createdBy : undefined, body: body.trim() });
|
|
51
|
+
}
|
|
52
|
+
catch (e) {
|
|
53
|
+
invalid.push({ file: `notes/${f}`, error: e.message });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
notes.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
|
|
57
|
+
return { notes, invalid };
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { readdir, readFile, mkdir, rm, stat } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { parseFrontmatter, stringifyFrontmatter } from "./frontmatter.js";
|
|
4
|
+
import { writeFileAtomic } from "./fsutil.js";
|
|
5
|
+
/**
|
|
6
|
+
* requests/<要望ID>/preflight/<RUN-ID>/
|
|
7
|
+
* run.json 評価結果・ログ・文脈(機械向け)
|
|
8
|
+
* drafts/D1.md ... 細分化されたタスク案(1案 = 1ファイル。人や AI が直接編集できる)
|
|
9
|
+
* children/C1.md ... 子の要望の案(分割の run。タスク案とは一緒に置かない)
|
|
10
|
+
*/
|
|
11
|
+
export class PreflightStore {
|
|
12
|
+
requestsDir;
|
|
13
|
+
/** requestsDir: .p3/requests */
|
|
14
|
+
constructor(requestsDir) {
|
|
15
|
+
this.requestsDir = requestsDir;
|
|
16
|
+
}
|
|
17
|
+
runDir(requestId, runId) {
|
|
18
|
+
return join(this.requestsDir, requestId, "preflight", runId);
|
|
19
|
+
}
|
|
20
|
+
async save(run) {
|
|
21
|
+
const { drafts, children, ...meta } = run;
|
|
22
|
+
await writeFileAtomic(join(this.runDir(run.requestId, run.id), "run.json"), JSON.stringify(meta, null, 2) + "\n");
|
|
23
|
+
}
|
|
24
|
+
async saveDrafts(requestId, runId, drafts) {
|
|
25
|
+
const dir = join(this.runDir(requestId, runId), "drafts");
|
|
26
|
+
await rm(dir, { recursive: true, force: true });
|
|
27
|
+
await mkdir(dir, { recursive: true });
|
|
28
|
+
for (const d of drafts)
|
|
29
|
+
await this.saveDraft(requestId, runId, d);
|
|
30
|
+
}
|
|
31
|
+
async saveDraft(requestId, runId, d) {
|
|
32
|
+
const { description, ...meta } = d;
|
|
33
|
+
await writeFileAtomic(join(this.runDir(requestId, runId), "drafts", `${d.key}.md`), stringifyFrontmatter({ ...meta, include: d.include }, description));
|
|
34
|
+
}
|
|
35
|
+
async loadDrafts(requestId, runId) {
|
|
36
|
+
const dir = join(this.runDir(requestId, runId), "drafts");
|
|
37
|
+
const files = await readdir(dir).catch(() => []);
|
|
38
|
+
const drafts = [];
|
|
39
|
+
for (const f of files.filter((f) => f.endsWith(".md"))) {
|
|
40
|
+
const { data, body } = parseFrontmatter(await readFile(join(dir, f), "utf8"));
|
|
41
|
+
drafts.push({
|
|
42
|
+
key: String(data.key ?? f.replace(/\.md$/, "")),
|
|
43
|
+
title: String(data.title ?? ""),
|
|
44
|
+
description: body.trim(),
|
|
45
|
+
areas: Array.isArray(data.areas) ? data.areas.map(String) : [],
|
|
46
|
+
dependsOn: Array.isArray(data.dependsOn) ? data.dependsOn.map(String) : [],
|
|
47
|
+
supersedes: Array.isArray(data.supersedes) ? data.supersedes.map(String) : [],
|
|
48
|
+
include: data.include !== false,
|
|
49
|
+
...("repo" in data ? { repo: data.repo === null || data.repo === "" || data.repo === "none" ? null : String(data.repo) } : {}),
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
return drafts.sort((a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }));
|
|
53
|
+
}
|
|
54
|
+
async saveChild(requestId, runId, c) {
|
|
55
|
+
const { description, ...meta } = c;
|
|
56
|
+
await writeFileAtomic(join(this.runDir(requestId, runId), "children", `${c.key}.md`), stringifyFrontmatter({ ...meta, include: c.include }, description));
|
|
57
|
+
}
|
|
58
|
+
/** 子の案(children/ が無ければ undefined: タスク案の run) */
|
|
59
|
+
async loadChildren(requestId, runId) {
|
|
60
|
+
const dir = join(this.runDir(requestId, runId), "children");
|
|
61
|
+
const files = await readdir(dir).catch(() => undefined);
|
|
62
|
+
if (!files)
|
|
63
|
+
return undefined;
|
|
64
|
+
const children = [];
|
|
65
|
+
for (const f of files.filter((f) => f.endsWith(".md"))) {
|
|
66
|
+
const { data, body } = parseFrontmatter(await readFile(join(dir, f), "utf8"));
|
|
67
|
+
const n = Number(data.estimatedTasks);
|
|
68
|
+
children.push({
|
|
69
|
+
key: String(data.key ?? f.replace(/\.md$/, "")),
|
|
70
|
+
title: String(data.title ?? ""),
|
|
71
|
+
description: body.trim(),
|
|
72
|
+
...(data.estimatedTasks !== undefined && Number.isFinite(n) ? { estimatedTasks: Math.max(0, Math.round(n)) } : {}),
|
|
73
|
+
requires: Array.isArray(data.requires) ? data.requires.map(String) : [],
|
|
74
|
+
overlaps: Array.isArray(data.overlaps) ? data.overlaps.map(String) : [],
|
|
75
|
+
include: data.include !== false,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return children.sort((a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }));
|
|
79
|
+
}
|
|
80
|
+
async get(requestId, runId) {
|
|
81
|
+
try {
|
|
82
|
+
const meta = JSON.parse(await readFile(join(this.runDir(requestId, runId), "run.json"), "utf8"));
|
|
83
|
+
const children = await this.loadChildren(requestId, runId);
|
|
84
|
+
return { ...meta, drafts: await this.loadDrafts(requestId, runId), ...(children ? { children } : {}) };
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** run の今の状態だけ(run.json の状態と日時。案・ログは返さない)。ファイルは変えない */
|
|
91
|
+
async pulse(requestId, runId) {
|
|
92
|
+
const file = join(this.runDir(requestId, runId), "run.json");
|
|
93
|
+
const info = await stat(file).catch((e) => e);
|
|
94
|
+
if (info instanceof Error) {
|
|
95
|
+
if (info.code !== "ENOENT")
|
|
96
|
+
return { id: runId, state: "broken" };
|
|
97
|
+
const dir = await stat(this.runDir(requestId, runId)).catch(() => undefined);
|
|
98
|
+
return { id: runId, state: dir?.isDirectory() ? "pending" : "missing" };
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const meta = JSON.parse(await readFile(file, "utf8"));
|
|
102
|
+
if (!meta || typeof meta !== "object" || typeof meta.status !== "string")
|
|
103
|
+
return { id: runId, state: "broken" };
|
|
104
|
+
return {
|
|
105
|
+
id: runId,
|
|
106
|
+
state: "ready",
|
|
107
|
+
status: meta.status,
|
|
108
|
+
...(meta.startedAt ? { startedAt: meta.startedAt } : {}),
|
|
109
|
+
...(meta.finishedAt ? { finishedAt: meta.finishedAt } : {}),
|
|
110
|
+
version: `${info.mtimeMs}:${info.size}`,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return { id: runId, state: "broken" };
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
async list(requestId) {
|
|
118
|
+
const ids = await readdir(join(this.requestsDir, requestId, "preflight")).catch(() => []);
|
|
119
|
+
const runs = await Promise.all(ids.filter((i) => i.startsWith("PF-")).map((i) => this.get(requestId, i)));
|
|
120
|
+
return newestFirst(runs.filter((r) => !!r));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* run を新しい順に並べる。基本は開始時刻だが、時計は戻ることがある(WSL2 の時刻の補正など)ので、
|
|
125
|
+
* 前回を引き継いだ run(previous)は、引き継いだ相手より必ず新しいとする。
|
|
126
|
+
*/
|
|
127
|
+
export function newestFirst(runs) {
|
|
128
|
+
const byTime = [...runs].sort((a, b) => b.startedAt.localeCompare(a.startedAt) || b.id.localeCompare(a.id));
|
|
129
|
+
// previous の鎖の長さ(引き継いだ回数)。鎖でつながる run どうしは、長い方が新しい
|
|
130
|
+
const ids = new Map(runs.map((r) => [r.id, r]));
|
|
131
|
+
const depth = new Map();
|
|
132
|
+
const chain = (r, seen = new Set()) => {
|
|
133
|
+
if (depth.has(r.id))
|
|
134
|
+
return depth.get(r.id);
|
|
135
|
+
const prev = r.previous && !seen.has(r.id) ? ids.get(r.previous) : undefined;
|
|
136
|
+
const d = prev ? chain(prev, seen.add(r.id)) + 1 : 0;
|
|
137
|
+
depth.set(r.id, d);
|
|
138
|
+
return d;
|
|
139
|
+
};
|
|
140
|
+
const root = (r) => {
|
|
141
|
+
let cur = r;
|
|
142
|
+
for (const seen = new Set(); cur.previous && ids.has(cur.previous) && !seen.has(cur.id);) {
|
|
143
|
+
seen.add(cur.id);
|
|
144
|
+
cur = ids.get(cur.previous);
|
|
145
|
+
}
|
|
146
|
+
return cur.id;
|
|
147
|
+
};
|
|
148
|
+
// 時刻順の並びで各鎖が占める位置はそのままにし、その位置に鎖の run を引き継いだ順(新しい方から)で入れ直す
|
|
149
|
+
const groups = new Map();
|
|
150
|
+
for (const r of byTime)
|
|
151
|
+
(groups.get(root(r)) ?? groups.set(root(r), []).get(root(r))).push(r);
|
|
152
|
+
for (const g of groups.values())
|
|
153
|
+
g.sort((a, b) => chain(b) - chain(a));
|
|
154
|
+
const next = new Map([...groups].map(([k]) => [k, 0]));
|
|
155
|
+
return byTime.map((r) => {
|
|
156
|
+
const k = root(r);
|
|
157
|
+
const i = next.get(k);
|
|
158
|
+
next.set(k, i + 1);
|
|
159
|
+
return groups.get(k)[i];
|
|
160
|
+
});
|
|
161
|
+
}
|