@infodb/p3 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +56 -2
- package/bin/p3.mjs +18 -0
- package/dist/web/apple-touch-icon.png +0 -0
- package/dist/web/assets/Outputs-Ni3pNuGU.js +1 -0
- package/dist/web/assets/RequestStatus-K8TZwpur.js +1 -0
- package/dist/web/assets/TagInput-BICKVH2x.js +1 -0
- package/dist/web/assets/TaskDrawer-BkDIstIN.js +3 -0
- package/dist/web/assets/_requestId-B5O_ytaq.js +1 -0
- package/dist/web/assets/_requestId-C66puEMO.js +30 -0
- package/dist/web/assets/action-CMjATXqv.js +1 -0
- package/dist/web/assets/board-CbfDjkls.js +1 -0
- package/dist/web/assets/copy-B1ZbihKL.js +2 -0
- package/dist/web/assets/done-CPQbCFHg.js +1 -0
- package/dist/web/assets/draft-dT3gLDIt.js +1 -0
- package/dist/web/assets/format-DuK6P1hb.js +1 -0
- package/dist/web/assets/index-BUcs2J6N.js +12 -0
- package/dist/web/assets/index-C3DkqwJ9.css +2 -0
- package/dist/web/assets/link-_s8ndNKS.js +1 -0
- package/dist/web/assets/new-T60RB7de.js +1 -0
- package/dist/web/assets/preload-helper-dXqN7N-I.js +1 -0
- package/dist/web/assets/release-notes-DxrPhDbt.js +3 -0
- package/dist/web/assets/requestData-D8ZiSZss.js +1 -0
- package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
- package/dist/web/assets/routes-D9ZxXoLk.js +2 -0
- package/dist/web/assets/search-CJ8MBKTz.js +1 -0
- package/dist/web/assets/settings-DsHVyqzJ.js +1 -0
- package/dist/web/assets/supersede-CLXlhCq0.js +1 -0
- package/dist/web/assets/ui-Cvke4y4X.js +1 -0
- package/dist/web/favicon.ico +0 -0
- package/dist/web/favicon.svg +12 -0
- package/dist/web/index.html +23 -0
- package/docs/architecture.md +591 -0
- package/docs/chatgpt-sign-in.md +163 -0
- package/docs/development.md +194 -0
- package/docs/how-to-use.md +524 -0
- package/docs/installation.md +284 -0
- package/docs/publishing.md +65 -0
- package/package.json +86 -3
- package/skills/p3/SKILL.md +95 -0
- package/src/cli/args.ts +179 -0
- package/src/cli/chatgpt.ts +74 -0
- package/src/cli/codex.ts +28 -0
- package/src/cli/format.ts +9 -0
- package/src/cli/help.ts +99 -0
- package/src/cli/main.ts +267 -0
- package/src/cli/output.ts +99 -0
- package/src/cli/preflightCommands.ts +237 -0
- package/src/cli/project.ts +508 -0
- package/src/cli/readOnly.ts +36 -0
- package/src/cli/releaseNotesCommands.ts +139 -0
- package/src/cli/render.ts +60 -0
- package/src/cli/requestCommands.ts +170 -0
- package/src/cli/showView.ts +110 -0
- package/src/cli/taskCommands.ts +167 -0
- package/src/cli/userConfig.ts +58 -0
- package/src/core/chatgpt.ts +33 -0
- package/src/core/context.ts +57 -0
- package/src/core/machineSettings.ts +207 -0
- package/src/core/machineSettingsEdit.ts +156 -0
- package/src/core/ops.ts +114 -0
- package/src/core/preflight/carryover.ts +133 -0
- package/src/core/preflight/codexEngine.ts +702 -0
- package/src/core/preflight/codexImage.ts +98 -0
- package/src/core/preflight/diagnose.ts +124 -0
- package/src/core/preflight/engine.ts +92 -0
- package/src/core/preflight/input.ts +65 -0
- package/src/core/preflight/launch.ts +86 -0
- package/src/core/preflight/launcher.mjs +75 -0
- package/src/core/preflight/mock-ui.html +24 -0
- package/src/core/preflight/mock-ui.png +0 -0
- package/src/core/preflight/mockEngine.ts +145 -0
- package/src/core/preflight/render-image/Dockerfile +23 -0
- package/src/core/preflight/render-image/render.mjs +53 -0
- package/src/core/preflight/render.ts +336 -0
- package/src/core/preflight/service.ts +690 -0
- package/src/core/preflight/uiMaterials.ts +272 -0
- package/src/core/preflight/uiRender.ts +84 -0
- package/src/core/preflight/wireframe.ts +69 -0
- package/src/core/preflight/xlsx.ts +328 -0
- package/src/core/redact.ts +31 -0
- package/src/core/releaseNotes/generate.ts +271 -0
- package/src/core/releaseNotes/material.ts +114 -0
- package/src/core/releaseNotes/mockSummarizer.ts +28 -0
- package/src/core/releaseNotes/service.ts +106 -0
- package/src/core/releaseNotes/store.ts +216 -0
- package/src/core/repoAdmin.ts +81 -0
- package/src/core/repoRefs.ts +90 -0
- package/src/core/requestOps.ts +140 -0
- package/src/core/requestStatus.ts +58 -0
- package/src/core/store/attachments.ts +228 -0
- package/src/core/store/collection.ts +282 -0
- package/src/core/store/frontmatter.ts +22 -0
- package/src/core/store/fsutil.ts +90 -0
- package/src/core/store/locate.ts +181 -0
- package/src/core/store/normalize.ts +155 -0
- package/src/core/store/noteStore.ts +56 -0
- package/src/core/store/preflightStore.ts +136 -0
- package/src/core/store/projectFile.ts +101 -0
- package/src/core/store/workspace.ts +328 -0
- package/src/core/supersede.ts +74 -0
- package/src/core/userConfig.ts +180 -0
- package/src/core/userTheme.ts +22 -0
- package/src/core/workTargets.ts +120 -0
- package/src/server/api/chatgptRoutes.ts +48 -0
- package/src/server/api/local.ts +33 -0
- package/src/server/api/manifest.ts +119 -0
- package/src/server/api/releaseNoteRoutes.ts +78 -0
- package/src/server/api/repoRoutes.ts +67 -0
- package/src/server/api/routes.ts +374 -0
- package/src/server/api/userThemeRoutes.ts +62 -0
- package/src/server/server.ts +49 -0
- package/src/shared/dates.ts +12 -0
- package/src/shared/preflightInput.ts +27 -0
- package/src/shared/refs.ts +55 -0
- package/src/shared/repos.ts +113 -0
- package/src/shared/scopeView.ts +48 -0
- package/src/shared/tags.ts +27 -0
- package/src/shared/types.ts +700 -0
- package/src/shared/workTarget.ts +44 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { access, mkdir, readFile, readdir, rename } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { parseFrontmatter, stringifyFrontmatter } from "./frontmatter.ts";
|
|
4
|
+
import { createExclusive, nowIso, writeFileAtomic } from "./fsutil.ts";
|
|
5
|
+
|
|
6
|
+
export interface Entity {
|
|
7
|
+
id: string;
|
|
8
|
+
rev: number;
|
|
9
|
+
createdAt: string;
|
|
10
|
+
updatedAt: string;
|
|
11
|
+
updatedBy?: string;
|
|
12
|
+
body: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class ConflictError extends Error {
|
|
16
|
+
constructor(
|
|
17
|
+
public id: string,
|
|
18
|
+
public expected: number,
|
|
19
|
+
public actual: number,
|
|
20
|
+
) {
|
|
21
|
+
super(`${id}: rev conflict (expected ${expected}, actual ${actual})`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class NotFoundError extends Error {
|
|
26
|
+
constructor(public id: string) {
|
|
27
|
+
super(`${id} not found`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** エンティティをどこに置き、どう採番するか */
|
|
32
|
+
export interface Layout {
|
|
33
|
+
/** エンティティのファイル */
|
|
34
|
+
path(id: string): string;
|
|
35
|
+
/** ディスク上にある ID */
|
|
36
|
+
scan(): Promise<string[]>;
|
|
37
|
+
/** 採番で使わない ID(アーカイブ済みなど。読み込みの対象ではない) */
|
|
38
|
+
reserved?(): Promise<string[]>;
|
|
39
|
+
/** 新しい ID。attempt は衝突してやり直した回数 */
|
|
40
|
+
nextId(existing: string[], attempt: number): string;
|
|
41
|
+
/** アーカイブ: 移す元と先 */
|
|
42
|
+
archive(id: string): { from: string; to: string };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface CollectionOptions<T extends Entity> {
|
|
46
|
+
layout: Layout;
|
|
47
|
+
normalize: (data: Record<string, unknown>, body: string, id: string) => T;
|
|
48
|
+
/** frontmatter に書くキー順 */
|
|
49
|
+
keyOrder: (keyof T)[];
|
|
50
|
+
/** ファイルに書かないキー(場所から決まるもの) */
|
|
51
|
+
derived?: (keyof T)[];
|
|
52
|
+
/** 書く直前の加工(ステータスを変えた日時の記録など)。prev は作成時 undefined */
|
|
53
|
+
beforeWrite?: (prev: T | undefined, next: T) => T;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 全件の読み込みの準備(prepareLoad)。commit で読んだ結果を公開し、abort で捨てる */
|
|
57
|
+
export interface PreparedLoad {
|
|
58
|
+
/** 読めた ID(読めなかったものは含まない) */
|
|
59
|
+
ids: string[];
|
|
60
|
+
commit(): void;
|
|
61
|
+
abort(): void;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
type ReadResult<T> = { item: T } | { error: string } | { missing: true };
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 1エンティティ = 1 Markdown ファイル(YAML frontmatter + 本文)のコレクション。
|
|
68
|
+
* メモリ上にキャッシュし、ファイル変更(人手・AI・Codex・git pull)は reload() で取り込む。
|
|
69
|
+
*
|
|
70
|
+
* 全件の読み込み(load / prepareLoad)は、読み終えてから入れ替える(読んでいる途中の空や半分の状態を見せない)。
|
|
71
|
+
* 読み込みの間に作成・更新・アーカイブ・1件の読み直しがあった ID は、読んだ結果ではなくその時点の状態を残す
|
|
72
|
+
* (読み込みが先に読んだ古い内容で、後の書き込みを戻さない)。
|
|
73
|
+
*/
|
|
74
|
+
export class MarkdownCollection<T extends Entity> {
|
|
75
|
+
private items = new Map<string, T>();
|
|
76
|
+
/** 読めないファイル。壊れたファイルで全体が落ちないようにする */
|
|
77
|
+
readonly errors = new Map<string, string>();
|
|
78
|
+
private layout: Layout;
|
|
79
|
+
/** 進行中の全件の読み込みごとの「その間に変わった ID」 */
|
|
80
|
+
private loads = new Set<Set<string>>();
|
|
81
|
+
|
|
82
|
+
constructor(private opts: CollectionOptions<T>) {
|
|
83
|
+
this.layout = opts.layout;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async load(): Promise<void> {
|
|
87
|
+
(await this.prepareLoad()).commit();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** ディスクから全件を読む。公開は commit でまとめて(同期で)行う */
|
|
91
|
+
async prepareLoad(): Promise<PreparedLoad> {
|
|
92
|
+
const touched = new Set<string>();
|
|
93
|
+
this.loads.add(touched);
|
|
94
|
+
const items = new Map<string, T>();
|
|
95
|
+
const errors = new Map<string, string>();
|
|
96
|
+
try {
|
|
97
|
+
for (const id of await this.layout.scan()) {
|
|
98
|
+
const r = await this.read(id);
|
|
99
|
+
if ("item" in r) items.set(id, r.item);
|
|
100
|
+
else if ("error" in r) errors.set(id, r.error);
|
|
101
|
+
}
|
|
102
|
+
} catch (e) {
|
|
103
|
+
this.loads.delete(touched);
|
|
104
|
+
throw e;
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
ids: [...items.keys()],
|
|
108
|
+
commit: () => {
|
|
109
|
+
if (!this.loads.delete(touched)) return;
|
|
110
|
+
for (const id of touched) {
|
|
111
|
+
const live = this.items.get(id);
|
|
112
|
+
if (live) items.set(id, live);
|
|
113
|
+
else items.delete(id);
|
|
114
|
+
const err = this.errors.get(id);
|
|
115
|
+
if (err !== undefined) errors.set(id, err);
|
|
116
|
+
else errors.delete(id);
|
|
117
|
+
}
|
|
118
|
+
this.items = items;
|
|
119
|
+
this.errors.clear();
|
|
120
|
+
for (const [id, e] of errors) this.errors.set(id, e);
|
|
121
|
+
},
|
|
122
|
+
abort: () => void this.loads.delete(touched),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* 1件をディスクから読むだけ(読み込んだ内容・索引・変更通知には触れない)。監視に頼らずに今のファイルを確かめるため。
|
|
128
|
+
* 無ければ { missing }、読めなければ { error }
|
|
129
|
+
*/
|
|
130
|
+
peek(id: string): Promise<ReadResult<T>> {
|
|
131
|
+
return this.read(id);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private async read(id: string): Promise<ReadResult<T>> {
|
|
135
|
+
try {
|
|
136
|
+
const { data, body } = parseFrontmatter(await readFile(this.layout.path(id), "utf8"));
|
|
137
|
+
return { item: this.opts.normalize(data, body, id) };
|
|
138
|
+
} catch (e) {
|
|
139
|
+
return (e as NodeJS.ErrnoException).code === "ENOENT" ? { missing: true } : { error: String(e) };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private touch(id: string) {
|
|
144
|
+
for (const t of this.loads) t.add(id);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private put(id: string, item: T) {
|
|
148
|
+
this.items.set(id, item);
|
|
149
|
+
this.touch(id);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 1件を読み直す。消えていれば除く */
|
|
153
|
+
async reload(id: string): Promise<void> {
|
|
154
|
+
const r = await this.read(id);
|
|
155
|
+
if ("item" in r) {
|
|
156
|
+
this.put(id, r.item);
|
|
157
|
+
this.errors.delete(id);
|
|
158
|
+
} else {
|
|
159
|
+
this.items.delete(id);
|
|
160
|
+
if ("error" in r) this.errors.set(id, r.error);
|
|
161
|
+
else this.errors.delete(id);
|
|
162
|
+
this.touch(id);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
list(): T[] {
|
|
167
|
+
return [...this.items.values()].sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true }));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
get(id: string): T | undefined {
|
|
171
|
+
return this.items.get(id);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
require(id: string): T {
|
|
175
|
+
const v = this.items.get(id);
|
|
176
|
+
if (!v) throw new NotFoundError(id);
|
|
177
|
+
return v;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
path(id: string) {
|
|
181
|
+
return this.layout.path(id);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
private serialize(item: T): string {
|
|
185
|
+
const { body, ...rest } = item;
|
|
186
|
+
const skip = new Set<string>(["body", ...((this.opts.derived ?? []) as string[])]);
|
|
187
|
+
const ordered: Record<string, unknown> = {};
|
|
188
|
+
for (const k of this.opts.keyOrder) if (!skip.has(k as string)) ordered[k as string] = (rest as Record<string, unknown>)[k as string];
|
|
189
|
+
for (const [k, v] of Object.entries(rest)) if (!(k in ordered) && !skip.has(k)) ordered[k] = v;
|
|
190
|
+
return stringifyFrontmatter(ordered, body);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** 作る。省いた項目は normalize の既定値になる */
|
|
194
|
+
async create(input: Partial<Omit<T, "id" | "rev" | "createdAt" | "updatedAt">>, actor?: string): Promise<T> {
|
|
195
|
+
// アーカイブ済みの ID も使わない(アーカイブしたタスクへの関係が新しいタスクを指さないように)
|
|
196
|
+
const existing = [...new Set([...this.items.keys(), ...(await this.layout.scan()), ...((await this.layout.reserved?.()) ?? [])])];
|
|
197
|
+
// 別のプロセス(CLI・AI)と同時に作っても、排他作成で衝突を検出して次の ID にする
|
|
198
|
+
for (let attempt = 0; ; attempt++) {
|
|
199
|
+
const id = this.layout.nextId(existing, attempt);
|
|
200
|
+
const now = nowIso();
|
|
201
|
+
const item = this.opts.normalize({}, "", id);
|
|
202
|
+
Object.assign(item, input, { id, rev: 1, createdAt: now, updatedAt: now, updatedBy: actor });
|
|
203
|
+
const final = this.opts.beforeWrite?.(undefined, item) ?? item;
|
|
204
|
+
Object.assign(item, final);
|
|
205
|
+
if (await createExclusive(this.layout.path(id), this.serialize(item))) {
|
|
206
|
+
this.put(id, item);
|
|
207
|
+
return item;
|
|
208
|
+
}
|
|
209
|
+
existing.push(id);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 部分更新。expectedRev を渡すと楽観ロック(AI が古い状態を元に上書きするのを防ぐ)。
|
|
215
|
+
*/
|
|
216
|
+
async update(id: string, patch: Partial<T>, opts: { expectedRev?: number; actor?: string } = {}): Promise<T> {
|
|
217
|
+
// 外部での編集を取りこぼさないよう、更新の直前にディスクから読み直す
|
|
218
|
+
await this.reload(id);
|
|
219
|
+
const cur = this.require(id);
|
|
220
|
+
if (opts.expectedRev !== undefined && opts.expectedRev !== cur.rev) {
|
|
221
|
+
throw new ConflictError(id, opts.expectedRev, cur.rev);
|
|
222
|
+
}
|
|
223
|
+
const merged = {
|
|
224
|
+
...cur,
|
|
225
|
+
...patch,
|
|
226
|
+
id,
|
|
227
|
+
rev: cur.rev + 1,
|
|
228
|
+
createdAt: cur.createdAt,
|
|
229
|
+
updatedAt: nowIso(),
|
|
230
|
+
updatedBy: opts.actor ?? cur.updatedBy,
|
|
231
|
+
} as T;
|
|
232
|
+
const next = this.opts.beforeWrite?.(cur, merged) ?? merged;
|
|
233
|
+
await writeFileAtomic(this.layout.path(id), this.serialize(next));
|
|
234
|
+
this.put(id, next);
|
|
235
|
+
return next;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 物理削除はせず .archive/ へ移す */
|
|
239
|
+
async archive(id: string): Promise<void> {
|
|
240
|
+
this.require(id);
|
|
241
|
+
const { from, to } = this.layout.archive(id);
|
|
242
|
+
// 既にアーカイブに同じ ID があれば上書きしない(rename は黙って置き換えるので先に確かめる)
|
|
243
|
+
if (await access(to).then(() => true, () => false)) throw new Error(`${id} は既にアーカイブにあります(${to})。上書きしません`);
|
|
244
|
+
await mkdir(dirname(to), { recursive: true });
|
|
245
|
+
await rename(from, to);
|
|
246
|
+
this.items.delete(id);
|
|
247
|
+
this.touch(id);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** ディレクトリの中の "<ID>.md"(タスク)。ID は要望の中の連番 */
|
|
252
|
+
export function fileLayout(dir: string, idPattern: RegExp, format: (n: number) => string): Layout {
|
|
253
|
+
/** ディレクトリの中の有効な名前の ID(中身は読まないので、壊れたファイルでも ID は予約される) */
|
|
254
|
+
const ids = async (d: string) =>
|
|
255
|
+
(await readdir(d).catch(() => [] as string[]))
|
|
256
|
+
.filter((f) => f.endsWith(".md"))
|
|
257
|
+
.map((f) => f.slice(0, -3))
|
|
258
|
+
.filter((id) => idPattern.test(id));
|
|
259
|
+
return {
|
|
260
|
+
path: (id) => join(dir, `${id}.md`),
|
|
261
|
+
scan: () => ids(dir),
|
|
262
|
+
reserved: () => ids(join(dir, ".archive")),
|
|
263
|
+
nextId: (existing, attempt) => {
|
|
264
|
+
const nums = existing.map((id) => Number(/\d+/.exec(id)?.[0] ?? 0));
|
|
265
|
+
return format((nums.length ? Math.max(...nums) : 0) + 1 + attempt);
|
|
266
|
+
},
|
|
267
|
+
archive: (id) => ({ from: join(dir, `${id}.md`), to: join(dir, ".archive", `${id}.md`) }),
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** "<ID>/<file>"(要望)。フォルダごと1件で、ID は新しく作る */
|
|
272
|
+
export function folderLayout(dir: string, file: string, idPattern: RegExp, newId: () => string): Layout {
|
|
273
|
+
return {
|
|
274
|
+
path: (id) => join(dir, id, file),
|
|
275
|
+
scan: async () =>
|
|
276
|
+
(await readdir(dir, { withFileTypes: true }).catch(() => []))
|
|
277
|
+
.filter((d) => d.isDirectory() && idPattern.test(d.name))
|
|
278
|
+
.map((d) => d.name),
|
|
279
|
+
nextId: () => newId(),
|
|
280
|
+
archive: (id) => ({ from: join(dir, id), to: join(dir, ".archive", id) }),
|
|
281
|
+
};
|
|
282
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import YAML from "yaml";
|
|
2
|
+
|
|
3
|
+
const FENCE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
|
|
4
|
+
|
|
5
|
+
/** `---\nyaml\n---\nbody` 形式を分解する。frontmatter が無ければ空オブジェクト。 */
|
|
6
|
+
export function parseFrontmatter(text: string): { data: Record<string, unknown>; body: string } {
|
|
7
|
+
const m = FENCE.exec(text);
|
|
8
|
+
if (!m) return { data: {}, body: text };
|
|
9
|
+
const data = (YAML.parse(m[1]) ?? {}) as Record<string, unknown>;
|
|
10
|
+
// stringify は frontmatter と本文の間に空行を1つ入れるので、それを取り除く
|
|
11
|
+
return { data, body: text.slice(m[0].length).replace(/^\r?\n/, "") };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function stringifyFrontmatter(data: Record<string, unknown>, body: string): string {
|
|
15
|
+
// undefined / 空配列は書かない(差分を小さく、人が読みやすく保つ)
|
|
16
|
+
const clean = Object.fromEntries(
|
|
17
|
+
Object.entries(data).filter(([, v]) => v !== undefined && !(Array.isArray(v) && v.length === 0)),
|
|
18
|
+
);
|
|
19
|
+
const yaml = YAML.stringify(clean, { lineWidth: 0 }).trimEnd();
|
|
20
|
+
const text = body.trim();
|
|
21
|
+
return `---\n${yaml}\n---\n${text ? `\n${text}\n` : ""}`;
|
|
22
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
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
|
+
|
|
5
|
+
/** tmp に書いてから rename する。外部エディタ/AI が途中状態を読まないように。 */
|
|
6
|
+
export async function writeFileAtomic(path: string, content: string): Promise<void> {
|
|
7
|
+
await mkdir(dirname(path), { recursive: true });
|
|
8
|
+
const tmp = `${path}.${randomBytes(4).toString("hex")}.tmp`;
|
|
9
|
+
await writeFile(tmp, content, "utf8");
|
|
10
|
+
await rename(tmp, path);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* ロックのファイル(O_EXCL で作る)で、同じマシンの別のプロセス(CLI・serve)と処理を1つずつにする。
|
|
15
|
+
* 取れなければ少し待つ。古いロック(staleMs より前)は落ちたプロセスのものとして取り直す。
|
|
16
|
+
*/
|
|
17
|
+
export async function withFileLock<T>(
|
|
18
|
+
lock: string,
|
|
19
|
+
fn: () => Promise<T>,
|
|
20
|
+
opts: { timeoutMs?: number; staleMs?: number; busyMessage?: string; mode?: number } = {},
|
|
21
|
+
): Promise<T> {
|
|
22
|
+
const { timeoutMs = 30_000, staleMs = 60_000, busyMessage = `${lock} を待ちきれませんでした(別のプロセスが使っています)` } = opts;
|
|
23
|
+
await mkdir(dirname(lock), { recursive: true, mode: 0o700 });
|
|
24
|
+
const until = Date.now() + timeoutMs;
|
|
25
|
+
for (;;) {
|
|
26
|
+
try {
|
|
27
|
+
const fh = await open(lock, "wx", opts.mode ?? 0o600);
|
|
28
|
+
await fh.writeFile(String(process.pid));
|
|
29
|
+
await fh.close();
|
|
30
|
+
break;
|
|
31
|
+
} catch (e) {
|
|
32
|
+
if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
|
|
33
|
+
const st = await stat(lock).catch(() => undefined);
|
|
34
|
+
if (st && Date.now() - st.mtimeMs > staleMs) {
|
|
35
|
+
await unlink(lock).catch(() => {});
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (Date.now() > until) throw new Error(busyMessage);
|
|
39
|
+
await new Promise((r) => setTimeout(r, 20 + Math.random() * 80));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
return await fn();
|
|
44
|
+
} finally {
|
|
45
|
+
await unlink(lock).catch(() => {});
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 既に存在する場合は false を返す(ID 採番の競合検出用) */
|
|
50
|
+
export async function createExclusive(path: string, content: string): Promise<boolean> {
|
|
51
|
+
await mkdir(dirname(path), { recursive: true });
|
|
52
|
+
try {
|
|
53
|
+
const fh = await open(path, "wx");
|
|
54
|
+
await fh.writeFile(content, "utf8");
|
|
55
|
+
await fh.close();
|
|
56
|
+
return true;
|
|
57
|
+
} catch (e) {
|
|
58
|
+
if ((e as NodeJS.ErrnoException).code === "EEXIST") return false;
|
|
59
|
+
throw e;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const nowIso = () => new Date().toISOString();
|
|
64
|
+
|
|
65
|
+
export function slugify(s: string): string {
|
|
66
|
+
return (
|
|
67
|
+
s
|
|
68
|
+
.toLowerCase()
|
|
69
|
+
.normalize("NFKC")
|
|
70
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
71
|
+
.replace(/^-+|-+$/g, "")
|
|
72
|
+
.slice(0, 40)
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const BASE32 = "0123456789abcdefghjkmnpqrstvwxyz"; // Crockford(i l o u を除く)
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 要望の ID(= フォルダ名)。作成日 + 乱数5文字(例: 261009-k7m3x)。
|
|
80
|
+
* 時刻順に並び、人が読み書きでき、複数人が同時に作っても実用上衝突しない(1日あたり約3,300万通り)。
|
|
81
|
+
* タイトルは後から変わるので含めない。
|
|
82
|
+
*/
|
|
83
|
+
export function newRequestId(now = new Date()): string {
|
|
84
|
+
// 作った人の日付(ローカル時刻)で付ける
|
|
85
|
+
const p2 = (n: number) => String(n).padStart(2, "0");
|
|
86
|
+
const d = `${p2(now.getFullYear() % 100)}${p2(now.getMonth() + 1)}${p2(now.getDate())}`;
|
|
87
|
+
let rand = "";
|
|
88
|
+
for (let i = 0; i < 5; i++) rand += BASE32[randomInt(32)];
|
|
89
|
+
return `${d}-${rand}`;
|
|
90
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
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
|
+
import type { UserConfig } from "../userConfig.ts";
|
|
6
|
+
|
|
7
|
+
/** p3 init がデータを置く既定のフォルダ名(リポジトリのルートの直下) */
|
|
8
|
+
export const DATA_DIR_NAME = ".p3";
|
|
9
|
+
|
|
10
|
+
export interface ResolvedProject {
|
|
11
|
+
/** 個人設定に登録したプロジェクト名(登録していないフォルダを --dir で指したときは無い) */
|
|
12
|
+
name?: string;
|
|
13
|
+
dataDir: string;
|
|
14
|
+
/** 個人設定の参照先の名前 → このマシンのパス(Preflight が読む。全部) */
|
|
15
|
+
repos: Record<string, string>;
|
|
16
|
+
/** どうやって決まったか */
|
|
17
|
+
via: "dir" | "project" | "cwd" | "legacy" | "only";
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** プロジェクトの決まり方の説明(whoami の表)。cwd 以外は今いる場所で決まっていない */
|
|
21
|
+
export const VIA_LABEL: Record<ResolvedProject["via"], string> = {
|
|
22
|
+
dir: "--dir で指定",
|
|
23
|
+
project: "--project で指定",
|
|
24
|
+
cwd: "今いる場所",
|
|
25
|
+
legacy: "リポジトリの中の .p3/",
|
|
26
|
+
only: "登録が1つだけ。今いる場所では決まっていない",
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** 操作するプロジェクトが決まらない(次に何をすればよいかをメッセージに含める) */
|
|
30
|
+
export class ProjectNotResolvedError extends Error {}
|
|
31
|
+
|
|
32
|
+
/** データのフォルダが無い・project.yaml が無い・読めない(次にすることをメッセージに含める)。ファイルは何も変えていない */
|
|
33
|
+
export class DataDirError extends Error {}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* データのフォルダとその project.yaml があるかを確かめる(プロジェクトを開く前。CLI と serve の共通の入口 openProject から)。
|
|
37
|
+
* 無いのに空のプロジェクトとして続けると、書く操作がフォルダを新しく作って別の場所に書いてしまう(移した・共有ドライブが
|
|
38
|
+
* つながっていない・パスの誤り)。無い(ENOENT)と読めない(権限・入出力)は分けて伝える。フォルダもファイルも作らない。
|
|
39
|
+
* requests/ は無くてよい(作ったばかりのプロジェクト)
|
|
40
|
+
*/
|
|
41
|
+
export async function checkDataDir(dataDir: string, projectName?: string): Promise<void> {
|
|
42
|
+
const yaml = join(dataDir, "project.yaml");
|
|
43
|
+
const problem = async (): Promise<string | undefined> => {
|
|
44
|
+
const dir = await stat(dataDir).catch((e: NodeJS.ErrnoException) => e);
|
|
45
|
+
if (dir instanceof Error) {
|
|
46
|
+
return dir.code === "ENOENT" ? `データのフォルダがありません: ${dataDir}` : `データのフォルダを読めません: ${dataDir}(${dir.code ?? dir.message})`;
|
|
47
|
+
}
|
|
48
|
+
if (!dir.isDirectory()) return `データのフォルダがフォルダではありません: ${dataDir}`;
|
|
49
|
+
const file = await stat(yaml).catch((e: NodeJS.ErrnoException) => e);
|
|
50
|
+
if (file instanceof Error) {
|
|
51
|
+
return file.code === "ENOENT" ? `データのフォルダに project.yaml がありません: ${yaml}` : `project.yaml を読めません: ${yaml}(${file.code ?? file.message})`;
|
|
52
|
+
}
|
|
53
|
+
if (!file.isFile()) return `project.yaml がファイルではありません: ${yaml}`;
|
|
54
|
+
return undefined;
|
|
55
|
+
};
|
|
56
|
+
const head = await problem();
|
|
57
|
+
if (!head) return;
|
|
58
|
+
const name = projectName ?? "<名前>";
|
|
59
|
+
throw new DataDirError(
|
|
60
|
+
[
|
|
61
|
+
head,
|
|
62
|
+
projectName ? ` (個人設定のプロジェクト「${projectName}」の登録先)` : "",
|
|
63
|
+
" 既にあるデータなら: パスの誤り・フォルダの移動・共有ドライブ(同期するフォルダ)がつながっているかを確かめる",
|
|
64
|
+
projectName
|
|
65
|
+
? ` 登録の場所を直すとき: p3 project ls で確かめ、p3 project rm ${name} → p3 project add ${name} <正しいフォルダ>(rm はデータを消さない)`
|
|
66
|
+
: " --dir で指すときは、project.yaml のあるフォルダを指す",
|
|
67
|
+
` 新しく作るなら: 管理したいリポジトリの中で p3 init --project ${name} --dir <フォルダ>`,
|
|
68
|
+
]
|
|
69
|
+
.filter(Boolean)
|
|
70
|
+
.join("\n"),
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 登録が1つだけで決まった(via: only)ときの案内。今いる場所とは関係なく決まるので、p3 を使わないフォルダでも当たる。
|
|
76
|
+
* 変える操作は止め(write)、読むだけの操作は警告して続ける。どちらも、プロジェクトを明示する方法と移る先を示す
|
|
77
|
+
*/
|
|
78
|
+
export function onlyRegistrationNotice(p: ResolvedProject, write: boolean): string {
|
|
79
|
+
const name = p.name ?? "<名前>";
|
|
80
|
+
return [
|
|
81
|
+
write
|
|
82
|
+
? `今いる場所ではプロジェクトが決まりません(登録が1つだけなので「${name}」になりますが、変える操作はしません)。`
|
|
83
|
+
: `※ 今いる場所ではプロジェクトが決まらず、登録が1つだけなので「${name}」を表示しています。変える操作の前には対象を明示してください。`,
|
|
84
|
+
` プロジェクト: ${name} ${p.dataDir}`,
|
|
85
|
+
` → p3 --project ${name} <コマンド> で明示する`,
|
|
86
|
+
` → または登録したリポジトリ(p3 --project ${name} repo ls)かデータのフォルダの中で実行する`,
|
|
87
|
+
].join("\n");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 操作するプロジェクトを決める。環境変数では切り替えない(同じ人が複数のプロジェクトを行き来するため)。
|
|
92
|
+
*
|
|
93
|
+
* 1. --dir <フォルダ> データのフォルダを直接指す
|
|
94
|
+
* 2. --project <名前> 個人設定に登録したプロジェクト
|
|
95
|
+
* 3. 今いる場所 登録したプロジェクトのデータのフォルダか、そのリポジトリ(作業ツリーを含む)の中
|
|
96
|
+
* 4. リポジトリの中の .p3/ 個人設定に登録していないとき(git のメインの作業ツリー → 上へ辿る。デモ・登録前の clone など)
|
|
97
|
+
* 5. 登録が1つだけ それを使う
|
|
98
|
+
*/
|
|
99
|
+
export function resolveProject(o: { cwd: string; dir?: string; project?: string; user: UserConfig }): ResolvedProject {
|
|
100
|
+
const entries = Object.entries(o.user.projects);
|
|
101
|
+
const named = ([name, p]: (typeof entries)[number], via: ResolvedProject["via"]): ResolvedProject => ({
|
|
102
|
+
name,
|
|
103
|
+
dataDir: p.dir,
|
|
104
|
+
repos: { ...p.repos },
|
|
105
|
+
via,
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
if (o.dir) {
|
|
109
|
+
const dataDir = resolve(o.cwd, o.dir);
|
|
110
|
+
const hit = entries.find(([, p]) => p.dir === dataDir);
|
|
111
|
+
return hit ? named(hit, "dir") : { dataDir, repos: {}, via: "dir" };
|
|
112
|
+
}
|
|
113
|
+
if (o.project) {
|
|
114
|
+
const hit = entries.find(([name]) => name === o.project);
|
|
115
|
+
if (!hit) throw new ProjectNotResolvedError(`プロジェクト「${o.project}」は登録されていません。\n${listing(o.user)}`);
|
|
116
|
+
return named(hit, "project");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const places = [...new Set([resolve(o.cwd), mainWorktree(o.cwd)].filter((x): x is string => !!x))];
|
|
120
|
+
const hits = entries.filter(([, p]) => places.some((pl) => inside(pl, p.dir) || Object.values(p.repos).some((r) => inside(pl, r))));
|
|
121
|
+
if (hits.length === 1) return named(hits[0], "cwd");
|
|
122
|
+
if (hits.length > 1) {
|
|
123
|
+
throw new ProjectNotResolvedError(
|
|
124
|
+
`この場所は複数のプロジェクトに登録されています: ${hits.map(([n]) => n).join(", ")}\n → p3 --project <名前> <コマンド> で選んでください`,
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const legacy = findDataDir(o.cwd);
|
|
129
|
+
if (legacy) {
|
|
130
|
+
const hit = entries.find(([, p]) => p.dir === legacy);
|
|
131
|
+
return hit ? named(hit, "legacy") : { dataDir: legacy, repos: {}, via: "legacy" };
|
|
132
|
+
}
|
|
133
|
+
if (entries.length === 1) return named(entries[0], "only");
|
|
134
|
+
|
|
135
|
+
throw new ProjectNotResolvedError(
|
|
136
|
+
entries.length
|
|
137
|
+
? `操作するプロジェクトが決まりません(今いる場所: ${o.cwd})。\n${listing(o.user)}`
|
|
138
|
+
: "プロジェクトがまだありません。管理したいリポジトリの中で次を実行してください:\n p3 init --project <名前>(データはリポジトリのルートの .p3。外に置くなら --dir <フォルダ>)",
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function listing(user: UserConfig): string {
|
|
143
|
+
const entries = Object.entries(user.projects);
|
|
144
|
+
if (!entries.length) return " (登録済みのプロジェクトはありません。p3 init で作ってください)";
|
|
145
|
+
const w = Math.max(...entries.map(([n]) => n.length));
|
|
146
|
+
return [
|
|
147
|
+
" 登録済みのプロジェクト:",
|
|
148
|
+
...entries.map(([n, p]) => ` ${n.padEnd(w)} ${p.dir}`),
|
|
149
|
+
" → p3 --project <名前> <コマンド>、またはプロジェクトのリポジトリの中で実行してください",
|
|
150
|
+
].join("\n");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const inside = (path: string, dir: string) => path === dir || path.startsWith(dir.endsWith(sep) ? dir : dir + sep);
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* リポジトリの中の .p3/ を探す(個人設定に登録していないとき。登録していれば 3. の今いる場所で決まる)。
|
|
157
|
+
* 要望ごとの作業ツリーの中で実行しても、git のメインの作業ツリーの .p3/ を使う(各作業ツリーの .p3/ はブランチ時点の写し)。
|
|
158
|
+
*/
|
|
159
|
+
export function findDataDir(cwd: string): string | undefined {
|
|
160
|
+
const main = mainWorktree(cwd);
|
|
161
|
+
if (main && existsSync(join(main, DATA_DIR_NAME, "project.yaml"))) return join(main, DATA_DIR_NAME);
|
|
162
|
+
for (let dir = resolve(cwd); ; dir = dirname(dir)) {
|
|
163
|
+
if (existsSync(join(dir, DATA_DIR_NAME, "project.yaml"))) return join(dir, DATA_DIR_NAME);
|
|
164
|
+
if (dirname(dir) === dir) return undefined;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** git のメインの作業ツリー(要望の作業ツリーの中からでもメインを返す) */
|
|
169
|
+
export function mainWorktree(cwd: string): string | undefined {
|
|
170
|
+
try {
|
|
171
|
+
const common = execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
|
|
172
|
+
cwd,
|
|
173
|
+
encoding: "utf8",
|
|
174
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
175
|
+
}).trim();
|
|
176
|
+
// 通常は <main>/.git。bare リポジトリなどはメインの作業ツリーが無いので対象外
|
|
177
|
+
return common.endsWith("/.git") ? dirname(common) : undefined;
|
|
178
|
+
} catch {
|
|
179
|
+
return undefined;
|
|
180
|
+
}
|
|
181
|
+
}
|