@infodb/p3 0.0.0-stage → 0.1.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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -2
  3. package/bin/p3.mjs +18 -0
  4. package/dist/web/apple-touch-icon.png +0 -0
  5. package/dist/web/assets/Outputs-Ni3pNuGU.js +1 -0
  6. package/dist/web/assets/RequestStatus-K8TZwpur.js +1 -0
  7. package/dist/web/assets/TagInput-BICKVH2x.js +1 -0
  8. package/dist/web/assets/TaskDrawer-BkDIstIN.js +3 -0
  9. package/dist/web/assets/_requestId-B5O_ytaq.js +1 -0
  10. package/dist/web/assets/_requestId-C66puEMO.js +30 -0
  11. package/dist/web/assets/action-CMjATXqv.js +1 -0
  12. package/dist/web/assets/board-CbfDjkls.js +1 -0
  13. package/dist/web/assets/copy-B1ZbihKL.js +2 -0
  14. package/dist/web/assets/done-CPQbCFHg.js +1 -0
  15. package/dist/web/assets/draft-dT3gLDIt.js +1 -0
  16. package/dist/web/assets/format-DuK6P1hb.js +1 -0
  17. package/dist/web/assets/index-BUcs2J6N.js +12 -0
  18. package/dist/web/assets/index-C3DkqwJ9.css +2 -0
  19. package/dist/web/assets/link-_s8ndNKS.js +1 -0
  20. package/dist/web/assets/new-T60RB7de.js +1 -0
  21. package/dist/web/assets/preload-helper-dXqN7N-I.js +1 -0
  22. package/dist/web/assets/release-notes-DxrPhDbt.js +3 -0
  23. package/dist/web/assets/requestData-D8ZiSZss.js +1 -0
  24. package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
  25. package/dist/web/assets/routes-D9ZxXoLk.js +2 -0
  26. package/dist/web/assets/search-CJ8MBKTz.js +1 -0
  27. package/dist/web/assets/settings-DsHVyqzJ.js +1 -0
  28. package/dist/web/assets/supersede-CLXlhCq0.js +1 -0
  29. package/dist/web/assets/ui-Cvke4y4X.js +1 -0
  30. package/dist/web/favicon.ico +0 -0
  31. package/dist/web/favicon.svg +12 -0
  32. package/dist/web/index.html +23 -0
  33. package/docs/architecture.md +588 -0
  34. package/docs/chatgpt-sign-in.md +163 -0
  35. package/docs/development.md +194 -0
  36. package/docs/how-to-use.md +524 -0
  37. package/docs/installation.md +275 -0
  38. package/docs/publishing.md +65 -0
  39. package/package.json +86 -3
  40. package/skills/p3/SKILL.md +95 -0
  41. package/src/cli/args.ts +179 -0
  42. package/src/cli/chatgpt.ts +74 -0
  43. package/src/cli/codex.ts +28 -0
  44. package/src/cli/format.ts +9 -0
  45. package/src/cli/help.ts +99 -0
  46. package/src/cli/main.ts +267 -0
  47. package/src/cli/output.ts +99 -0
  48. package/src/cli/preflightCommands.ts +237 -0
  49. package/src/cli/project.ts +501 -0
  50. package/src/cli/readOnly.ts +36 -0
  51. package/src/cli/releaseNotesCommands.ts +139 -0
  52. package/src/cli/render.ts +60 -0
  53. package/src/cli/requestCommands.ts +170 -0
  54. package/src/cli/showView.ts +110 -0
  55. package/src/cli/taskCommands.ts +167 -0
  56. package/src/cli/userConfig.ts +58 -0
  57. package/src/core/chatgpt.ts +33 -0
  58. package/src/core/context.ts +57 -0
  59. package/src/core/machineSettings.ts +207 -0
  60. package/src/core/machineSettingsEdit.ts +156 -0
  61. package/src/core/ops.ts +114 -0
  62. package/src/core/preflight/carryover.ts +133 -0
  63. package/src/core/preflight/codexEngine.ts +702 -0
  64. package/src/core/preflight/codexImage.ts +98 -0
  65. package/src/core/preflight/diagnose.ts +124 -0
  66. package/src/core/preflight/engine.ts +92 -0
  67. package/src/core/preflight/input.ts +65 -0
  68. package/src/core/preflight/launch.ts +86 -0
  69. package/src/core/preflight/launcher.mjs +75 -0
  70. package/src/core/preflight/mock-ui.html +24 -0
  71. package/src/core/preflight/mock-ui.png +0 -0
  72. package/src/core/preflight/mockEngine.ts +145 -0
  73. package/src/core/preflight/render-image/Dockerfile +23 -0
  74. package/src/core/preflight/render-image/render.mjs +53 -0
  75. package/src/core/preflight/render.ts +336 -0
  76. package/src/core/preflight/service.ts +690 -0
  77. package/src/core/preflight/uiMaterials.ts +272 -0
  78. package/src/core/preflight/uiRender.ts +84 -0
  79. package/src/core/preflight/wireframe.ts +69 -0
  80. package/src/core/preflight/xlsx.ts +328 -0
  81. package/src/core/redact.ts +31 -0
  82. package/src/core/releaseNotes/generate.ts +271 -0
  83. package/src/core/releaseNotes/material.ts +114 -0
  84. package/src/core/releaseNotes/mockSummarizer.ts +28 -0
  85. package/src/core/releaseNotes/service.ts +106 -0
  86. package/src/core/releaseNotes/store.ts +216 -0
  87. package/src/core/repoAdmin.ts +81 -0
  88. package/src/core/repoRefs.ts +90 -0
  89. package/src/core/requestOps.ts +140 -0
  90. package/src/core/requestStatus.ts +58 -0
  91. package/src/core/store/attachments.ts +228 -0
  92. package/src/core/store/collection.ts +282 -0
  93. package/src/core/store/frontmatter.ts +22 -0
  94. package/src/core/store/fsutil.ts +90 -0
  95. package/src/core/store/locate.ts +181 -0
  96. package/src/core/store/normalize.ts +155 -0
  97. package/src/core/store/noteStore.ts +56 -0
  98. package/src/core/store/preflightStore.ts +136 -0
  99. package/src/core/store/projectFile.ts +101 -0
  100. package/src/core/store/workspace.ts +328 -0
  101. package/src/core/supersede.ts +74 -0
  102. package/src/core/userConfig.ts +180 -0
  103. package/src/core/userTheme.ts +22 -0
  104. package/src/core/workTargets.ts +120 -0
  105. package/src/server/api/chatgptRoutes.ts +48 -0
  106. package/src/server/api/local.ts +33 -0
  107. package/src/server/api/manifest.ts +119 -0
  108. package/src/server/api/releaseNoteRoutes.ts +78 -0
  109. package/src/server/api/repoRoutes.ts +67 -0
  110. package/src/server/api/routes.ts +374 -0
  111. package/src/server/api/userThemeRoutes.ts +62 -0
  112. package/src/server/server.ts +49 -0
  113. package/src/shared/dates.ts +12 -0
  114. package/src/shared/preflightInput.ts +27 -0
  115. package/src/shared/refs.ts +55 -0
  116. package/src/shared/repos.ts +113 -0
  117. package/src/shared/scopeView.ts +48 -0
  118. package/src/shared/tags.ts +27 -0
  119. package/src/shared/types.ts +700 -0
  120. package/src/shared/workTarget.ts +44 -0
@@ -0,0 +1,501 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { appendFile, copyFile, mkdir } from "node:fs/promises";
4
+ import { homedir, userInfo } from "node:os";
5
+ import { basename, dirname, join, relative, resolve } from "node:path";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { fileURLToPath } from "node:url";
8
+ import { REQUEST_ID } from "../shared/refs.ts";
9
+ import type { ProjectConfig } from "../shared/types.ts";
10
+ import type { P3Context } from "../core/context.ts";
11
+ import { resolveRequestId } from "../core/ops.ts";
12
+ import { writeProjectFile, writeRepoEntry } from "../core/store/projectFile.ts";
13
+ import { repoNameProblem } from "../shared/repos.ts";
14
+ import { addRepo, checkFolder, RepoAdminError, removeRepo, setLocalRepoPath, updateRepo, type RepoPatch } from "../core/repoAdmin.ts";
15
+ import { Workspace as WorkspaceStore } from "../core/store/workspace.ts";
16
+ import { requestWorkstreams } from "../shared/workTarget.ts";
17
+ import type { Workspace } from "../core/store/workspace.ts";
18
+ import { loadUserConfig, PROJECT_NAME, setProjectNode, updateUserConfig, userConfigPath } from "../core/userConfig.ts";
19
+
20
+ /** プロジェクトの初期設定・設定変更、変更者と「今の要望」の判定(CLI) */
21
+
22
+ export class UsageError extends Error {}
23
+
24
+ function git(cwd: string, ...args: string[]): string | undefined {
25
+ try {
26
+ return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || undefined;
27
+ } catch {
28
+ return undefined;
29
+ }
30
+ }
31
+
32
+ /** リポジトリのルート(git のメインの作業ツリー)。git 管理外ならカレント */
33
+ export function repoRoot(cwd: string): string {
34
+ const common = git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir");
35
+ if (common?.endsWith("/.git")) return common.slice(0, -"/.git".length);
36
+ return git(cwd, "rev-parse", "--show-toplevel") ?? cwd;
37
+ }
38
+
39
+ /**
40
+ * CLI の変更者。明示(--actor / P3_ACTOR。AI は ai:<名前>)→ human:<git の user.name> → OS のユーザー名。
41
+ */
42
+ export function resolveActor(explicit: string | undefined, cwd: string): string {
43
+ if (explicit) return explicit;
44
+ return `human:${git(cwd, "config", "user.name") ?? process.env.USER ?? userInfo().username}`;
45
+ }
46
+
47
+ /** 今いる場所が、どの参照先(リポジトリ・フォルダ)か。参照先の中か、その git のリポジトリの作業ツリーの中なら当たる */
48
+ export function locateHere(ctx: P3Context, cwd: string): { repos: string[]; branch?: string } {
49
+ const here = resolve(cwd);
50
+ const common = git(here, "rev-parse", "--path-format=absolute", "--git-common-dir");
51
+ const repos = ctx.ws
52
+ .refs()
53
+ .filter((r) => r.status === "ok" && r.local)
54
+ .filter((r) => {
55
+ if (inside(here, r.local!)) return true;
56
+ // 要望の作業ツリーの中: 参照先と同じ git のリポジトリで、作業ツリーの中の同じ場所(サブフォルダなら同じ相対位置)より下
57
+ if (!common) return false;
58
+ const theirs = git(r.local!, "rev-parse", "--path-format=absolute", "--git-common-dir");
59
+ if (theirs !== common) return false;
60
+ const top = git(here, "rev-parse", "--show-toplevel");
61
+ const theirTop = git(r.local!, "rev-parse", "--show-toplevel");
62
+ return !!top && !!theirTop && inside(here, join(top, relative(theirTop, r.local!)));
63
+ })
64
+ .map((r) => r.name);
65
+ const branch = common ? git(here, "symbolic-ref", "--quiet", "--short", "HEAD") : undefined;
66
+ return { repos, branch };
67
+ }
68
+
69
+ const inside = (path: string, dir: string) => path === dir || path.startsWith(dir.endsWith("/") ? dir : `${dir}/`);
70
+
71
+ /**
72
+ * 今の要望。明示(--req / P3_REQUEST)→ 今いる参照先のブランチ(その参照先の割当だけと照らす)→
73
+ * ブランチ名に要望 ID が入っている(detached HEAD などで決まらなければ --req で指定してもらう)。
74
+ * パスに要望 ID が入っているだけでは決めない。候補が複数なら --req を案内する。
75
+ * AI が要望の作業ツリーで作業していれば、`p3 new "..."` だけでその要望のタスクになる。
76
+ */
77
+ export function currentRequest(ctx: P3Context, explicit: string | undefined, cwd: string): string | undefined {
78
+ if (explicit) {
79
+ const id = resolveRequestId(ctx, explicit);
80
+ if (!id) throw new UsageError(`要望が見つかりません: ${explicit}`);
81
+ return id;
82
+ }
83
+ const { repos: hereRepos, branch } = locateHere(ctx, cwd);
84
+ const requests = ctx.ws.requests.list();
85
+ const pick = (ids: string[], why: string) => {
86
+ const uniq = [...new Set(ids)];
87
+ if (uniq.length > 1) throw new UsageError(`${why}が複数の要望に当たります: ${uniq.join(", ")}。--req <要望ID> で指定してください`);
88
+ return uniq[0];
89
+ };
90
+ if (branch) {
91
+ // 今いる参照先の割当だけと照らす(別のリポジトリの同じ名前のブランチと取り違えない)。参照先の外なら全部と照らす
92
+ const byBranch = requests
93
+ .filter((r) => Object.entries(requestWorkstreams(r)).some(([name, w]) => w.branch === branch && (!hereRepos.length || hereRepos.includes(name))))
94
+ .map((r) => r.id);
95
+ const hit = pick(byBranch, `ブランチ ${branch} `);
96
+ if (hit) return hit;
97
+ }
98
+ if (branch) {
99
+ const m = new RegExp(REQUEST_ID.source.slice(1, -1)).exec(branch);
100
+ if (m && ctx.ws.requests.get(m[0])) return m[0];
101
+ }
102
+ return undefined;
103
+ }
104
+
105
+ /** init で本体の主なフォルダ(最初に読むもの)の候補にするドキュメントと、フォルダの入口の候補 */
106
+ const DOC_CANDIDATES = ["docs", "doc", "README.md", "ARCHITECTURE.md", "DESIGN.md", "AGENTS.md", "CLAUDE.md", "CONTRIBUTING.md"];
107
+ const DOC_ENTRIES = ["README.md", "index.md"];
108
+
109
+ const AGENTS_MARK = "タスク管理(infodb p3)";
110
+
111
+ /**
112
+ * p3 init --agents で AGENTS.md / CLAUDE.md に追記する指示。手順の詳しい版は同梱のスキル(skills/p3/SKILL.md)で、
113
+ * 役割と終わり方はそちらとそろえる(test/agents.test.ts が確かめる)
114
+ */
115
+ export const AGENTS_SNIPPET = `
116
+ ## ${AGENTS_MARK}
117
+
118
+ - 作業の単位は要望。タスクは \`p3\` CLI(入っていなければ \`pnpx @infodb/p3\`)で操作し、\`--json\` で結果を読むこと(データのフォルダを直接編集しない)。
119
+ 詳しい手順はスキル \`.claude/skills/p3/SKILL.md\`(Claude Code)・\`.agents/skills/p3/SKILL.md\`(Codex)。中身は同じ
120
+ - 変更するときは環境変数 \`P3_ACTOR=ai:<エージェント名>\` を付ける
121
+ - 操作する要望は \`--req <要望ID>\` で指定する(要望の作業ツリーの中なら省ける)。まず \`p3 whoami --json\` で確かめる
122
+ - \`whoami\` の \`via\`(プロジェクトの決まり方)が \`cwd\` でなければ(\`dir\` / \`project\` / \`legacy\` / \`only\`)、それ以上 p3 を操作せず、対象のプロジェクトでよいか人に確かめる(推測した \`--project\` / \`--dir\` で避けない。人が指定・確認した後はその対象のまま続ける)
123
+ - 新しい作業を頼まれたら \`p3 request new "<タイトル>" --body "..."\` で要望を登録し、ID を伝えて終える。
124
+ Preflight(\`preflight\`)とタスク化(\`accept\`)は人が行う(AI は実行しない。結果を \`p3 drafts\` で読むのと、頼まれたメモの保存 \`--note-only\` はよい)
125
+ - 着手する前に \`p3 show T003 --brief --json\` で本文・依存とその状態(\`dependencies\`)・置き換えの注意(\`warnings\`)を読む
126
+ - 着手する前に、\`--brief --json\` の \`work\`(作業先のリポジトリとブランチ)を見て、そのリポジトリでブランチに入る(作業先なしなら移動しない)
127
+ - 着手するときは \`p3 move T003 doing\`、終えたら \`p3 move T003 done --output <PR の URL など> --record -\`(変更の記録は必須: 何を変えたか・なぜ・入れた決まり・やめたもの を標準入力から Markdown で)。複数のリポジトリにまたがるときは最後のタスクに \`--repo-output <参照先>=<PR の URL>\` で全部の PR を残す
128
+ - 要望のタスクを全部終えたら \`p3 request set <要望ID> status=resolved\`(対応済)にする。完了済(done)・見送り(rejected)とタスクの済み(check)は人が決める
129
+ - 置き換えられたタスク(\`p3 ls\` の \`※置換\`、\`--json\` の \`superseded\`)からは始めない。\`move\` が \`warnings\` を返したら止めて人に確かめる
130
+ - 作業中に新しく必要になった作業は \`p3 new "<タイトル>" --body "..."\` でタスクにする(人への質問はタスクにしない)
131
+ `;
132
+
133
+ /**
134
+ * 同梱のスキルの原本と、プロジェクトに置く場所(リポジトリのルートからの相対パス。同じ原本を写す)。
135
+ * 置くのはプロジェクトの中だけ(個人のスキルの場所に置くと、p3 を使わないプロジェクトでも読まれる)
136
+ */
137
+ export const SKILL_SOURCE = fileURLToPath(new URL("../../skills/p3/SKILL.md", import.meta.url));
138
+ export const SKILL_TARGETS = [
139
+ { path: ".claude/skills/p3/SKILL.md", agent: "Claude Code" },
140
+ { path: ".agents/skills/p3/SKILL.md", agent: "Codex" },
141
+ ] as const;
142
+
143
+ /**
144
+ * --agents: AGENTS.md(無ければ CLAUDE.md、どちらも無ければ AGENTS.md を作る)に指示を追記し、スキルを置く。
145
+ * 指示は見出しがあれば足さない。スキルは置く場所ごとに、無ければ置き、同じ内容なら何もせず、違えば上書きしない
146
+ * (手で直したものを消さない。片方が違っても、もう片方は置く)。
147
+ */
148
+ async function placeAgents(root: string, cwd: string): Promise<string[]> {
149
+ const lines: string[] = [];
150
+ const agentsFile = ["AGENTS.md", "CLAUDE.md"].find((f) => existsSync(join(root, f)));
151
+ const target = join(root, agentsFile ?? "AGENTS.md");
152
+ if (existsSync(target) && readFileSync(target, "utf8").includes(AGENTS_MARK)) {
153
+ lines.push(` AI 向けの使い方は ${relative(cwd, target) || target} に書いてあります(追記しません)`);
154
+ } else {
155
+ await appendFile(target, AGENTS_SNIPPET);
156
+ lines.push(` AI 向けの使い方を ${relative(cwd, target) || target} に追記しました`);
157
+ }
158
+ const source = readFileSync(SKILL_SOURCE, "utf8");
159
+ for (const t of SKILL_TARGETS) {
160
+ const skill = join(root, t.path);
161
+ const shown = relative(cwd, skill);
162
+ if (!existsSync(skill)) {
163
+ await mkdir(dirname(skill), { recursive: true });
164
+ await copyFile(SKILL_SOURCE, skill);
165
+ lines.push(` AI 向けのスキル(${t.agent})を ${shown} に置きました`);
166
+ } else if (readFileSync(skill, "utf8") === source) {
167
+ lines.push(` AI 向けのスキル(${t.agent})${shown} は最新です`);
168
+ } else {
169
+ lines.push(` ※ ${shown}(${t.agent})は既にあり、同梱の版と違うので上書きしません。手で見比べて更新してください: ${SKILL_SOURCE}`);
170
+ }
171
+ }
172
+ return lines;
173
+ }
174
+
175
+ export interface InitOptions {
176
+ cwd: string;
177
+ /** 個人設定に登録する名前(既定: リポジトリのフォルダ名) */
178
+ project?: string;
179
+ /** データを置くフォルダ(必須。端末では聞く) */
180
+ dir?: string;
181
+ name?: string;
182
+ description?: string;
183
+ instructions?: string;
184
+ agents?: boolean;
185
+ yes?: boolean;
186
+ /** このリポジトリの参照先の名前(既定はフォルダ名) */
187
+ repoName?: string;
188
+ }
189
+
190
+ /**
191
+ * p3 init。管理したいリポジトリの中で実行する。
192
+ * - データを置くフォルダ(場所は自由。リポジトリの外を勧める)に project.yaml と requests/ を作る
193
+ * - 既に作られたフォルダ(他の人が作って共有したもの)を指したら、作らずに参加だけする
194
+ * - どちらの場合も個人設定に「プロジェクト名 → フォルダ・手元のリポジトリ」を登録する。以後はリポジトリの中なら指定が要らない
195
+ * 端末から実行すると対話式で聞き、--yes か非対話(AI・スクリプト)なら引数と推測した既定値で作る。
196
+ */
197
+ export async function init(o: InitOptions): Promise<string> {
198
+ const root = repoRoot(o.cwd);
199
+ const user = await loadUserConfig();
200
+
201
+ const interactive = !o.yes && process.stdin.isTTY && process.stdout.isTTY;
202
+ const rl = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : undefined;
203
+ const ask = async (q: string, def: string) => {
204
+ if (!rl) return def;
205
+ const a = (await rl.question(`${q}${def ? ` [${def}]` : ""}: `)).trim();
206
+ return a || def;
207
+ };
208
+
209
+ try {
210
+ if (rl) console.log(`p3 のプロジェクトを作ります(リポジトリ: ${root})\n(Enter で [ ] 内の既定値)\n`);
211
+ const key = await ask("プロジェクト名(切り替えに使う短い名前)", o.project ?? slugifyName(basename(root)) ?? "project");
212
+ if (!PROJECT_NAME.test(key)) throw new UsageError(`プロジェクト名は英数字と . _ - で: ${key}`);
213
+ const dirRaw = o.dir ?? (await ask("データを置くフォルダ(リポジトリの外を勧めます)", ""));
214
+ if (!dirRaw) throw new UsageError("データを置くフォルダを指定してください。例: p3 init --project myapp --dir ~/p3-data/myapp");
215
+ const dir = resolvePath(o.cwd, dirRaw);
216
+
217
+ const registered = user.projects[key];
218
+ if (registered && registered.dir !== dir) throw new UsageError(`プロジェクト名「${key}」は別のフォルダで登録済みです: ${registered.dir}`);
219
+ // このリポジトリを参照先として登録する名前(新しく作るときは本体として共有の定義も書く。参加するときは同じ名前の参照先か、
220
+ // 参照先が1つならそれ。決まらなければ登録せず p3 repo path を案内する)
221
+ const joining = existsSync(join(dir, "project.yaml"));
222
+ const shared = joining ? (await (async () => { const ws = new WorkspaceStore(dir); await ws.load(); return ws.project.repos; })()) : [];
223
+ const derived = o.repoName ?? slugifyName(basename(root)) ?? "app";
224
+ const refName = joining ? (shared.find((r) => r.name === derived) ?? (shared.length === 1 ? shared[0] : undefined))?.name : derived;
225
+ if (!joining && repoNameProblem(refName!)) throw new UsageError(`参照先の名前: ${repoNameProblem(refName!)}(--repo-name で指定してください)`);
226
+ // 最新の個人設定の上で、このプロジェクトの登録だけを書く(聞いている間にほかで変わっていても消さない)
227
+ const register = () =>
228
+ updateUserConfig((doc, now) => {
229
+ const prev = now.projects[key];
230
+ if (prev && prev.dir !== dir) throw new UsageError(`プロジェクト名「${key}」は別のフォルダで登録済みです: ${prev.dir}`);
231
+ setProjectNode(doc, key, { dir, repos: refName ? { ...prev?.repos, [refName]: root } : (prev?.repos ?? {}) });
232
+ });
233
+
234
+ const agentsFile = ["AGENTS.md", "CLAUDE.md"].find((f) => existsSync(join(root, f)));
235
+ const askAgents = async () =>
236
+ o.agents ??
237
+ (rl ? /^y/i.test(await ask(`${agentsFile ?? "AGENTS.md"} と .claude/skills/・.agents/skills/ に AI 向けの p3 の使い方を置きますか (y/n)`, agentsFile ? "y" : "n")) : false);
238
+
239
+ // 既に作られたフォルダなら参加だけ
240
+ if (joining) {
241
+ // 登録済みのリポジトリでも --agents なら、登録とデータはそのままで AI 向けの使い方だけを置く(あとから置き場所が増えたとき)
242
+ const already = !!registered && (!refName || registered.repos[refName] === root);
243
+ if (already && !o.agents) throw new UsageError(`${key}(${dir})は登録済みです(設定の変更は p3 config。AI 向けの使い方を置くなら --agents)`);
244
+ if (already) return [`登録済みです: ${key} → ${dir}`, ...(await placeAgents(root, o.cwd))].join("\n");
245
+ const addAgents = await askAgents();
246
+ await register();
247
+ return [
248
+ `参加しました: ${key} → ${dir}`,
249
+ refName
250
+ ? ` 参照先 ${refName} ${root}`
251
+ : ` このリポジトリを参照先として登録していません。p3 repo ls で名前を確かめ、p3 repo path <名前> ${root} で登録してください`,
252
+ ...(addAgents ? await placeAgents(root, o.cwd) : []),
253
+ "",
254
+ "次に: p3 request ls / p3 serve",
255
+ ]
256
+ .filter((l, i) => l || i > 1)
257
+ .join("\n");
258
+ }
259
+
260
+ // 既定値: git とリポジトリの中身から推測する
261
+ const docsFound = DOC_CANDIDATES.filter((d) => existsSync(join(root, d)));
262
+ const name = o.name ?? key;
263
+ const description = await ask("何を作っているプロジェクトか(Preflight の前提になります)", o.description ?? "");
264
+ // ドキュメントは本体(最初に読む)の主なフォルダにする。Preflight は評価の前に必要な範囲で読む。
265
+ // フォルダの入口は、その中に README.md / index.md があればそれ(任意)
266
+ const docs = splitList(await ask("最初に読むドキュメント(カンマ区切り。Preflight が評価の前に読みます)", docsFound.join(", ")));
267
+ const map = docs.map((d) => {
268
+ const entry = DOC_ENTRIES.map((e) => `${d}/${e}`).find((e) => existsSync(join(root, e)));
269
+ return { path: d, role: "ドキュメント", ...(entry ? { entry } : {}) };
270
+ });
271
+ const instructions = await ask("Preflight で重視する観点・制約(任意)", o.instructions ?? "");
272
+ const addAgents = await askAgents();
273
+
274
+ const cfg: ProjectConfig = {
275
+ name,
276
+ description,
277
+ // このリポジトリを本体の参照先にする(このマシンのパスは個人設定に持ち、共有するデータには書かない)
278
+ repos: [{ name: refName!, role: "本体", readFirst: true, writable: true, map }],
279
+ milestones: [],
280
+ branchPattern: "req/{id}-{slug}",
281
+ preflight: { instructions },
282
+ };
283
+ await mkdir(join(dir, "requests"), { recursive: true });
284
+ await writeProjectFile(join(dir, "project.yaml"), cfg);
285
+ await writeRepoEntry(join(dir, "project.yaml"), refName!, cfg.repos[0]);
286
+ await register();
287
+
288
+ const agentLines = addAgents ? await placeAgents(root, o.cwd) : [];
289
+ return [
290
+ `作りました: ${key} → ${dir}`,
291
+ ` 参照先 ${refName}(本体) → ${root}`,
292
+ ` 主なフォルダ ${map.map((m) => m.path).join(", ") || "(なし。設定画面で足せます)"}`,
293
+ ` 個人設定 ${userConfigPath()} に登録しました`,
294
+ ...agentLines,
295
+ "",
296
+ "次に: p3 request new \"<やりたいこと>\" --body \"...\" → p3 preflight <要望ID> → p3 serve",
297
+ cfg.description ? "" : "※ description が空です。p3 config set description=\"...\" で設定してください(Preflight の精度に効きます)",
298
+ ]
299
+ .filter((l, i, a) => l !== "" || (i > 0 && a[i - 1] !== ""))
300
+ .join("\n")
301
+ .trimEnd();
302
+ } finally {
303
+ rl?.close();
304
+ }
305
+ }
306
+
307
+ /** p3 project [ls | add <名前> <フォルダ> | rm <名前>]: 個人設定のプロジェクトの一覧・登録・登録解除(データは消さない) */
308
+ export async function projectCommand(
309
+ cwd: string,
310
+ args: string[],
311
+ o: { repo?: string },
312
+ current: string | undefined,
313
+ ): Promise<{ data: unknown; text: string }> {
314
+ const user = await loadUserConfig();
315
+ const [sub = "ls", name, dirRaw] = args;
316
+ if (sub === "ls") {
317
+ const rows = Object.entries(user.projects).map(([n, p]) => ({ name: n, ...p, current: n === current }));
318
+ const w = Math.max(4, ...rows.map((r) => r.name.length));
319
+ return {
320
+ data: rows,
321
+ text: rows.length
322
+ ? rows.map((r) => `${r.current ? "*" : " "} ${r.name.padEnd(w)} ${r.dir}${Object.keys(r.repos).length ? ` (参照先 ${Object.keys(r.repos).join(", ")})` : ""}`).join("\n")
323
+ : "登録済みのプロジェクトはありません。管理したいリポジトリの中で p3 init --project <名前> --dir <フォルダ>",
324
+ };
325
+ }
326
+ if (sub === "add") {
327
+ if (!name || !dirRaw) throw new UsageError("p3 project add <名前> <フォルダ>");
328
+ if (o.repo) throw new UsageError("--repo は使えなくなりました。登録したあと、p3 repo path <参照先の名前> <パス> でこのマシンのパスを登録してください");
329
+ if (!PROJECT_NAME.test(name)) throw new UsageError(`プロジェクト名は英数字と . _ - で: ${name}`);
330
+ const dir = resolvePath(cwd, dirRaw);
331
+ if (!existsSync(join(dir, "project.yaml"))) throw new UsageError(`${dir} はまだ p3 のプロジェクトではありません。作るときは管理したいリポジトリの中で p3 init`);
332
+ const saved = await updateUserConfig((doc, now) => {
333
+ const prev = now.projects[name];
334
+ if (prev && prev.dir !== dir) throw new UsageError(`「${name}」は別のフォルダで登録済みです: ${prev.dir}`);
335
+ const next = { dir, repos: prev?.repos ?? {} };
336
+ setProjectNode(doc, name, next);
337
+ return next;
338
+ });
339
+ return {
340
+ data: { name, ...saved },
341
+ text: `登録しました: ${name} → ${dir}\n 参照先のこのマシンのパスは p3 --project ${name} repo ls で確かめ、p3 repo path <名前> <パス> で登録してください`,
342
+ };
343
+ }
344
+ if (sub === "rm") {
345
+ if (!name) throw new UsageError("p3 project rm <名前>");
346
+ await updateUserConfig((doc, now) => {
347
+ if (!now.projects[name]) throw new UsageError(`登録されていません: ${name}`);
348
+ setProjectNode(doc, name, null);
349
+ });
350
+ return { data: { name }, text: `登録を外しました: ${name}(データのフォルダはそのまま)` };
351
+ }
352
+ throw new UsageError("p3 project [ls | add <名前> <フォルダ> | rm <名前>]");
353
+ }
354
+
355
+ /** 入力されたパス。対話式の入力ではシェルが ~ を展開しないので、ここで展開する */
356
+ export const resolvePath = (cwd: string, p: string) => resolve(cwd, p === "~" ? homedir() : p.startsWith("~/") ? join(homedir(), p.slice(2)) : p);
357
+
358
+ const slugifyName = (s: string) => s.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-._]+|-+$/g, "") || undefined;
359
+
360
+ const CONFIG_KEYS = ["name", "description", "branchPattern", "instructions"] as const;
361
+
362
+ /** p3 config [set key=value ...] */
363
+ export async function config(ws: Workspace, args: string[]): Promise<{ data: unknown; text: string }> {
364
+ if (args[0] === "set") {
365
+ const patch: Partial<ProjectConfig> = {};
366
+ for (const pair of args.slice(1)) {
367
+ const eq = pair.indexOf("=");
368
+ const key = pair.slice(0, eq) as (typeof CONFIG_KEYS)[number];
369
+ const value = pair.slice(eq + 1).trim();
370
+ if (eq < 1 || !CONFIG_KEYS.includes(key)) throw new UsageError(`設定できるキー: ${CONFIG_KEYS.join(", ")}`);
371
+ if (key === "instructions") patch.preflight = { instructions: value };
372
+ else if (key === "branchPattern" && !value.includes("{id}")) throw new UsageError("branchPattern には {id} を含めてください");
373
+ else if (key === "name" && !value) throw new UsageError(`${key} は空にできません`);
374
+ else patch[key] = value;
375
+ }
376
+ if (!Object.keys(patch).length) throw new UsageError("p3 config set キー=値 ...");
377
+ const next = await ws.saveProject(patch);
378
+ const keys = args.slice(1).map((p) => p.slice(0, p.indexOf("=")));
379
+ return { data: next, text: `更新しました: ${keys.join(", ")}` };
380
+ }
381
+ const p = ws.project;
382
+ const text = [
383
+ `name ${p.name}`,
384
+ `description ${p.description || "(なし)"}`,
385
+ `repos ${p.repos.map((r) => r.name).join(", ") || "(なし)"} (p3 repo ls)`,
386
+ `milestones ${p.milestones.map((m) => `${m.id}${m.due ? `(${m.due})` : ""}${m.done ? "[済]" : ""}`).join(", ") || "(なし)"}`,
387
+ `branchPattern ${p.branchPattern}`,
388
+ `instructions ${p.preflight.instructions || "(なし)"}`,
389
+ "",
390
+ `ファイル: ${join(ws.dataDir, "project.yaml")}`,
391
+ ].join("\n");
392
+ return { data: p, text };
393
+ }
394
+
395
+ function splitList(s: string): string[] {
396
+ return s.split(",").map((x) => x.trim()).filter(Boolean);
397
+ }
398
+
399
+ /**
400
+ * p3 repo: Preflight が読む参照先(リポジトリ・フォルダ)。共有の定義(project.yaml の repos)と、このマシンのパス
401
+ * (個人設定の projects.<プロジェクト>.repos)を分けて扱う。
402
+ *
403
+ * ls 一覧(このマシンのパスが無いものは登録の仕方を出す)
404
+ * add <名前> [<パス>] [キー=値 ...] 共有の定義を足す(パスを渡せばこのマシンのパスも登録する)
405
+ * set <名前> キー=値 ... 共有の定義を変える(role readFirst writable)
406
+ * path <名前> <パス> このマシンのパスだけを登録する(ほかの人が足した参照先に)
407
+ * rm <名前> [--local] 共有の定義とこのマシンのパスを消す(--local はこのマシンのパスだけ)
408
+ */
409
+ export async function repoCommand(
410
+ ws: Workspace,
411
+ projectName: string | undefined,
412
+ cwd: string,
413
+ args: string[],
414
+ o: { local?: boolean },
415
+ ): Promise<{ data: unknown; text: string }> {
416
+ const [sub = "ls", name, ...rest] = args;
417
+ const shared = () => ws.project.repos.find((r) => r.name === name);
418
+ const usage = "p3 repo [ls | add <名前> [<パス>] [role=… readFirst=true writable=true] | set <名前> キー=値 … | path <名前> <パス> | rm <名前> [--local]]";
419
+
420
+ const pairs = (list: string[]): RepoPatch => {
421
+ const patch: RepoPatch = {};
422
+ for (const pair of list) {
423
+ const eq = pair.indexOf("=");
424
+ const key = pair.slice(0, eq);
425
+ const value = pair.slice(eq + 1).trim();
426
+ if (key === "role") patch.role = value;
427
+ else if (key === "readFirst" || key === "writable") {
428
+ if (!["true", "false"].includes(value)) throw new UsageError(`${key} は true か false`);
429
+ patch[key] = value === "true";
430
+ } else throw new UsageError(`変えられるキー: role readFirst writable(主なフォルダ map は設定画面か project.yaml で)`);
431
+ }
432
+ return patch;
433
+ };
434
+ /** 共通の操作の失敗は使い方の誤りとして出す */
435
+ const run = async <T>(f: () => Promise<T>): Promise<T> => {
436
+ try {
437
+ return await f();
438
+ } catch (e) {
439
+ if (e instanceof RepoAdminError) throw new UsageError(e.message);
440
+ throw e;
441
+ }
442
+ };
443
+ const folder = (raw: string) => resolvePath(cwd, raw);
444
+
445
+ if (sub === "ls") {
446
+ const refs = ws.refs();
447
+ const rows = refs.map((r) => ({ ...r, local: r.local ?? null }));
448
+ const text = [
449
+ ...(!refs.length ? ["(参照先はまだありません。足すときは p3 repo add <名前> <パス> role=…)"] : []),
450
+ ...refs.map((r) => {
451
+ const flags = [r.readFirst && "最初に読む", r.writable && "作業先候補"].filter(Boolean).join("・");
452
+ const where =
453
+ r.status === "ok" ? r.local : r.status === "unregistered" ? `未登録 → p3 repo path ${r.name} <このマシンのパス>` : `${r.reason}`;
454
+ return `${r.name}${r.role ? `(${r.role})` : ""}${flags ? ` [${flags}]` : ""} /workspace/${r.mount}\n ${where}${
455
+ r.map.length ? `\n 主なフォルダ: ${r.map.map((m) => (m.entry ? `${m.path}(入口 ${m.entry})` : m.path)).join(", ")}` : ""
456
+ }`;
457
+ }),
458
+ ].join("\n");
459
+ return { data: rows, text };
460
+ }
461
+ if (!name) throw new UsageError(usage);
462
+ const problem = repoNameProblem(name);
463
+ if (problem && sub !== "rm") throw new UsageError(`参照先の名前: ${problem}`);
464
+
465
+ if (sub === "add") {
466
+ const maybePath = rest[0] && !rest[0].includes("=") ? rest[0] : undefined;
467
+ const patch = pairs(maybePath ? rest.slice(1) : rest);
468
+ if (shared()) throw new UsageError(`「${name}」は既にあります。変えるときは p3 repo set ${name} キー=値、このマシンのパスは p3 repo path ${name} <パス>`);
469
+ const path = maybePath ? folder(maybePath) : undefined;
470
+ if (path) await run(async () => checkFolder(path));
471
+ const entry = await run(() => addRepo(ws, name, patch));
472
+ if (path) await run(() => setLocalRepoPath(ws, projectName, name, path));
473
+ return {
474
+ data: { ...entry, local: path ?? null },
475
+ text: `参照先を足しました: ${name}${entry.role ? `(${entry.role})` : ""}${path ? ` → ${path}` : `(このマシンのパスは未登録: p3 repo path ${name} <パス>)`}`,
476
+ };
477
+ }
478
+ if (sub === "set") {
479
+ if (!shared()) throw new UsageError(`「${name}」はありません。足すときは p3 repo add ${name} <パス>`);
480
+ if (!rest.length) throw new UsageError("キー=値 を指定してください(role readFirst writable)");
481
+ const next = await run(() => updateRepo(ws, name, pairs(rest)));
482
+ return { data: next, text: `参照先を変えました: ${name}` };
483
+ }
484
+ if (sub === "path") {
485
+ if (!shared()) throw new UsageError(`「${name}」は共有の参照先にありません(p3 repo ls)。足すときは p3 repo add ${name} <パス>`);
486
+ if (!rest[0]) throw new UsageError(`p3 repo path ${name} <このマシンのパス>`);
487
+ const path = folder(rest[0]);
488
+ await run(() => setLocalRepoPath(ws, projectName, name, path));
489
+ return { data: { name, local: path }, text: `このマシンのパスを登録しました: ${name} → ${path}(共有の定義は変えていません)` };
490
+ }
491
+ if (sub === "rm") {
492
+ if (o.local) {
493
+ await run(() => setLocalRepoPath(ws, projectName, name, null));
494
+ return { data: { name, local: null }, text: `このマシンのパスを外しました: ${name}(共有の定義は残しています。ほかの人には影響しません)` };
495
+ }
496
+ if (!shared()) throw new UsageError(`「${name}」は共有の参照先にありません。このマシンのパスだけを外すときは --local`);
497
+ await run(() => removeRepo(ws, projectName, name));
498
+ return { data: { name }, text: `参照先を消しました: ${name}(共有の定義。ほかの人の Preflight でも読まなくなります。ファイルやフォルダは消していません)` };
499
+ }
500
+ throw new UsageError(usage);
501
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * 読むだけの操作か(データのフォルダ・個人設定・ファイルを変えず、外の生成も始めない)。
3
+ * 登録が1つだけでプロジェクトが決まったとき(via: only)に、読むだけなら警告して続け、ほかは止めるために使う(main.ts)。
4
+ * 載っていない操作(新しいコマンド・知らないサブコマンド)は書く操作として扱う。サブコマンドの省略は各コマンドの既定に合わせる。
5
+ */
6
+ export function readsOnly(cmd: string, args: string[]): boolean {
7
+ const sub = args[0];
8
+ switch (cmd) {
9
+ case "whoami":
10
+ case "progress":
11
+ case "ls":
12
+ case "list":
13
+ case "show":
14
+ case "find":
15
+ case "resolve":
16
+ case "notes":
17
+ case "drafts":
18
+ return true;
19
+ case "request":
20
+ case "req":
21
+ return sub === "ls" || sub === "list" || sub === "show";
22
+ case "milestone":
23
+ case "milestones":
24
+ return sub === undefined || sub === "ls" || sub === "list";
25
+ case "config":
26
+ return sub === undefined;
27
+ case "repo":
28
+ case "attach":
29
+ return sub === undefined || sub === "ls";
30
+ case "release-notes":
31
+ case "release-note":
32
+ return sub === undefined || sub === "ls" || sub === "list" || sub === "show" || sub === "export";
33
+ default:
34
+ return false;
35
+ }
36
+ }