@kzmshx/chiken 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.
package/dist/cli.mjs ADDED
@@ -0,0 +1,1701 @@
1
+ #!/usr/bin/env node
2
+
3
+ // node/cli.ts
4
+ import fs13 from "node:fs";
5
+ import path13 from "node:path";
6
+
7
+ // node/export/build.ts
8
+ import fs7 from "node:fs";
9
+ import path7 from "node:path";
10
+
11
+ // node/export/report.ts
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ var KIND = { study: "\u8ABF\u3079\u308B", try: "\u8A66\u3059", change: "\u5909\u3048\u308B" };
15
+ var LINK = { pre: "\u524D\u63D0\u306B\u306A\u308B", ease: "\u9032\u3081\u308B\u3068\u697D\u306B\u306A\u308B", same: "\u540C\u3058\u5F62" };
16
+ var ALINK = { pre: "\u524D\u306B\u8981\u308B", alt: "\u3069\u3061\u3089\u304B" };
17
+ var ORIGIN = { self: "\u81EA\u5206\u304C\u611F\u3058\u3066\u3044\u308B", ai: "AI \u306E\u63D0\u6848" };
18
+ var AUTHOR = { self: "\u53C2\u52A0\u8005", external: "\u767B\u58C7\u30FB\u8CC7\u6599\u30FB\u8A18\u4E8B", ai: "AI \u306E\u63D0\u6848" };
19
+ function writeReport(out2, d, summaries, modelCue) {
20
+ fs.rmSync(out2, { recursive: true, force: true });
21
+ for (const sub of ["sessions", "problems", "actions", "data"]) fs.mkdirSync(path.join(out2, sub), { recursive: true });
22
+ const P = new Map(d.problems.map((p) => [p.id, p]));
23
+ const A = new Map(d.actions.map((a) => [a.id, a]));
24
+ const S = new Map(d.sessions.map((s) => [s.id, s]));
25
+ const src = new Map(d.insightSources.map((s) => [s.id, s]));
26
+ const I = new Map(d.insights.map((i) => [i.id, i]));
27
+ const area = new Map(d.problemAreas.map((a) => [a.id, a]));
28
+ const pref = (id) => `${id} ${P.get(id)?.name ?? ""}`;
29
+ const srcName = (i) => {
30
+ const s = src.get(i.source);
31
+ return s ? s.session ? S.get(s.session)?.name ?? s.label : s.label : "";
32
+ };
33
+ const insightLine = (i, withProblems) => {
34
+ const meta = [srcName(i), i.who && i.who !== srcName(i) ? i.who : null, i.kind === "impression" ? "\u6240\u611F" : null, AUTHOR[i.author]].filter(Boolean).join("\u30FB");
35
+ const probs = withProblems && i.problems.length ? `\uFF08\u624B\u304C\u304B\u308A\u306B\u306A\u308B\u8AB2\u984C: ${i.problems.join("\u3001")}\uFF09` : "";
36
+ return `- ${i.text}\u3000[${meta}]${probs}`;
37
+ };
38
+ const sessionMd = (sid, h = "#") => {
39
+ const s = S.get(sid);
40
+ const ins = d.insights.filter((i) => src.get(i.source)?.session === sid);
41
+ return [
42
+ `${h} ${s.title ?? s.name}`,
43
+ "",
44
+ `- \u4F1A\u793E\u30FB\u767B\u58C7\u8005: ${[s.name, s.who].filter(Boolean).join("\u3000")}`,
45
+ `- ${s.day} \u65E5\u76EE ${s.time}\uFF08${s.attended ? "\u8074\u3044\u305F" : "\u8CC7\u6599\u3060\u3051\u8AAD\u3093\u3060"}\uFF09`,
46
+ "",
47
+ ...s.sum ? [s.sum, ""] : [],
48
+ ...s.slides?.length ? [`${h}# \u8CC7\u6599`, "", ...s.slides.map((x) => `- [${x.label}](${x.url})\uFF08${x.host}\uFF09`), ""] : [],
49
+ ...s.points?.length ? [`${h}# \u8CC7\u6599\u306E\u8981\u70B9`, "", ...s.points.map((t) => `- ${t}`), ""] : [],
50
+ ...s.take ? [`${h}# \u6301\u3061\u5E30\u3063\u305F\u3053\u3068`, "", s.take, ""] : [],
51
+ ...s.notes?.length ? [`${h}# \u6240\u611F`, "", ...s.notes.map((t) => `- ${t}`), ""] : [],
52
+ ...ins.length ? [`${h}# \u77E5\u898B`, "", ...ins.map((i) => insightLine(i, true)), ""] : []
53
+ ].join("\n");
54
+ };
55
+ const problemMd = (pid, h = "#") => {
56
+ const p = P.get(pid);
57
+ const ups = d.problemLinks.filter((e) => e.down === pid);
58
+ const downs = d.problemLinks.filter((e) => e.up === pid);
59
+ const acts = d.actions.filter((a) => a.problem === pid || a.also?.includes(pid));
60
+ const ins = d.insights.filter((i) => i.problems.includes(pid));
61
+ return [
62
+ `${h} ${p.id} ${p.name}`,
63
+ "",
64
+ `- \u9818\u57DF: ${area.get(p.area)?.name ?? p.area}`,
65
+ `- \u51FA\u3069\u3053\u308D: ${ORIGIN[p.origin]}`,
66
+ "",
67
+ ...p.why ? [p.why, ""] : [],
68
+ `${h}# \u4ECA\u306E\u72B6\u614B`,
69
+ "",
70
+ ...p.now.map((t) => `- ${t}`),
71
+ "",
72
+ ...p.concern?.length ? [`${h}# \u6C17\u306B\u3057\u3066\u3044\u308B\u3053\u3068`, "", ...p.concern.map((t) => `- ${t}`), ""] : [],
73
+ ...p.own?.length ? [`${h}# \u898B\u7ACB\u3066`, "", ...p.own.map((t) => `- ${t}`), ""] : [],
74
+ ...ups.length ? [`${h}# \u524D\u306B\u3042\u308B\u8AB2\u984C`, "", ...ups.map((e) => `- ${pref(e.up)}\uFF08${LINK[e.kind]}\uFF09: ${e.reason}`), ""] : [],
75
+ ...downs.length ? [`${h}# \u5F8C\u306B\u3042\u308B\u8AB2\u984C`, "", ...downs.map((e) => `- ${pref(e.down)}\uFF08${LINK[e.kind]}\uFF09: ${e.reason}`), ""] : [],
76
+ ...acts.length ? [`${h}# \u30A2\u30AF\u30B7\u30E7\u30F3`, "", ...acts.map((a) => `- ${a.id} ${a.name}\uFF08${KIND[a.kind]}${a.problem !== pid ? "\u3001\u4E3B\u306A\u8AB2\u984C\u306F " + a.problem : ""}\uFF09`), ""] : [],
77
+ ...ins.length ? [`${h}# \u624B\u304C\u304B\u308A\u306B\u306A\u308B\u77E5\u898B`, "", ...ins.map((i) => insightLine(i, false)), ""] : []
78
+ ].join("\n");
79
+ };
80
+ const actionMd = (a, h = "#") => {
81
+ const links = d.actionLinks.filter((l) => l.from === a.id || l.to === a.id);
82
+ const basis = (a.basis ?? []).map((id) => I.get(id)).filter((x) => !!x);
83
+ const body = a.doc ?? [
84
+ a.check && `${h}# \u78BA\u304B\u3081\u308B\u3053\u3068
85
+
86
+ ${a.check}
87
+ `,
88
+ a.done && `${h}# \u7D42\u308F\u308A\u306E\u6761\u4EF6
89
+
90
+ ${a.done}
91
+ `,
92
+ a.why && `${h}# \u52B9\u304D\u305D\u3046\u306A\u7406\u7531
93
+
94
+ ${a.why}
95
+ `
96
+ ].filter(Boolean).join("\n");
97
+ return [
98
+ `${h} ${a.id} ${a.name}`,
99
+ "",
100
+ `- \u7A2E\u985E: ${KIND[a.kind]}`,
101
+ `- \u51FA\u3069\u3053\u308D: ${ORIGIN[a.origin]}`,
102
+ `- \u4E3B\u306A\u8AB2\u984C: ${pref(a.problem)}`,
103
+ ...a.also?.length ? [`- \u3042\u308F\u305B\u3066\u9032\u3080\u8AB2\u984C: ${a.also.map(pref).join("\u3001")}`] : [],
104
+ "",
105
+ a.doc ? body.replace(/^## /gm, `${h}# `) : body,
106
+ "",
107
+ ...links.length ? [`${h}# \u307B\u304B\u306E\u30A2\u30AF\u30B7\u30E7\u30F3\u3068\u306E\u3064\u306A\u304C\u308A`, "", ...links.map((l) => `- ${ALINK[l.kind]}: ${l.from === a.id ? l.to : l.from} ${A.get(l.from === a.id ? l.to : l.from)?.name ?? ""} \u2014 ${l.reason}`), ""] : [],
108
+ ...basis.length ? [`${h}# \u6839\u62E0\u306E\u77E5\u898B`, "", ...basis.map((i) => insightLine(i, false)), ""] : []
109
+ ].join("\n");
110
+ };
111
+ for (const s of d.sessions) fs.writeFileSync(path.join(out2, "sessions", `${s.id.replace(/\//g, "-")}.md`), sessionMd(s.id));
112
+ for (const p of d.problems) fs.writeFileSync(path.join(out2, "problems", `${p.id}.md`), problemMd(p.id));
113
+ for (const a of d.actions) fs.writeFileSync(path.join(out2, "actions", `${a.id}.md`), actionMd(a));
114
+ fs.writeFileSync(path.join(out2, "data", "map.json"), JSON.stringify(d, null, 1));
115
+ fs.writeFileSync(path.join(out2, "data", "model.cue"), modelCue);
116
+ const summaryMd = summaries.flatMap((summary) => [`## ${summary.title}`, "", summary.lead, "", ...summary.themes.flatMap((t) => [`### ${t.name}`, "", t.sum, "", ...t.items.map((c) => `- **${c.name}** : ${c.sum}`), ""])]);
117
+ const report = [
118
+ `# ${d.title}`,
119
+ "",
120
+ d.lead,
121
+ "",
122
+ "## \u3053\u306E\u30EC\u30DD\u30FC\u30C8\u306E\u8AAD\u307F\u65B9",
123
+ "",
124
+ "- \u53D7\u3051\u53D6\u3063\u305F\u30A4\u30F3\u30D7\u30C3\u30C8\uFF08\u30A4\u30D9\u30F3\u30C8\u306E\u767B\u58C7\u3001\u8A18\u4E8B\u306A\u3069\uFF09\u306E\u77E5\u898B\u3092\u3001\u8AB2\u984C\u306B\u7D50\u3073\u4ED8\u3051\u305F\u3082\u306E",
125
+ "- \u300CAI \u306E\u63D0\u6848\u300D\u3068\u66F8\u3044\u305F\u8AB2\u984C\u30FB\u30A2\u30AF\u30B7\u30E7\u30F3\u30FB\u3064\u306A\u304C\u308A\u306F\u3001\u8A18\u9332\u3092\u7A81\u304D\u5408\u308F\u305B\u3066 AI \u304C\u6319\u3052\u305F\u3082\u306E\u3067\u3001\u307E\u3060\u691C\u8A0E\u3057\u3066\u3044\u306A\u3044",
126
+ "- \u540C\u3058\u4E2D\u8EAB\u3092\u3001\u30BB\u30C3\u30B7\u30E7\u30F3\u30FB\u8AB2\u984C\u30FB\u30A2\u30AF\u30B7\u30E7\u30F3\u3054\u3068\u306E\u30D5\u30A1\u30A4\u30EB\uFF08sessions/\u30FBproblems/\u30FBactions/\uFF09\u3068\u3001\u69CB\u9020\u5316\u30C7\u30FC\u30BF\uFF08data/map.json\u3001\u5F62\u306F data/model.cue\uFF09\u3067\u3082\u7F6E\u3044\u3066\u3044\u308B",
127
+ "",
128
+ ...summaryMd,
129
+ "## \u8AB2\u984C",
130
+ "",
131
+ ...d.problemAreas.flatMap((ar) => [`### ${ar.name}`, "", ar.sum, "", ...d.problems.filter((p) => p.area === ar.id).map((p) => problemMd(p.id, "####")), ""]),
132
+ ...d.priorityNote ? ["## \u3069\u3053\u304B\u3089\u624B\u3092\u4ED8\u3051\u308B\u304B\uFF08AI \u306E\u63D0\u6848\uFF09", "", ...d.priorityNote.text.map((t) => `- ${t}`), ""] : [],
133
+ "## \u30A2\u30AF\u30B7\u30E7\u30F3",
134
+ "",
135
+ ...d.actions.map((a) => actionMd(a, "###")),
136
+ "## \u30BB\u30C3\u30B7\u30E7\u30F3\u3068\u77E5\u898B",
137
+ "",
138
+ ...d.sessions.filter((s) => s.attended).map((s) => sessionMd(s.id, "###")),
139
+ ...d.sessions.filter((s) => !s.attended).map((s) => sessionMd(s.id, "###"))
140
+ ].join("\n");
141
+ fs.writeFileSync(path.join(out2, "report.md"), report);
142
+ fs.writeFileSync(path.join(out2, "README.md"), [
143
+ `# ${d.title}`,
144
+ "",
145
+ "- `index.html` : \u4EBA\u304C\u8AAD\u3080\u305F\u3081\u306E\u5730\u56F3\uFF08\u30D6\u30E9\u30A6\u30B6\u3067\u958B\u304F\uFF09",
146
+ "- `report.md` : \u5168\u90E8\u3092 1 \u672C\u306B\u307E\u3068\u3081\u305F\u30EC\u30DD\u30FC\u30C8\u3002AI \u306B\u8AAD\u307E\u305B\u308B\u306A\u3089\u307E\u305A\u3053\u308C",
147
+ "- `sessions/` `problems/` `actions/` : \u30BB\u30C3\u30B7\u30E7\u30F3\u30FB\u8AB2\u984C\u30FB\u30A2\u30AF\u30B7\u30E7\u30F3\u3054\u3068\u306E Markdown",
148
+ "- `data/map.json` : \u540C\u3058\u4E2D\u8EAB\u306E\u69CB\u9020\u5316\u30C7\u30FC\u30BF\uFF08\u5F62\u306F `data/model.cue`\uFF09",
149
+ "",
150
+ "AI \u306B\u6E21\u3059\u3068\u304D\u306E\u4F8B: \u300Creport.md \u3092\u8AAD\u3093\u3067\u3001P03 \u306B\u95A2\u4FC2\u3059\u308B\u77E5\u898B\u3068\u3001\u8A66\u305B\u308B\u30A2\u30AF\u30B7\u30E7\u30F3\u3092\u8AAC\u660E\u3057\u3066\u300D",
151
+ ""
152
+ ].join("\n"));
153
+ }
154
+
155
+ // node/root/read.ts
156
+ import fs2 from "node:fs";
157
+ import path2 from "node:path";
158
+ import YAML from "yaml";
159
+ function linkRoot(root, config) {
160
+ const c = config ?? YAML.parse(fs2.readFileSync(path2.join(root, LAYOUT.config), "utf8"));
161
+ return path2.resolve(root, c.linkBase ?? "..");
162
+ }
163
+ var LAYOUT = {
164
+ config: "chiken.yaml",
165
+ areas: "areas.md",
166
+ priority: "priority.md",
167
+ problems: "problems",
168
+ actions: "actions",
169
+ sources: "sources",
170
+ exports: "exports"
171
+ };
172
+ function readMd(file) {
173
+ const text = fs2.readFileSync(file, "utf8").replace(/\r\n/g, "\n");
174
+ const m = /^---\n([\s\S]*?)\n---\n?/.exec(text);
175
+ if (!m) return { fm: {}, body: text };
176
+ return { fm: YAML.parse(m[1]) ?? {}, body: text.slice(m[0].length) };
177
+ }
178
+ var mdFiles = (dir) => fs2.existsSync(dir) ? fs2.readdirSync(dir, { recursive: true }).map(String).filter((f) => f.endsWith(".md")).map((f) => path2.join(dir, f)) : [];
179
+ var title = (body) => /^#\s+(.+)$/m.exec(body)?.[1].trim() ?? "";
180
+ function section(body, h) {
181
+ const m = new RegExp(`^## ${h}\\s*\\n([\\s\\S]*?)(?=^## |(?![\\s\\S]))`, "m").exec(body);
182
+ const t = m?.[1].trim();
183
+ return t || void 0;
184
+ }
185
+ var bullets = (t) => t ? t.split("\n").filter((l) => l.startsWith("- ")).map((l) => l.slice(2).trim()) : void 0;
186
+ var need = (v, file, key) => {
187
+ if (v === void 0 || v === null || v === "") throw new Error(`${file}: frontmatter \u306B ${key} \u304C\u306A\u3044`);
188
+ return String(v);
189
+ };
190
+ var str = (v) => v === void 0 || v === null ? void 0 : String(v);
191
+ var arr = (v) => Array.isArray(v) ? v.map(String) : void 0;
192
+ function readRoot(root) {
193
+ const config = YAML.parse(fs2.readFileSync(path2.join(root, LAYOUT.config), "utf8"));
194
+ const legacyShare = [];
195
+ const files = /* @__PURE__ */ new Map();
196
+ const areasFm = readMd(path2.join(root, LAYOUT.areas)).fm;
197
+ const contexts = (areasFm.contexts ?? []).map((c) => ({ id: String(c.id), name: String(c.name), ...c.sum ? { sum: String(c.sum) } : {} }));
198
+ if (!Array.isArray(areasFm.areas)) throw new Error(`${path2.join(root, LAYOUT.areas)}: frontmatter \u306B areas \u304C\u306A\u3044`);
199
+ const problemAreas = areasFm.areas.map((a) => ({ id: a.id, name: a.name, sum: a.sum, ...a.context ? { context: String(a.context) } : {} }));
200
+ const problems = [];
201
+ const problemLinks = [];
202
+ for (const f of mdFiles(path2.join(root, LAYOUT.problems)).sort()) {
203
+ const { fm, body } = readMd(f);
204
+ const id = need(fm.id, f, "id");
205
+ files.set(id, f);
206
+ if (fm.share !== void 0) legacyShare.push(id);
207
+ const p = { id, area: String(fm.area), origin: fm.origin, name: title(body), now: bullets(section(body, "\u4ECA\u306E\u72B6\u614B")) ?? [] };
208
+ const pg = arr(fm.groups);
209
+ if (pg?.length) p.groups = pg;
210
+ const concern = bullets(section(body, "\u6C17\u306B\u3057\u3066\u3044\u308B\u3053\u3068"));
211
+ const own = bullets(section(body, "\u81EA\u5206\u306E\u898B\u7ACB\u3066"));
212
+ const why = section(body, "\u306A\u305C\u8AB2\u984C\u3068\u898B\u305F\u304B");
213
+ if (concern) p.concern = concern;
214
+ if (own) p.own = own;
215
+ if (why) p.why = why;
216
+ if (fm.session) p.session = String(fm.session);
217
+ problems.push(p);
218
+ for (const l of fm.before ?? []) problemLinks.push({ up: l.id, down: id, kind: l.kind, reason: l.reason });
219
+ }
220
+ const actions = [];
221
+ const actionLinks = [];
222
+ for (const f of mdFiles(path2.join(root, LAYOUT.actions)).sort()) {
223
+ const { fm, body } = readMd(f);
224
+ const id = need(fm.id, f, "id");
225
+ files.set(id, f);
226
+ const detailed = /^## 手順/m.test(body);
227
+ const a = { id, kind: fm.kind, origin: fm.origin, name: title(body), problem: String(fm.problem) };
228
+ const also = arr(fm.also);
229
+ const basis = arr(fm.basis);
230
+ if (also) a.also = also;
231
+ if (basis) a.basis = basis;
232
+ const check2 = section(body, "\u78BA\u304B\u3081\u308B\u3053\u3068");
233
+ const done = section(body, "\u7D42\u308F\u308A\u306E\u6761\u4EF6");
234
+ const why = section(body, "\u52B9\u304D\u305D\u3046\u306A\u7406\u7531");
235
+ if (why) a.why = why;
236
+ if (check2) a.check = check2;
237
+ if (done) a.done = done;
238
+ if (fm.share !== void 0) legacyShare.push(id);
239
+ const ag = arr(fm.groups);
240
+ if (ag?.length) a.groups = ag;
241
+ if (detailed) a.doc = body.replace(/<!--[\s\S]*?-->/g, "").trim().replace(/^#\s.*\n+/, "").trim();
242
+ actions.push(a);
243
+ for (const l of fm.needs ?? []) actionLinks.push({ from: l.id, to: id, kind: l.kind, reason: l.reason });
244
+ }
245
+ const collections = [];
246
+ const sessions = [];
247
+ const insightSources = [];
248
+ const insights = [];
249
+ const sourceOf = /* @__PURE__ */ new Map();
250
+ const indexFiles = mdFiles(path2.join(root, LAYOUT.sources)).filter((f) => path2.basename(f) === "_index.md");
251
+ const collectionDirs = new Map(indexFiles.map((f) => [path2.dirname(f), readMd(f).fm]));
252
+ for (const [dir, fm] of collectionDirs) {
253
+ files.set(String(fm.id), path2.join(dir, "_index.md"));
254
+ collections.push({ id: String(fm.id), kind: String(fm.kind ?? "event"), type: str(fm.type), dates: arr(fm.dates), dir: path2.relative(root, dir), name: String(fm.name), days: fm.days, sessionMinutes: fm.sessionMinutes, photos: str(fm.photos), summary: fm.summary });
255
+ }
256
+ const collectionOf = (f) => [...collectionDirs.entries()].find(([dir]) => f.startsWith(dir + path2.sep));
257
+ for (const f of mdFiles(path2.join(root, LAYOUT.sources)).filter((x) => path2.basename(x) !== "_index.md").sort()) {
258
+ const { fm } = readMd(f);
259
+ if (!fm.id) continue;
260
+ const sid = String(fm.id);
261
+ files.set(sid, f);
262
+ const medium = String(fm.medium ?? "article");
263
+ const b = collectionOf(f);
264
+ const isSession = medium === "talk" && !!b && fm.day !== void 0;
265
+ sourceOf.set(sid, b ? String(b[1].id) : sid);
266
+ const short = sid.split("/").pop();
267
+ if (isSession) {
268
+ const s = { id: sid, day: Number(fm.day), time: String(fm.time), name: String(fm.org ?? short), attended: fm.taken === "live" || fm.taken === "watched" };
269
+ if (fm.title) s.title = String(fm.title);
270
+ if (fm.who) s.who = String(fm.who);
271
+ if (fm.sum) s.sum = String(fm.sum);
272
+ if (fm.take) s.take = String(fm.take);
273
+ const notes = arr(fm.notes);
274
+ const points = arr(fm.points);
275
+ if (notes) s.notes = notes;
276
+ if (points) s.points = points;
277
+ if (Array.isArray(fm.slides) && fm.slides.length) s.slides = fm.slides;
278
+ sessions.push(s);
279
+ }
280
+ const src = { id: sid, label: String(fm.org ?? (isSession ? short : fm.title ?? short)), medium };
281
+ if (isSession) src.session = sid;
282
+ if (b) src.collection = String(b[1].id);
283
+ if (medium === "note" && fm.type) src.noteType = String(fm.type);
284
+ if (fm.taken) src.taken = String(fm.taken);
285
+ if (fm.date) src.date = String(fm.date);
286
+ if (!isSession) {
287
+ if (fm.title) src.title = String(fm.title);
288
+ const points = arr(fm.points);
289
+ if (points) src.points = points;
290
+ if (Array.isArray(fm.slides) && fm.slides.length) src.links = fm.slides;
291
+ }
292
+ if (fm.url) src.url = String(fm.url);
293
+ const sg = arr(fm.groups);
294
+ if (sg?.length) src.groups = sg;
295
+ insightSources.push(src);
296
+ const list2 = fm.insights ?? [];
297
+ for (const i of list2) {
298
+ const ins = { id: `${sid}#${i.n}`, source: sid, text: String(i.text), kind: i.kind, author: i.author, problems: arr(i.problems) ?? [] };
299
+ if (i.who) ins.who = String(i.who);
300
+ if (i.verify) ins.verify = String(i.verify);
301
+ if (i.share !== void 0) legacyShare.push(ins.id);
302
+ const ig = arr(i.groups);
303
+ if (ig?.length) ins.groups = ig;
304
+ insights.push(ins);
305
+ }
306
+ }
307
+ const prio = fs2.existsSync(path2.join(root, LAYOUT.priority)) ? readMd(path2.join(root, LAYOUT.priority)).fm : void 0;
308
+ const map = {
309
+ title: config.title,
310
+ lead: config.lead,
311
+ priorityNote: prio ? { up: arr(prio.up) ?? [], down: arr(prio.down) ?? [], text: arr(prio.text) ?? [] } : void 0,
312
+ contexts,
313
+ problemAreas,
314
+ problems,
315
+ problemLinks,
316
+ sessions,
317
+ insightSources,
318
+ insights,
319
+ actions,
320
+ actionLinks
321
+ };
322
+ return { root, config, collections, map, legacyShare, sourceOf, files };
323
+ }
324
+
325
+ // node/lib/cue.ts
326
+ import { execFileSync } from "node:child_process";
327
+ import fs4 from "node:fs";
328
+ import path4 from "node:path";
329
+
330
+ // node/lib/paths.ts
331
+ import fs3 from "node:fs";
332
+ import os from "node:os";
333
+ import path3 from "node:path";
334
+ import { fileURLToPath } from "node:url";
335
+ function packageRoot() {
336
+ let dir = path3.dirname(fileURLToPath(import.meta.url));
337
+ while (!fs3.existsSync(path3.join(dir, "package.json"))) {
338
+ const up = path3.dirname(dir);
339
+ if (up === dir) throw new Error("chiken \u306E package.json \u304C\u898B\u3064\u304B\u3089\u306A\u3044");
340
+ dir = up;
341
+ }
342
+ return dir;
343
+ }
344
+ var REPO = packageRoot();
345
+ var FROM_SOURCE = false;
346
+ var CACHE = process.env.CHIKEN_CACHE ? path3.resolve(process.env.CHIKEN_CACHE) : FROM_SOURCE ? path3.join(REPO, ".cache") : path3.join(os.homedir(), ".cache", "chiken");
347
+
348
+ // node/lib/cue.ts
349
+ var NoCue = class extends Error {
350
+ };
351
+ var run = (cmd, a) => execFileSync(cmd, a, { cwd: REPO, encoding: "utf8", stdio: "pipe" });
352
+ var how;
353
+ function cueHow() {
354
+ if (how) return how;
355
+ const ok = (cmd, a) => {
356
+ try {
357
+ run(cmd, a);
358
+ return true;
359
+ } catch {
360
+ return false;
361
+ }
362
+ };
363
+ how = ok("cue", ["version"]) ? "path" : ok("mise", ["exec", "--", "cue", "version"]) ? "mise" : "none";
364
+ return how;
365
+ }
366
+ function cue(args) {
367
+ const h = cueHow();
368
+ if (h === "none") throw new NoCue("cue \u304C\u898B\u3064\u304B\u3089\u306A\u3044");
369
+ try {
370
+ return h === "path" ? run("cue", args) : run("mise", ["exec", "--", "cue", ...args]);
371
+ } catch (e) {
372
+ const er = e;
373
+ throw new Error(er.stderr || String(e));
374
+ }
375
+ }
376
+ var warned = false;
377
+ function vetMap(map) {
378
+ const file = path4.join(CACHE, "map.json");
379
+ fs4.mkdirSync(path4.dirname(file), { recursive: true });
380
+ fs4.writeFileSync(file, JSON.stringify({ ...map, flow: void 0, actions: map.actions.map(({ doc: _d, ...a }) => a) }));
381
+ try {
382
+ cue(["vet", "-c", "./schema/model.cue", "./schema/check.cue", file, "-d", "#Checked"]);
383
+ } catch (e) {
384
+ if (e instanceof NoCue) {
385
+ if (!warned) console.error("cue \u304C\u306A\u3044\u306E\u3067\u3001schema \u306E\u691C\u67FB\uFF08cue vet\uFF09\u306F\u98DB\u3070\u3057\u305F\u3002\u5165\u308C\u308B\u306A\u3089 https://cuelang.org/docs/introduction/installation/");
386
+ warned = true;
387
+ return;
388
+ }
389
+ throw new Error(`\u30C7\u30FC\u30BF\u30D5\u30A9\u30EB\u30C0\u304B\u3089\u7D44\u307F\u7ACB\u3066\u305F\u5730\u56F3\u304C schema \u306B\u5408\u308F\u306A\u3044:
390
+ ${e.message}`);
391
+ }
392
+ }
393
+
394
+ // src/model/source.ts
395
+ var MEDIUM = {
396
+ talk: "\u767B\u58C7",
397
+ article: "\u8A18\u4E8B",
398
+ video: "\u52D5\u753B",
399
+ podcast: "\u30DD\u30C3\u30C9\u30AD\u30E3\u30B9\u30C8",
400
+ book: "\u672C",
401
+ paper: "\u8AD6\u6587",
402
+ doc: "\u7D44\u7E54\u306E\u6587\u66F8",
403
+ note: "\u30E1\u30E2"
404
+ };
405
+ var TAKEN = {
406
+ live: "\u305D\u306E\u5834\u3067\u8074\u3044\u305F",
407
+ watched: "\u9332\u753B\u3092\u89B3\u305F",
408
+ read: "\u5168\u6587\u3092\u8AAD\u3093\u3060",
409
+ skimmed: "\u8CC7\u6599\u3084\u8981\u7D04\u3060\u3051"
410
+ };
411
+ var firsthand = (t) => t !== "skimmed";
412
+ var COLLECTION = {
413
+ event: "\u30A4\u30D9\u30F3\u30C8",
414
+ series: "\u9023\u8F09",
415
+ book: "\u672C"
416
+ };
417
+ var EVENT_TYPE = {
418
+ conference: "\u30AB\u30F3\u30D5\u30A1\u30EC\u30F3\u30B9",
419
+ meetup: "\u30DF\u30FC\u30C8\u30A2\u30C3\u30D7",
420
+ study: "\u52C9\u5F37\u4F1A",
421
+ webinar: "\u30A6\u30A7\u30D3\u30CA\u30FC"
422
+ };
423
+ var collectionLabel = (kind, type) => type && EVENT_TYPE[type] || COLLECTION[kind] || kind;
424
+
425
+ // node/export/scope.ts
426
+ function hits(w, t) {
427
+ return w.startsWith("(?i)") ? new RegExp(w.slice(4), "i").test(t) : t.toLowerCase().includes(w.toLowerCase());
428
+ }
429
+ var leaked = (forbid, t) => forbid.filter((w) => hits(w, t));
430
+ function soften(r, t) {
431
+ let s = t;
432
+ for (const [a, b] of r.replace ?? []) {
433
+ s = a.startsWith("(?i)") ? s.replace(new RegExp(a.slice(4), "gi"), b) : s.split(a).join(b);
434
+ }
435
+ return s;
436
+ }
437
+ function groupFilter(e) {
438
+ return (groups) => {
439
+ const g = groups ?? [];
440
+ if (e.include?.length && !g.some((x) => e.include.includes(x))) return false;
441
+ return !g.some((x) => e.exclude?.includes(x));
442
+ };
443
+ }
444
+ function redact(src, e, rules, title2) {
445
+ const r = rules ?? {};
446
+ const forbid = r.forbid ?? [];
447
+ const dropWords = [...forbid, ...r.drop ?? []];
448
+ const fix = (t) => soften(r, t);
449
+ const keepGroups = groupFilter(e);
450
+ const redactDoc = (md) => !rules ? md : fix(md.replace(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g, (_m, t, l) => l ?? t.split("/").pop() ?? t)).split("\n").filter((line) => !dropWords.some((w) => hits(w, line))).join("\n");
451
+ const leaks = (t) => !!t && dropWords.some((w) => hits(w, t));
452
+ const problems = src.problems.filter((p) => keepGroups(p.groups)).map((p) => ({
453
+ ...p,
454
+ name: fix(p.name),
455
+ now: p.now.map(fix),
456
+ concern: p.concern?.map(fix),
457
+ own: p.own?.map(fix),
458
+ why: p.why && fix(p.why)
459
+ }));
460
+ const keep = new Set(problems.map((p) => p.id));
461
+ const hiddenSrc = new Set(src.insightSources.filter((x) => !keepGroups(x.groups)).map((x) => x.id));
462
+ const unseenSrc = new Set(e.firsthand ? src.insightSources.filter((x) => !firsthand(x.taken)).map((x) => x.id) : []);
463
+ const srcOf = new Map(src.insights.map((i) => [i.id, i.source]));
464
+ const onlyUnseen = (basis) => !!basis?.length && basis.every((b) => unseenSrc.has(srcOf.get(b) ?? ""));
465
+ let dropped = 0;
466
+ const insights = src.insights.filter((i) => !unseenSrc.has(i.source) && !hiddenSrc.has(i.source) && keepGroups(i.groups)).filter((i) => !i.problems.length || i.problems.some((x) => keep.has(x))).map((i) => ({ ...i, problems: i.problems.filter((x) => keep.has(x)), text: fix(i.text), who: i.who && fix(i.who), verify: i.verify && fix(i.verify) })).filter((i) => {
467
+ const bad = leaks(i.text) || leaks(i.who) || leaks(i.verify);
468
+ if (bad) dropped++;
469
+ return !bad;
470
+ });
471
+ const ik = new Set(insights.map((i) => i.id));
472
+ const actions = src.actions.filter((a) => keepGroups(a.groups) && keep.has(a.problem) && !onlyUnseen(a.basis)).map((a) => ({
473
+ ...a,
474
+ name: fix(a.name),
475
+ why: a.why && fix(a.why),
476
+ check: a.check && fix(a.check),
477
+ done: a.done && fix(a.done),
478
+ also: a.also?.filter((x) => keep.has(x)),
479
+ basis: a.basis?.filter((x) => ik.has(x)),
480
+ doc: a.doc && redactDoc(a.doc)
481
+ }));
482
+ const ak = new Set(actions.map((a) => a.id));
483
+ const usedSrc = new Set(insights.map((i) => i.source));
484
+ const problemLinks = src.problemLinks.filter((e2) => keep.has(e2.up) && keep.has(e2.down)).map((e2) => ({ ...e2, reason: fix(e2.reason) }));
485
+ const f = (ids) => ids.filter((id) => keep.has(id));
486
+ if (rules || e.firsthand) console.log(`${e.name}: \u898F\u5247\u3067\u5916\u3057\u305F\u77E5\u898B ${dropped}\u3001\u8CC7\u6599\u3084\u8981\u7D04\u3060\u3051\u306E\u30A4\u30F3\u30D7\u30C3\u30C8\u306E\u77E5\u898B ${src.insights.filter((i) => unseenSrc.has(i.source)).length}\u3001\u305D\u308C\u3060\u3051\u3092\u6839\u62E0\u306B\u3059\u308B\u30A2\u30AF\u30B7\u30E7\u30F3 ${src.actions.filter((a) => onlyUnseen(a.basis)).length}`);
487
+ return {
488
+ title: title2,
489
+ lead: r.lead ?? src.lead,
490
+ priorityNote: src.priorityNote && { up: f(src.priorityNote.up), down: f(src.priorityNote.down), text: (r.priorityText ?? src.priorityNote.text).map(fix) },
491
+ contexts: src.contexts.map((c) => ({ ...c, name: fix(c.name), sum: c.sum && fix(c.sum) })),
492
+ problemAreas: src.problemAreas.filter((a) => problems.some((p) => p.area === a.id)).map((a) => ({ ...a, sum: fix(r.areaSum?.[a.id] ?? a.sum) })),
493
+ problems,
494
+ problemLinks,
495
+ // セッションの文章にも言い換えを当て、外す語を含む文章は外す。グループで外したインプットのセッションは出さない
496
+ sessions: src.sessions.filter((s) => !hiddenSrc.has(s.id)).map((s) => {
497
+ const clean = (t) => t && !leaks(fix(t)) ? fix(t) : void 0;
498
+ return {
499
+ ...s,
500
+ name: fix(s.name),
501
+ title: s.title && fix(s.title),
502
+ who: s.who && fix(s.who),
503
+ sum: clean(s.sum),
504
+ take: clean(s.take),
505
+ notes: s.notes?.map(fix).filter((t) => !leaks(t)),
506
+ points: s.points?.map(fix).filter((t) => !leaks(t)),
507
+ slides: s.slides?.map((x) => ({ ...x, label: fix(x.label) }))
508
+ };
509
+ }),
510
+ insightSources: src.insightSources.filter((x) => !hiddenSrc.has(x.id) && (x.session || !unseenSrc.has(x.id) || usedSrc.has(x.id))).map((x) => ({ ...x, label: fix(x.label), title: x.title && fix(x.title), points: x.points?.map(fix).filter((t) => !leaks(t)), links: x.links?.map((l) => ({ ...l, label: fix(l.label) })) })),
511
+ insights,
512
+ actions,
513
+ actionLinks: src.actionLinks.filter((l) => ak.has(l.from) && ak.has(l.to)).map((l) => ({ ...l, reason: fix(l.reason) }))
514
+ };
515
+ }
516
+ function toSummary(d, r) {
517
+ if (!d) return void 0;
518
+ const fix = (t) => r ? soften(r, t) : t;
519
+ const words = [...r?.forbid ?? [], ...r?.drop ?? []];
520
+ const leaks = (t) => words.some((w) => hits(w, t));
521
+ return {
522
+ title: fix(d.title),
523
+ lead: fix(d.lead),
524
+ themes: d.themes.map((t) => ({
525
+ name: fix(t.name),
526
+ sum: fix(t.sum),
527
+ items: t.items.map((i) => ({ name: fix(i.name), sum: fix(i.sum), sessions: i.sessions })).filter((i) => !leaks(i.name) && !leaks(i.sum))
528
+ })).filter((t) => !leaks(t.name) && !leaks(t.sum))
529
+ };
530
+ }
531
+
532
+ // node/export/flow.ts
533
+ import ELK from "elkjs/lib/elk.bundled.js";
534
+
535
+ // src/model/flow.ts
536
+ var FLOW = {
537
+ action: { w: 264, h: 116 },
538
+ // 中身は バッジの行 22 + 間 6 + 名前 3 行 63 + 上下の余白 20 = 111。少し余らせる
539
+ problem: { w: 224, h: 148 },
540
+ area: { padTop: 44, pad: 16, gap: 16 },
541
+ group: { padTop: 40, pad: 12, gap: 12, layerGap: 40 },
542
+ // 課題の枠(アクションの図)と、領域の枠の中の層
543
+ rootGap: 32,
544
+ rootPad: 24
545
+ };
546
+
547
+ // node/export/flow.ts
548
+ var pad = (top, side) => `[top=${top},left=${side},bottom=${side},right=${side}]`;
549
+ var packed = (aspect, gap, p) => ({ "elk.algorithm": "rectpacking", "elk.aspectRatio": aspect, "elk.spacing.nodeNode": String(gap), "elk.padding": p });
550
+ var layered = (p, aspect = "2.2") => ({
551
+ "elk.algorithm": "layered",
552
+ "elk.direction": "RIGHT",
553
+ "elk.separateConnectedComponents": "true",
554
+ "elk.aspectRatio": aspect,
555
+ "elk.spacing.nodeNode": String(FLOW.group.gap),
556
+ "elk.spacing.componentComponent": String(FLOW.group.gap),
557
+ "elk.layered.spacing.nodeNodeBetweenLayers": String(FLOW.group.layerGap),
558
+ "elk.layered.spacing.edgeNodeBetweenLayers": "12",
559
+ "elk.edgeRouting": "ORTHOGONAL",
560
+ "elk.padding": p
561
+ });
562
+ function leaf(id, cards, links, size, opts) {
563
+ const inside = new Set(cards);
564
+ return {
565
+ id,
566
+ layoutOptions: opts,
567
+ children: cards.map((c) => ({ id: c, width: size.w, height: size.h })),
568
+ edges: links.filter((l) => inside.has(l.from) && inside.has(l.to)).map((l, i) => ({ id: `${id}-${i}`, sources: [l.from], targets: [l.to] }))
569
+ };
570
+ }
571
+ function flatten(out2, card, frameKinds) {
572
+ const frames = [];
573
+ const cards = {};
574
+ const routes = {};
575
+ const walk = (n, ox, oy, depth) => {
576
+ for (const e of n.edges ?? []) {
577
+ const s = e.sections?.[0];
578
+ if (s) routes[`${e.sources[0]}>${e.targets[0]}`] = [s.startPoint, ...s.bendPoints ?? [], s.endPoint].map((q) => ({ x: ox + q.x, y: oy + q.y }));
579
+ }
580
+ for (const c of n.children ?? []) {
581
+ const x = ox + (c.x ?? 0);
582
+ const y = oy + (c.y ?? 0);
583
+ const kind = frameKinds[depth];
584
+ if (c.children) {
585
+ if (kind) frames.push({ id: c.id, kind, x, y, w: c.width ?? 0, h: c.height ?? 0 });
586
+ walk(c, x, y, depth + 1);
587
+ } else cards[c.id] = { x, y };
588
+ }
589
+ };
590
+ walk(out2, 0, 0, 0);
591
+ return { width: out2.width ?? 0, height: out2.height ?? 0, card, frames, cards, routes };
592
+ }
593
+ var elk = new ELK();
594
+ var run2 = async (g) => await elk.layout(g);
595
+ async function flowLayouts(d) {
596
+ const actionLinks = d.actionLinks.map((l) => ({ from: l.from, to: l.to }));
597
+ const problemLinks = d.problemLinks.filter((l) => l.kind !== "same").map((l) => ({ from: l.up, to: l.down }));
598
+ const rootOpts = packed("1.6", FLOW.rootGap, pad(FLOW.rootPad, FLOW.rootPad));
599
+ const areaOpts = packed("1.2", FLOW.area.gap, pad(FLOW.area.padTop, FLOW.area.pad));
600
+ const actionsGrouped = await run2({
601
+ id: "root",
602
+ layoutOptions: rootOpts,
603
+ children: d.problemAreas.map((area) => ({
604
+ id: area.id,
605
+ layoutOptions: areaOpts,
606
+ children: d.problems.filter((p) => p.area === area.id && d.actions.some((a) => a.problem === p.id)).map((p) => leaf(p.id, d.actions.filter((a) => a.problem === p.id).map((a) => a.id), actionLinks, FLOW.action, layered(pad(FLOW.group.padTop, FLOW.group.pad))))
607
+ })).filter((a) => a.children.length)
608
+ });
609
+ const actionsFlat = await run2(leaf("root", d.actions.map((a) => a.id), actionLinks, FLOW.action, layered(pad(FLOW.rootPad, FLOW.rootPad), "1.8")));
610
+ const problemsGrouped = await run2({
611
+ id: "root",
612
+ layoutOptions: rootOpts,
613
+ children: d.problemAreas.map((area) => leaf(area.id, d.problems.filter((p) => p.area === area.id).map((p) => p.id), problemLinks, FLOW.problem, layered(pad(FLOW.area.padTop, FLOW.area.pad), "1.4"))).filter((a) => a.children?.length)
614
+ });
615
+ return {
616
+ actionsGrouped: flatten(actionsGrouped, FLOW.action, ["area", "problem"]),
617
+ actionsFlat: flatten(actionsFlat, FLOW.action, []),
618
+ problemsGrouped: flatten(problemsGrouped, FLOW.problem, ["area"])
619
+ };
620
+ }
621
+
622
+ // node/export/payload.ts
623
+ function scope(src, v, e) {
624
+ const want = e.sources?.length ? new Set(e.sources) : null;
625
+ const inSrc = (sid) => !want || want.has(sid) || want.has(v.sourceOf.get(sid) ?? "");
626
+ const insightSources = src.insightSources.filter((x) => inSrc(x.id));
627
+ const sk = new Set(insightSources.map((x) => x.id));
628
+ const insights = src.insights.filter((i) => sk.has(i.source));
629
+ const ik = new Set(insights.map((i) => i.id));
630
+ const sessions = src.sessions.filter((s) => insightSources.some((x) => x.session === s.id));
631
+ let problems = src.problems;
632
+ if (e.contexts?.length) {
633
+ const areas = new Set(src.problemAreas.filter((a) => a.context && e.contexts.includes(a.context)).map((a) => a.id));
634
+ problems = problems.filter((p) => areas.has(p.area));
635
+ }
636
+ let actions = src.actions;
637
+ if (e.problems === "linked") {
638
+ actions = actions.filter((a) => a.basis?.some((b) => ik.has(b)));
639
+ const pk2 = /* @__PURE__ */ new Set([...insights.flatMap((i) => i.problems), ...actions.flatMap((a) => [a.problem, ...a.also ?? []])]);
640
+ problems = problems.filter((p) => pk2.has(p.id));
641
+ }
642
+ const pk = new Set(problems.map((p) => p.id));
643
+ actions = actions.filter((a) => pk.has(a.problem));
644
+ const ak = new Set(actions.map((a) => a.id));
645
+ return structuredClone({
646
+ ...src,
647
+ sessions,
648
+ insightSources,
649
+ insights,
650
+ problems,
651
+ actions,
652
+ problemLinks: src.problemLinks.filter((l) => pk.has(l.up) && pk.has(l.down)),
653
+ actionLinks: src.actionLinks.filter((l) => ak.has(l.from) && ak.has(l.to)),
654
+ problemAreas: src.problemAreas.filter((a) => problems.some((p) => p.area === a.id))
655
+ });
656
+ }
657
+ async function makePayload(v, e, photoOf, photoUrl) {
658
+ const scoped = scope(v.map, v, e);
659
+ const rules = e.rules ? v.config.rules?.[e.rules] : void 0;
660
+ if (e.rules && !rules) throw new Error(`${e.name} \u306E rules \u304C\u306A\u3044: ${e.rules}\uFF08chiken.yaml \u306E rules\uFF09`);
661
+ const m = redact(scoped, e, rules, e.title);
662
+ const photosUsed = /* @__PURE__ */ new Set();
663
+ m.sessions = m.sessions.map((s) => {
664
+ const ph = photoOf.get(s.id) ?? [];
665
+ for (const p of ph) {
666
+ photosUsed.add(p.t);
667
+ photosUsed.add(p.f);
668
+ }
669
+ return { ...s, photos: ph.map((p) => ({ t: photoUrl(p.t), f: photoUrl(p.f) })) };
670
+ });
671
+ m.flow = await flowLayouts(m);
672
+ const used = new Set(m.insightSources.map((s) => s.collection).filter(Boolean));
673
+ const collections = v.collections.filter((b) => (!e.sources || e.sources.includes(b.id)) && used.has(b.id)).map((b) => ({
674
+ id: b.id,
675
+ name: b.name,
676
+ kind: b.kind,
677
+ type: b.type,
678
+ dates: b.dates,
679
+ kindLabel: collectionLabel(b.kind, b.type),
680
+ summary: toSummary(b.summary, rules)
681
+ }));
682
+ const ctxIds = [...new Set(m.problemAreas.map((a) => a.context).filter(Boolean))];
683
+ const ctx = ctxIds.length === 1 && m.problemAreas.every((a) => a.context === ctxIds[0]) ? m.contexts.find((c) => c.id === ctxIds[0]) : void 0;
684
+ const payload = {
685
+ title: e.title,
686
+ map: m,
687
+ collections,
688
+ sides: {
689
+ start: e.start ?? (e.sources?.length ? "sources" : "problems"),
690
+ sources: e.sources?.length === 1 && collections.length === 1 ? collections[0].name : "\u30E9\u30A4\u30D6\u30E9\u30EA",
691
+ problems: ctx ? `${ctx.name} \u306E\u8AB2\u984C` : "\u8AB2\u984C",
692
+ context: ctx?.name
693
+ }
694
+ };
695
+ return { payload, map: m, used: photosUsed };
696
+ }
697
+
698
+ // node/export/photos.ts
699
+ import { execFileSync as execFileSync2 } from "node:child_process";
700
+ import fs5 from "node:fs";
701
+ import path5 from "node:path";
702
+ import exifr from "exifr";
703
+ import sharp from "sharp";
704
+ async function shotTime(file) {
705
+ try {
706
+ const head = fs5.readFileSync(file).subarray(0, 256 * 1024);
707
+ const exif = await exifr.parse(head, ["DateTimeOriginal"]);
708
+ if (exif?.DateTimeOriginal instanceof Date) return exif.DateTimeOriginal;
709
+ } catch {
710
+ }
711
+ try {
712
+ const out2 = execFileSync2("mdls", ["-raw", "-name", "kMDItemContentCreationDate", file], { encoding: "utf8" }).trim();
713
+ if (out2 && out2 !== "(null)") return new Date(out2.replace(" +0000", "Z").replace(" ", "T"));
714
+ } catch {
715
+ }
716
+ return fs5.statSync(file).birthtime;
717
+ }
718
+ async function resized(src, thumbs, size, quality, tag) {
719
+ const dst = path5.join(thumbs, `${path5.parse(src).name}_${tag}.jpg`);
720
+ if (!fs5.existsSync(dst)) {
721
+ fs5.mkdirSync(thumbs, { recursive: true });
722
+ await sharp(src).rotate().resize(size, size, { fit: "inside", withoutEnlargement: true }).jpeg({ quality }).toFile(dst);
723
+ }
724
+ return dst;
725
+ }
726
+ async function assignPhotos(photosDir, collection, sessions) {
727
+ const files = fs5.readdirSync(photosDir).filter((f) => /^IMG_\d+\.(jpe?g|png|heic)$/i.test(f)).sort().map((f) => path5.join(photosDir, f));
728
+ const minutes = collection.sessionMinutes ?? 45;
729
+ const slots = sessions.filter((s) => s.attended).map((s) => {
730
+ const [h, m] = s.time.split(":").map(Number);
731
+ const start = /* @__PURE__ */ new Date(`${collection.days?.[String(s.day)]}T${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:00+09:00`);
732
+ return { id: s.id, start: start.getTime(), end: start.getTime() + minutes * 6e4 };
733
+ });
734
+ const got = Object.fromEntries(slots.map((s) => [s.id, []]));
735
+ for (const f of files) {
736
+ const t = await shotTime(f);
737
+ if (!t) continue;
738
+ const slot = slots.find((s) => t.getTime() >= s.start && t.getTime() < s.end);
739
+ if (slot) got[slot.id].push(f);
740
+ }
741
+ return got;
742
+ }
743
+ async function photosFor(thumbs, srcs) {
744
+ const out2 = [];
745
+ for (const src of srcs) {
746
+ out2.push({ t: await resized(src, thumbs, 560, 72, "t"), f: await resized(src, thumbs, 1800, 78, "f") });
747
+ }
748
+ return out2;
749
+ }
750
+ async function preparePhotos(v) {
751
+ const photoOf = /* @__PURE__ */ new Map();
752
+ for (const b of v.collections.filter((x) => x.photos)) {
753
+ const dir = path5.resolve(v.root, b.dir, b.photos);
754
+ const sessions = v.map.sessions.filter((s) => v.sourceOf.get(v.map.insightSources.find((x) => x.session === s.id)?.id ?? "") === b.id);
755
+ const assigned = await assignPhotos(dir, b, sessions);
756
+ for (const [sid, files] of Object.entries(assigned)) photoOf.set(sid, await photosFor(path5.join(dir, "thumbs"), files));
757
+ }
758
+ return photoOf;
759
+ }
760
+
761
+ // node/export/app.ts
762
+ import fs6 from "node:fs";
763
+ import path6 from "node:path";
764
+ var MARK = "<!--chiken-data-->";
765
+ var built = /* @__PURE__ */ new Map();
766
+ async function template(v) {
767
+ const packaged = path6.join(REPO, "templates", `${v}.html`);
768
+ if (!FROM_SOURCE && fs6.existsSync(packaged)) return fs6.readFileSync(packaged, "utf8");
769
+ if (!built.has(v)) {
770
+ built.set(v, (async () => {
771
+ const { buildTemplate } = await import("./template-build");
772
+ return buildTemplate(v, path6.join(CACHE, "templates"));
773
+ })());
774
+ }
775
+ return built.get(v);
776
+ }
777
+ async function buildApp(opts) {
778
+ const { payload, edit = false } = opts;
779
+ const v = edit ? "edit" : payload?.map.actions.some((a) => a.doc?.includes("```mermaid")) ? "view-mermaid" : "view";
780
+ const html = await template(v);
781
+ if (!html.includes(MARK)) throw new Error(`\u753B\u9762\u306E\u96DB\u5F62\u306B\u30C7\u30FC\u30BF\u306E\u5DEE\u3057\u8FBC\u307F\u53E3\u304C\u306A\u3044\uFF08${v}\uFF09`);
782
+ const esc = (t) => t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
783
+ const data = payload ? `<script id="chiken-data" type="application/json">${JSON.stringify(payload).replace(/</g, "\\u003c")}</script>` : "";
784
+ return html.replace(MARK, () => data).replace("<title>chiken</title>", () => `<title>${esc(opts.title)}</title>`);
785
+ }
786
+
787
+ // node/export/build.ts
788
+ async function buildOne(payload, name, outFile, forbid) {
789
+ const html = await buildApp({ payload, title: payload.title });
790
+ if (forbid.length) {
791
+ const text = html.replace(/data:[a-z/+.-]+;base64,[A-Za-z0-9+/=]+/g, "");
792
+ const leak = leaked(forbid, text);
793
+ if (leak.length) {
794
+ const where = leak.map((w) => {
795
+ const i = text.toLowerCase().indexOf(w.toLowerCase());
796
+ return `${w}: \u2026${text.slice(Math.max(0, i - 80), i + 40)}\u2026`;
797
+ });
798
+ throw new Error(`\u6B62\u3081\u308B\u8A9E\u304C HTML \u306B\u6B8B\u3063\u3066\u3044\u308B\uFF08${name}\uFF09:
799
+ ${where.join("\n")}`);
800
+ }
801
+ }
802
+ fs7.writeFileSync(outFile, html);
803
+ console.log(`${path7.basename(outFile)} ${(html.length / 1024 / 1024).toFixed(1)} MB`);
804
+ return html;
805
+ }
806
+ async function buildExports(root, only) {
807
+ if (!fs7.existsSync(path7.join(root, "chiken.yaml"))) throw new Error(`chiken.yaml \u304C\u306A\u3044\u3002chiken \u306E\u30C7\u30FC\u30BF\u30D5\u30A9\u30EB\u30C0\u3092\u6E21\u3059: ${root}`);
808
+ const v = readRoot(root);
809
+ vetMap(v.map);
810
+ const photoOf = await preparePhotos(v);
811
+ const targets = v.config.exports.filter((x) => !only || x.name === only);
812
+ if (only && !targets.length) throw new Error(`\u66F8\u304D\u51FA\u3057\u304C\u306A\u3044: ${only}\uFF08chiken.yaml \u306E exports: ${v.config.exports.map((x) => x.name).join(", ")}\uFF09`);
813
+ for (const e of targets) {
814
+ const forbid = e.rules && v.config.rules?.[e.rules]?.forbid || [];
815
+ const out2 = path7.resolve(root, e.out);
816
+ const outDir = path7.dirname(out2);
817
+ fs7.mkdirSync(outDir, { recursive: true });
818
+ const { payload, map: m, used } = await makePayload(v, e, photoOf, (abs) => path7.relative(outDir, abs));
819
+ if (forbid.length) {
820
+ const probe = JSON.stringify({ ...payload, map: { ...m, sessions: m.sessions.map((s) => ({ ...s, photos: [] })) } });
821
+ const leak = leaked(forbid, probe);
822
+ if (leak.length) {
823
+ const where = leak.map((w) => {
824
+ const i = w.startsWith("(?i)") ? probe.search(new RegExp(w.slice(4), "i")) : probe.toLowerCase().indexOf(w.toLowerCase());
825
+ return `${w}: \u2026${probe.slice(Math.max(0, i - 60), i + 40)}\u2026`;
826
+ });
827
+ throw new Error(`\u6B62\u3081\u308B\u8A9E\u304C\u30C7\u30FC\u30BF\u306B\u6B8B\u3063\u3066\u3044\u308B\uFF08${e.name}\uFF09:
828
+ ${where.join("\n")}`);
829
+ }
830
+ }
831
+ const html = await buildOne(payload, e.name, out2, forbid);
832
+ if (e.release) {
833
+ const dir = path7.join(CACHE, `report-${e.name}`);
834
+ writeReport(dir, { ...m, flow: void 0, sessions: m.sessions.map(({ photos: _p, ...s }) => s) }, payload.collections.flatMap((b) => b.summary ? [b.summary] : []), fs7.readFileSync(path7.join(REPO, "schema", "model.cue"), "utf8"));
835
+ const text = fs7.readdirSync(dir, { recursive: true }).filter((f) => String(f).endsWith(".md") || String(f).endsWith(".json")).map((f) => fs7.readFileSync(path7.join(dir, String(f)), "utf8")).join("\n");
836
+ const leak = leaked(forbid, text);
837
+ if (leak.length) throw new Error(`\u6B62\u3081\u308B\u8A9E\u304C\u30EC\u30DD\u30FC\u30C8\u306B\u6B8B\u3063\u3066\u3044\u308B\uFF08${e.name}\uFF09: ${leak.join(", ")}`);
838
+ let site = html;
839
+ fs7.mkdirSync(path7.join(dir, "assets"), { recursive: true });
840
+ for (const f of used) {
841
+ fs7.copyFileSync(f, path7.join(dir, "assets", path7.basename(f)));
842
+ site = site.split(JSON.stringify(path7.relative(outDir, f)).slice(1, -1)).join(`assets/${path7.basename(f)}`);
843
+ }
844
+ fs7.writeFileSync(path7.join(dir, "index.html"), site);
845
+ if (e.release) fs7.writeFileSync(path7.join(dir, "release.json"), JSON.stringify(e.release, null, 2));
846
+ console.log(`zip \u306E\u4E2D\u8EAB: ${dir}\uFF08\u5199\u771F ${used.size / 2} \u679A\uFF09`);
847
+ }
848
+ }
849
+ }
850
+
851
+ // node/export/release.ts
852
+ import { execFileSync as execFileSync3 } from "node:child_process";
853
+ import fs8 from "node:fs";
854
+ import path8 from "node:path";
855
+ function releaseZip(root, only, dir) {
856
+ const v = readRoot(root);
857
+ const e = v.config.exports.find((x) => only ? x.name === only : !!x.release);
858
+ if (!e?.release) throw new Error("release \u3092\u6301\u3064\u66F8\u304D\u51FA\u3057\u304C\u306A\u3044\uFF08chiken.yaml \u306E exports\uFF09");
859
+ const outDir = dir ?? path8.dirname(path8.resolve(root, e.out));
860
+ const name = e.release.name;
861
+ const report = path8.join(CACHE, `report-${e.name}`);
862
+ if (!fs8.existsSync(path8.join(report, "index.html"))) throw new Error(`\u66F8\u304D\u51FA\u3057\u304C\u306A\u3044\u3002\u5148\u306B\u66F8\u304D\u51FA\u3057\u3092\u6D41\u3059: ${report}`);
863
+ fs8.mkdirSync(outDir, { recursive: true });
864
+ const siteDir = path8.join(outDir, `${name}-site`);
865
+ const zip = path8.join(outDir, `${name}-site.zip`);
866
+ fs8.rmSync(siteDir, { recursive: true, force: true });
867
+ fs8.rmSync(zip, { force: true });
868
+ fs8.cpSync(report, siteDir, { recursive: true });
869
+ fs8.rmSync(path8.join(siteDir, "release.json"), { force: true });
870
+ execFileSync3("zip", ["-qr", path8.basename(zip), path8.basename(siteDir)], { cwd: outDir });
871
+ fs8.rmSync(siteDir, { recursive: true });
872
+ console.log(`${path8.relative(process.cwd(), zip)} ${(fs8.statSync(zip).size / 1024 / 1024).toFixed(1)} MB`);
873
+ return zip;
874
+ }
875
+
876
+ // node/serve.ts
877
+ import fs11 from "node:fs";
878
+ import http from "node:http";
879
+ import path11 from "node:path";
880
+ import { execFile } from "node:child_process";
881
+ import { randomBytes } from "node:crypto";
882
+
883
+ // node/root/ops.ts
884
+ import fs9 from "node:fs";
885
+ import path9 from "node:path";
886
+ var fail = (msg) => {
887
+ throw new Error(msg);
888
+ };
889
+ var today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
890
+ var safeName = (name) => name.replace(/[\\/:*?"<>|#^[\]]/g, "\u30FB").trim();
891
+ var kindOf = (v, id) => v.map.problems.some((p) => p.id === id) ? "problem" : v.map.actions.some((a) => a.id === id) ? "action" : v.map.insights.some((i) => i.id === id) ? "insight" : v.files.has(id) ? "source" : void 0;
892
+ function editFm(tx, v, id, fn) {
893
+ const file = v.files.get(id) ?? fail(`\u898B\u3064\u304B\u3089\u306A\u3044: ${id}`);
894
+ const { fm, body } = readMd(file);
895
+ fn(fm);
896
+ fm.updated = today();
897
+ tx.writeMd(file, fm, body);
898
+ return file;
899
+ }
900
+ function editInsight(tx, v, ref, fn) {
901
+ const [sid, n] = ref.split("#");
902
+ if (!n) fail(`\u77E5\u898B\u306F <\u30A4\u30F3\u30D7\u30C3\u30C8\u306E ID>#<n> \u3067\u6307\u3059\uFF08\u4F8B: conf/talk1#1\uFF09: ${ref}`);
903
+ const file = v.files.get(sid) ?? fail(`\u30A4\u30F3\u30D7\u30C3\u30C8\u304C\u306A\u3044: ${sid}\uFF08\u307E\u3068\u307E\u308A\u306E\u4E2D\u306E\u30A4\u30F3\u30D7\u30C3\u30C8\u306F <\u307E\u3068\u307E\u308A>/<\u77ED\u3044\u540D\u524D>\uFF09`);
904
+ const { fm, body } = readMd(file);
905
+ const list2 = fm.insights ?? [];
906
+ const it = list2.find((x) => String(x.n) === n) ?? fail(`\u77E5\u898B\u304C\u306A\u3044: ${ref}`);
907
+ fn(it, list2);
908
+ fm.insights = list2;
909
+ tx.writeMd(file, fm, body);
910
+ }
911
+ function nextId(v, prefix) {
912
+ const ids = (prefix === "P" ? v.map.problems : v.map.actions).map((x) => Number(x.id.slice(1))).filter(Number.isFinite);
913
+ return `${prefix}${String(Math.max(0, ...ids) + 1).padStart(prefix === "P" ? 2 : 3, "0")}`;
914
+ }
915
+ var ops = {
916
+ // 課題どうし(後の課題の before)か、アクションどうし(後のアクションの needs)をつなぐ・外す
917
+ link(tx, v, later, earlier, link) {
918
+ const k = kindOf(v, later);
919
+ if (k !== kindOf(v, earlier) || k !== "problem" && k !== "action") fail(`\u8AB2\u984C\u3069\u3046\u3057\u304B\u3001\u30A2\u30AF\u30B7\u30E7\u30F3\u3069\u3046\u3057\u3092\u3064\u306A\u3050\uFF08\u6E21\u3055\u308C\u305F ID: ${later} \u3068 ${earlier}\uFF09`);
920
+ if (later === earlier) fail("\u540C\u3058\u3082\u306E\u3069\u3046\u3057\u306F\u3064\u306A\u3052\u306A\u3044");
921
+ const field = k === "problem" ? "before" : "needs";
922
+ editFm(tx, v, later, (fm) => {
923
+ const xs = (fm[field] ?? []).filter((x) => x.id !== earlier);
924
+ if (link) xs.push({ id: earlier, kind: link.kind ?? "pre", reason: link.reason ?? fail("\u3064\u306A\u3050\u7406\u7531\uFF08reason\uFF09\u304C\u8981\u308B") });
925
+ fm[field] = xs;
926
+ });
927
+ return { later, earlier, field };
928
+ },
929
+ // 知見を課題に結ぶ・外す
930
+ tag(tx, v, ref, add, remove = []) {
931
+ let out2 = [];
932
+ editInsight(tx, v, ref, (it) => {
933
+ const cur = new Set(it.problems ?? []);
934
+ for (const p of add) cur.add(p);
935
+ for (const p of remove) cur.delete(p);
936
+ out2 = [...cur];
937
+ if (out2.length) it.problems = out2;
938
+ else delete it.problems;
939
+ });
940
+ return { id: ref, problems: out2 };
941
+ },
942
+ // frontmatter の 1 項目を変える。文章は本文で直すので、ここでは扱わない
943
+ set(tx, v, id, field, value) {
944
+ const allowed = ["kind", "area", "origin", "problem", "groups", "also", "basis", "session"];
945
+ if (!allowed.includes(field)) fail(`\u5909\u3048\u3089\u308C\u308B\u9805\u76EE: ${allowed.join(", ")}\uFF08\u6587\u7AE0\u306F\u672C\u6587\u3067\u76F4\u3059\u3002\u77E5\u898B\u306F insight set\u3001\u77E5\u898B\u3068\u8AB2\u984C\u306F tag\uFF09`);
946
+ editFm(tx, v, id, (fm) => {
947
+ fm[field] = Array.isArray(value) ? value.length ? value : void 0 : value || void 0;
948
+ });
949
+ return { id, field, value };
950
+ },
951
+ // 知見の項目を変える(kind・author・verify・groups・text・who)。groups はカンマ区切り
952
+ setInsight(tx, v, ref, field, value) {
953
+ if (!["kind", "author", "verify", "groups", "text", "who"].includes(field)) fail(`\u77E5\u898B\u3067\u5909\u3048\u3089\u308C\u308B\u9805\u76EE: kind, author, verify, groups, text, who`);
954
+ if (field === "text" && !value) fail("\u77E5\u898B\u306E\u6587\u306F\u7A7A\u306B\u3067\u304D\u306A\u3044");
955
+ const v2 = field === "groups" ? (value ?? "").split(",").map((x) => x.trim()).filter(Boolean) : value;
956
+ editInsight(tx, v, ref, (it) => {
957
+ if (Array.isArray(v2) ? v2.length : v2) it[field] = v2;
958
+ else delete it[field];
959
+ });
960
+ return { id: ref, field, value };
961
+ },
962
+ newProblem(tx, v, a) {
963
+ if (!a.now.length) fail("\u4ECA\u306E\u72B6\u614B\uFF08now\uFF09\u304C\u8981\u308B");
964
+ const id = nextId(v, "P");
965
+ const file = path9.join(v.root, LAYOUT.problems, `${id} ${safeName(a.name)}.md`);
966
+ tx.writeMd(file, { id, area: a.area, origin: a.origin ?? "ai", updated: today() }, `# ${a.name}
967
+
968
+ ## \u4ECA\u306E\u72B6\u614B
969
+
970
+ ${a.now.map((t) => `- ${t}`).join("\n")}
971
+ ${a.why ? `
972
+ ## \u306A\u305C\u8AB2\u984C\u3068\u898B\u305F\u304B
973
+
974
+ ${a.why}
975
+ ` : ""}`);
976
+ return { id, file: path9.relative(v.root, file) };
977
+ },
978
+ newAction(tx, v, a) {
979
+ const id = nextId(v, "A");
980
+ const file = path9.join(v.root, LAYOUT.actions, `${id} ${safeName(a.name)}.md`);
981
+ tx.writeMd(file, { id, kind: a.kind, origin: a.origin ?? "ai", problem: a.problem, also: a.also, basis: a.basis, updated: today() }, `# ${a.name}
982
+
983
+ ## \u78BA\u304B\u3081\u308B\u3053\u3068
984
+
985
+ ${a.check ?? ""}
986
+
987
+ ## \u7D42\u308F\u308A\u306E\u6761\u4EF6
988
+
989
+ ${a.done ?? ""}
990
+
991
+ ## \u52B9\u304D\u305D\u3046\u306A\u7406\u7531
992
+
993
+ ${a.why ?? ""}
994
+ `);
995
+ return { id, file: path9.relative(v.root, file) };
996
+ },
997
+ // インプットのノートの枠を作る。まとまりの中なら <まとまり>/(メモは notes/)、まとまりのないインプットは items/<年>/ に置く
998
+ addSource(tx, v, a) {
999
+ if (!(a.medium in MEDIUM)) fail(`\u5A92\u4F53\u306E\u5024: ${Object.keys(MEDIUM).join(", ")}`);
1000
+ if (a.medium !== "note" && !a.taken) fail(`--taken \u304C\u8981\u308B\uFF08${Object.keys(TAKEN).join(", ")}\uFF09`);
1001
+ if (a.taken && !(a.taken in TAKEN)) fail(`\u53D7\u3051\u53D6\u308A\u65B9\u306E\u5024: ${Object.keys(TAKEN).join(", ")}`);
1002
+ if (a.day && !a.collection) fail("--day \u306F\u307E\u3068\u307E\u308A\uFF08\u30A4\u30D9\u30F3\u30C8\uFF09\u306E\u4E2D\u306E\u767B\u58C7\u3060\u3051");
1003
+ if (a.date && !/^\d{4}-\d{2}-\d{2}$/.test(a.date)) fail("\u65E5\u4ED8\u306F YYYY-MM-DD");
1004
+ let file;
1005
+ let id;
1006
+ const name = `${safeName(a.file ?? a.title)}.md`;
1007
+ if (a.collection) {
1008
+ const b = v.collections.find((x) => x.id === a.collection) ?? fail(`\u307E\u3068\u307E\u308A\u304C\u306A\u3044: ${a.collection}\uFF08\u4F7F\u3048\u308B\u307E\u3068\u307E\u308A: ${v.collections.map((x) => x.id).join(", ") || "\u306A\u3057"}\uFF09`);
1009
+ id = `${b.id}/${a.id}`;
1010
+ file = path9.join(v.root, b.dir, a.medium === "note" ? "notes" : "", name);
1011
+ } else {
1012
+ id = a.id;
1013
+ file = path9.join(v.root, LAYOUT.sources, "items", (a.date ?? today()).slice(0, 4), name);
1014
+ }
1015
+ if (v.sourceOf.has(id)) fail(`\u30A4\u30F3\u30D7\u30C3\u30C8\u306E ID \u304C\u91CD\u306A\u308B: ${id}`);
1016
+ if (fs9.existsSync(file)) fail(`\u30D5\u30A1\u30A4\u30EB\u304C\u3059\u3067\u306B\u3042\u308B: ${file}`);
1017
+ tx.writeMd(file, { id, medium: a.medium, type: a.type, taken: a.medium === "note" ? void 0 : a.taken, title: a.title, org: a.org, who: a.who, date: a.date, day: a.day ? Number(a.day) : void 0, time: a.time, url: a.url }, `# ${a.title}
1018
+ `);
1019
+ return { id, file: path9.relative(v.root, file) };
1020
+ },
1021
+ addInsight(tx, v, sid, a) {
1022
+ const file = v.files.get(sid) ?? fail(`\u30A4\u30F3\u30D7\u30C3\u30C8\u304C\u306A\u3044: ${sid}`);
1023
+ const { fm, body } = readMd(file);
1024
+ const list2 = fm.insights ?? [];
1025
+ const n = Math.max(0, ...list2.map((x) => Number(x.n) || 0)) + 1;
1026
+ list2.push(Object.fromEntries(Object.entries({ n, ...a, problems: a.problems?.length ? a.problems : void 0 }).filter(([, x]) => x !== void 0)));
1027
+ fm.insights = list2;
1028
+ tx.writeMd(file, fm, body);
1029
+ return { id: `${sid}#${n}` };
1030
+ },
1031
+ // 課題・アクションの名前を変える。本文の 1 行目の見出しとファイル名を変え、データフォルダの中の wiki リンクを張り替える。ID は変えない。
1032
+ // origin: self の名前は本人の言葉なので、force を付けたときだけ変える
1033
+ rename(tx, v, id, name, force = false) {
1034
+ const k = kindOf(v, id);
1035
+ if (k !== "problem" && k !== "action") fail("\u540D\u524D\u3092\u5909\u3048\u3089\u308C\u308B\u306E\u306F\u8AB2\u984C\u3068\u30A2\u30AF\u30B7\u30E7\u30F3");
1036
+ const item = k === "problem" ? v.map.problems.find((p) => p.id === id) : v.map.actions.find((a) => a.id === id);
1037
+ if (item.origin === "self" && !force) fail(`${id} \u306F\u672C\u4EBA\u304C\u4ED8\u3051\u305F\u540D\u524D\uFF08origin: self\uFF09\u3002\u5909\u3048\u308B\u306A\u3089 force \u3092\u4ED8\u3051\u308B`);
1038
+ const file = v.files.get(id);
1039
+ const { fm, body } = readMd(file);
1040
+ if (!/^#\s+.+$/m.test(body)) fail(`${id} \u306E\u672C\u6587\u306B\u898B\u51FA\u3057\u304C\u306A\u3044`);
1041
+ const to = path9.join(path9.dirname(file), `${id} ${safeName(name)}.md`);
1042
+ fm.updated = today();
1043
+ const nextBody = body.replace(/^#\s+.+$/m, `# ${name}`);
1044
+ if (to !== file) {
1045
+ if (fs9.existsSync(to)) fail(`\u30D5\u30A1\u30A4\u30EB\u304C\u3059\u3067\u306B\u3042\u308B: ${to}`);
1046
+ tx.remove(file);
1047
+ }
1048
+ tx.writeMd(to, fm, nextBody);
1049
+ const base = linkRoot(v.root, v.config);
1050
+ const oldRef = path9.relative(base, file).replace(/\.md$/, "");
1051
+ const newRef = path9.relative(base, to).replace(/\.md$/, "");
1052
+ const relinked = [];
1053
+ if (oldRef !== newRef) {
1054
+ for (const f of mdFiles(v.root)) {
1055
+ if (f === to || f.includes(`${path9.sep}.chiken${path9.sep}`)) continue;
1056
+ const text = fs9.readFileSync(f, "utf8");
1057
+ if (!text.includes(`[[${oldRef}`)) continue;
1058
+ tx.writeRaw(f, text.split(`[[${oldRef}`).join(`[[${newRef}`));
1059
+ relinked.push(path9.relative(v.root, f));
1060
+ }
1061
+ }
1062
+ return { id, name, file: path9.relative(v.root, to), relinked };
1063
+ },
1064
+ // 同じインプットの中で重なる知見を 1 件にまとめる。drop の課題を keep に足し、drop を根拠にしていたアクションを keep に付け替えて、drop を消す
1065
+ merge(tx, v, keep, drop) {
1066
+ if (keep.split("#")[0] !== drop.split("#")[0]) fail("\u307E\u3068\u3081\u3089\u308C\u308B\u306E\u306F\u540C\u3058\u30A4\u30F3\u30D7\u30C3\u30C8\u306E\u77E5\u898B\u3060\u3051");
1067
+ const d = v.map.insights.find((i) => i.id === drop) ?? fail(`\u77E5\u898B\u304C\u306A\u3044: ${drop}`);
1068
+ ops.tag(tx, v, keep, d.problems);
1069
+ for (const a of v.map.actions.filter((x) => x.basis?.includes(drop))) {
1070
+ editFm(tx, v, a.id, (fm) => {
1071
+ fm.basis = [...new Set((fm.basis ?? []).map((x) => x === drop ? keep : x))];
1072
+ });
1073
+ }
1074
+ editInsight(tx, v, drop, (it, list2) => {
1075
+ list2.splice(list2.indexOf(it), 1);
1076
+ });
1077
+ return { keep, drop, problems: [.../* @__PURE__ */ new Set([...v.map.insights.find((i) => i.id === keep)?.problems ?? [], ...d.problems])] };
1078
+ },
1079
+ // 課題・アクション・知見を消し、ほかから指しているところも外す。課題を主な課題にしているアクションがあれば止める
1080
+ rm(tx, v, id) {
1081
+ const k = kindOf(v, id);
1082
+ const m = v.map;
1083
+ const touchedIds = [];
1084
+ if (k === "problem") {
1085
+ const owners = m.actions.filter((a) => a.problem === id).map((a) => a.id);
1086
+ if (owners.length) fail(`${id} \u3092\u4E3B\u306A\u8AB2\u984C\u306B\u3057\u3066\u3044\u308B\u30A2\u30AF\u30B7\u30E7\u30F3\u304C\u3042\u308B: ${owners.join(" ")}\uFF08\u5148\u306B\u4ED8\u3051\u66FF\u3048\u308B\u304B\u6D88\u3059\uFF09`);
1087
+ for (const p of m.problemLinks.filter((l) => l.up === id)) {
1088
+ editFm(tx, v, p.down, (fm) => {
1089
+ fm.before = (fm.before ?? []).filter((x) => x.id !== id);
1090
+ });
1091
+ touchedIds.push(p.down);
1092
+ }
1093
+ for (const a of m.actions.filter((x) => x.also?.includes(id))) {
1094
+ editFm(tx, v, a.id, (fm) => {
1095
+ fm.also = (fm.also ?? []).filter((x) => x !== id);
1096
+ });
1097
+ touchedIds.push(a.id);
1098
+ }
1099
+ for (const i of m.insights.filter((x) => x.problems.includes(id))) {
1100
+ ops.tag(tx, v, i.id, [], [id]);
1101
+ touchedIds.push(i.id);
1102
+ }
1103
+ tx.remove(v.files.get(id));
1104
+ } else if (k === "action") {
1105
+ for (const l of m.actionLinks.filter((x) => x.from === id)) {
1106
+ editFm(tx, v, l.to, (fm) => {
1107
+ fm.needs = (fm.needs ?? []).filter((x) => x.id !== id);
1108
+ });
1109
+ touchedIds.push(l.to);
1110
+ }
1111
+ tx.remove(v.files.get(id));
1112
+ } else if (k === "insight") {
1113
+ for (const a of m.actions.filter((x) => x.basis?.includes(id))) {
1114
+ editFm(tx, v, a.id, (fm) => {
1115
+ fm.basis = (fm.basis ?? []).filter((x) => x !== id);
1116
+ });
1117
+ touchedIds.push(a.id);
1118
+ }
1119
+ editInsight(tx, v, id, (it, list2) => {
1120
+ list2.splice(list2.indexOf(it), 1);
1121
+ });
1122
+ } else fail(`\u6D88\u305B\u308B\u306E\u306F\u8AB2\u984C\u30FB\u30A2\u30AF\u30B7\u30E7\u30F3\u30FB\u77E5\u898B: ${id}`);
1123
+ return { id, kind: k, touched: touchedIds };
1124
+ }
1125
+ };
1126
+
1127
+ // node/root/tx.ts
1128
+ import fs10 from "node:fs";
1129
+ import path10 from "node:path";
1130
+ import YAML2 from "yaml";
1131
+
1132
+ // node/root/check.ts
1133
+ function check(v) {
1134
+ const f = [];
1135
+ const err = (msg) => f.push({ level: "error", msg });
1136
+ const warn = (msg) => f.push({ level: "warn", msg });
1137
+ const m = v.map;
1138
+ const dup = (xs, what) => {
1139
+ const seen = /* @__PURE__ */ new Set();
1140
+ for (const x of xs) {
1141
+ if (seen.has(x)) err(`${what} \u306E\u91CD\u306A\u308A: ${x}`);
1142
+ seen.add(x);
1143
+ }
1144
+ };
1145
+ dup(m.problems.map((p) => p.id), "\u8AB2\u984C\u306E ID");
1146
+ dup(m.actions.map((a) => a.id), "\u30A2\u30AF\u30B7\u30E7\u30F3\u306E ID");
1147
+ dup(m.insights.map((i) => i.id), "\u77E5\u898B\u306E\u756A\u53F7");
1148
+ dup([...v.sourceOf.keys()], "\u30A4\u30F3\u30D7\u30C3\u30C8\u306E ID");
1149
+ for (const p of m.problems) if (!/^P\d{2,}$/.test(p.id)) err(`\u8AB2\u984C\u306E ID \u306E\u5F62: ${p.id}`);
1150
+ for (const a of m.actions) if (!/^A\d{3,}$/.test(a.id)) err(`\u30A2\u30AF\u30B7\u30E7\u30F3\u306E ID \u306E\u5F62: ${a.id}`);
1151
+ const P = new Set(m.problems.map((p) => p.id));
1152
+ const A = new Set(m.actions.map((a) => a.id));
1153
+ const I = new Set(m.insights.map((i) => i.id));
1154
+ const areas = new Set(m.problemAreas.map((a) => a.id));
1155
+ const ctx = new Set(m.contexts.map((c) => c.id));
1156
+ for (const a of m.problemAreas) if (a.context && !ctx.has(a.context)) err(`\u9818\u57DF ${a.id} \u306E\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u304C\u306A\u3044: ${a.context}\uFF08areas.md \u306E contexts\uFF09`);
1157
+ for (const p of m.problems) {
1158
+ if (!areas.has(p.area)) err(`${p.id} \u306E\u9818\u57DF\u304C\u306A\u3044: ${p.area}`);
1159
+ if (!["self", "ai"].includes(p.origin)) err(`${p.id} \u306E\u51FA\u3069\u3053\u308D\uFF08origin\uFF09\u306E\u5024: ${p.origin}\uFF08self / ai\uFF09`);
1160
+ }
1161
+ for (const l of m.problemLinks) {
1162
+ if (!P.has(l.up)) err(`${l.down} \u306E before\uFF08\u524D\u306B\u3042\u308B\u8AB2\u984C\uFF09\u306B\u3001\u306A\u3044\u8AB2\u984C: ${l.up}`);
1163
+ if (!["pre", "ease", "same"].includes(l.kind)) err(`${l.down} \u306E before \u306E\u7A2E\u985E\u306E\u5024: ${l.kind}\uFF08pre / ease / same\uFF09`);
1164
+ }
1165
+ for (const a of m.actions) {
1166
+ if (!P.has(a.problem)) err(`${a.id} \u306E\u4E3B\u306A\u8AB2\u984C\u304C\u306A\u3044: ${a.problem}`);
1167
+ for (const x of a.also ?? []) if (!P.has(x)) err(`${a.id} \u306E\u3042\u308F\u305B\u3066\u9032\u3080\u8AB2\u984C\u304C\u306A\u3044: ${x}`);
1168
+ for (const b of a.basis ?? []) if (!I.has(b)) err(`${a.id} \u306E\u6839\u62E0\u306E\u77E5\u898B\u304C\u306A\u3044: ${b}`);
1169
+ if (!["study", "try", "change"].includes(a.kind)) err(`${a.id} \u306E\u7A2E\u985E\uFF08kind\uFF09\u306E\u5024: ${a.kind}\uFF08study / try / change\uFF09`);
1170
+ if (!a.basis?.length) warn(`${a.id} \u306B\u6839\u62E0\u306E\u77E5\u898B\u304C\u306A\u3044\uFF08chiken set ${a.id} basis <\u77E5\u898B>,\u2026\uFF09`);
1171
+ if (!a.why) warn(`${a.id} \u306B\u300C\u52B9\u304D\u305D\u3046\u306A\u7406\u7531\u300D\u304C\u306A\u3044\uFF08\u672C\u6587\u306E ## \u52B9\u304D\u305D\u3046\u306A\u7406\u7531 \u306B\u66F8\u304F\uFF09`);
1172
+ }
1173
+ for (const l of m.actionLinks) {
1174
+ if (!A.has(l.from)) err(`${l.to} \u306E needs\uFF08\u524D\u306B\u8981\u308B\u30A2\u30AF\u30B7\u30E7\u30F3\uFF09\u306B\u3001\u306A\u3044\u30A2\u30AF\u30B7\u30E7\u30F3: ${l.from}`);
1175
+ if (!["pre", "alt"].includes(l.kind)) err(`${l.to} \u306E needs \u306E\u7A2E\u985E\u306E\u5024: ${l.kind}\uFF08pre / alt\uFF09`);
1176
+ }
1177
+ for (const i of m.insights) {
1178
+ for (const p of i.problems) if (!P.has(p)) err(`${i.id} \u306E\u624B\u304C\u304B\u308A\u306B\u306A\u308B\u8AB2\u984C\u304C\u306A\u3044: ${p}`);
1179
+ if (!["fact", "impression"].includes(i.kind)) err(`${i.id} \u306E\u7A2E\u985E\uFF08kind\uFF09\u306E\u5024: ${i.kind}\uFF08fact / impression\uFF09`);
1180
+ if (!["self", "external", "ai"].includes(i.author)) err(`${i.id} \u306E\u66F8\u304D\u624B\uFF08author\uFF09\u306E\u5024: ${i.author}\uFF08self / external / ai\uFF09`);
1181
+ }
1182
+ const G = /^[a-z0-9][a-z0-9-]*$/;
1183
+ const groupsOf = [...m.problems.map((p) => [p.id, p.groups]), ...m.actions.map((a) => [a.id, a.groups]), ...m.insightSources.map((x) => [x.id, x.groups]), ...m.insights.map((i) => [i.id, i.groups])];
1184
+ for (const [id, gs] of groupsOf) for (const g of gs ?? []) if (!G.test(g)) err(`${id} \u306E\u30B0\u30EB\u30FC\u30D7\u306E\u540D\u524D: ${g}\uFF08\u82F1\u5C0F\u6587\u5B57\u30FB\u6570\u5B57\u30FB\u30CF\u30A4\u30D5\u30F3\uFF09`);
1185
+ for (const id of v.legacyShare) err(`${id} \u306B share \u304C\u3042\u308B\u3002\u4ECA\u306F groups \u3067\u66F8\u304F\uFF08share: self \u306F groups: [private] \u306B\u3057\u3001\u66F8\u304D\u51FA\u3057\u3067 exclude: [private]\uFF09`);
1186
+ const used = new Set(groupsOf.flatMap(([, gs]) => gs ?? []));
1187
+ for (const e of v.config.exports ?? []) {
1188
+ if (e.rules && !v.config.rules?.[e.rules]) err(`\u66F8\u304D\u51FA\u3057 ${e.name} \u306E rules \u304C\u306A\u3044: ${e.rules}\uFF08chiken.yaml \u306E rules\uFF09`);
1189
+ for (const g of [...e.include ?? [], ...e.exclude ?? []]) if (!used.has(g)) warn(`\u66F8\u304D\u51FA\u3057 ${e.name} \u306E\u30B0\u30EB\u30FC\u30D7 ${g} \u3092\u6301\u3064\u3082\u306E\u304C\u306A\u3044\uFF08\u7DB4\u308A\u3092\u78BA\u304B\u3081\u308B\uFF09`);
1190
+ if (e.audience !== void 0) err(`\u66F8\u304D\u51FA\u3057 ${e.name} \u306B audience \u304C\u3042\u308B\u3002\u4ECA\u306F exclude \u3068 rules \u3067\u66F8\u304F\uFF08ADR-0011\uFF09`);
1191
+ }
1192
+ if (v.config.org !== void 0) err("chiken.yaml \u306B org \u304C\u3042\u308B\u3002\u4ECA\u306F rules \u306B\u540D\u524D\u3092\u4ED8\u3051\u3066\u66F8\u304D\u3001\u66F8\u304D\u51FA\u3057\u306E rules \u3067\u6307\u3059\uFF08ADR-0011\uFF09");
1193
+ const cyc = (edges, what) => {
1194
+ const g = /* @__PURE__ */ new Map();
1195
+ for (const [a, b] of edges) g.set(a, [...g.get(a) ?? [], b]);
1196
+ const state = /* @__PURE__ */ new Map();
1197
+ const dfs = (n, trail) => {
1198
+ state.set(n, 1);
1199
+ for (const x of g.get(n) ?? []) {
1200
+ if (state.get(x) === 1) err(`${what}\u306E\u8F2A: ${[...trail, n, x].join(" \u2192 ")}`);
1201
+ else if (!state.has(x)) dfs(x, [...trail, n]);
1202
+ }
1203
+ state.set(n, 2);
1204
+ };
1205
+ for (const n of g.keys()) if (!state.has(n)) dfs(n, []);
1206
+ };
1207
+ cyc(m.problemLinks.filter((l) => l.kind !== "same").map((l) => [l.up, l.down]), "\u8AB2\u984C\u306E\u524D\u5F8C");
1208
+ cyc(m.actionLinks.filter((l) => l.kind === "pre").map((l) => [l.from, l.to]), "\u30A2\u30AF\u30B7\u30E7\u30F3\u306E\u524D\u5F8C");
1209
+ for (const p of m.problems) {
1210
+ const acts = m.actions.some((a) => a.problem === p.id || a.also?.includes(p.id));
1211
+ const links = m.problemLinks.some((l) => l.up === p.id || l.down === p.id);
1212
+ const ins = m.insights.some((i) => i.problems.includes(p.id));
1213
+ if (!acts && !links && !ins) warn(`${p.id} \u306F\u3064\u306A\u304C\u308A\u3082\u77E5\u898B\u3082\u30A2\u30AF\u30B7\u30E7\u30F3\u3082\u306A\u3044`);
1214
+ else if (!acts) warn(`${p.id} \u306B\u30A2\u30AF\u30B7\u30E7\u30F3\u304C\u306A\u3044`);
1215
+ }
1216
+ const loose = m.insights.filter((i) => !i.problems.length).length;
1217
+ if (loose) warn(`\u3069\u306E\u8AB2\u984C\u306B\u3082\u7D50\u3070\u308C\u3066\u3044\u306A\u3044\u77E5\u898B: ${loose} \u4EF6`);
1218
+ return f;
1219
+ }
1220
+ function runCheck(root) {
1221
+ const v = readRoot(root);
1222
+ const findings = check(v);
1223
+ let schema = null;
1224
+ try {
1225
+ vetMap(v.map);
1226
+ } catch (e) {
1227
+ schema = e.message;
1228
+ }
1229
+ return { ok: !schema && !findings.some((x) => x.level === "error"), schema, findings };
1230
+ }
1231
+
1232
+ // node/root/tx.ts
1233
+ function toYaml(o) {
1234
+ const doc = new YAML2.Document(o);
1235
+ YAML2.visit(doc, { Seq(_, node) {
1236
+ if (node.items.every((x) => YAML2.isScalar(x) && String(x.value).length <= 32)) node.flow = true;
1237
+ } });
1238
+ return doc.toString({ lineWidth: 0, flowCollectionPadding: false });
1239
+ }
1240
+ var Tx = class {
1241
+ constructor(root) {
1242
+ this.root = root;
1243
+ }
1244
+ root;
1245
+ stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
1246
+ created = [];
1247
+ // 新しく作ったファイル(戻すときは消す)
1248
+ saved = [];
1249
+ // 書き換える前のファイルのバックアップ(戻すときに写し戻す)
1250
+ touched = false;
1251
+ get historyDir() {
1252
+ return path10.join(this.root, ".chiken", "history", this.stamp);
1253
+ }
1254
+ backup(file) {
1255
+ if (!fs10.existsSync(file)) {
1256
+ if (!this.created.includes(file)) this.created.push(file);
1257
+ return;
1258
+ }
1259
+ const to = path10.join(this.historyDir, path10.relative(this.root, file));
1260
+ if (fs10.existsSync(to)) return;
1261
+ fs10.mkdirSync(path10.dirname(to), { recursive: true });
1262
+ fs10.copyFileSync(file, to);
1263
+ this.saved.push({ file, copy: to });
1264
+ }
1265
+ writeMd(file, fm, body) {
1266
+ this.backup(file);
1267
+ fs10.mkdirSync(path10.dirname(file), { recursive: true });
1268
+ const clean = Object.fromEntries(Object.entries(fm).filter(([, v]) => v !== void 0 && v !== null && !(Array.isArray(v) && !v.length)));
1269
+ fs10.writeFileSync(file, `---
1270
+ ${toYaml(clean)}---
1271
+
1272
+ ${body.replace(/^\n+/, "").replace(/\s*$/, "\n")}`);
1273
+ this.touched = true;
1274
+ }
1275
+ // 本文ごと書き換える(名前を変えたときの wiki リンクの張り替えだけに使う)
1276
+ writeRaw(file, text) {
1277
+ this.backup(file);
1278
+ fs10.writeFileSync(file, text);
1279
+ this.touched = true;
1280
+ }
1281
+ remove(file) {
1282
+ this.backup(file);
1283
+ fs10.rmSync(file);
1284
+ this.touched = true;
1285
+ }
1286
+ rollback() {
1287
+ for (const { file, copy } of this.saved) {
1288
+ fs10.mkdirSync(path10.dirname(file), { recursive: true });
1289
+ fs10.copyFileSync(copy, file);
1290
+ }
1291
+ for (const f of this.created) fs10.rmSync(f, { force: true });
1292
+ }
1293
+ };
1294
+ function transact(root, fn, opts = {}) {
1295
+ const tx = new Tx(root);
1296
+ let result;
1297
+ try {
1298
+ result = fn(tx, readRoot(root));
1299
+ } catch (e) {
1300
+ tx.rollback();
1301
+ throw e;
1302
+ }
1303
+ if (!tx.touched) return { result, check: null, rolledBack: false, history: tx.historyDir };
1304
+ let c;
1305
+ try {
1306
+ c = runCheck(root);
1307
+ } catch (e) {
1308
+ tx.rollback();
1309
+ throw e;
1310
+ }
1311
+ const rolledBack = !c.ok && !opts.force;
1312
+ if (rolledBack) tx.rollback();
1313
+ return { result, check: c, rolledBack, history: tx.historyDir };
1314
+ }
1315
+
1316
+ // node/serve.ts
1317
+ var ALLOWED = ["link", "tag", "set", "setInsight", "rename", "rm", "merge"];
1318
+ async function serve(root, opts) {
1319
+ console.log("\u753B\u9762\u3092\u30D3\u30EB\u30C9\u3057\u3066\u3044\u308B\u2026");
1320
+ const token = randomBytes(24).toString("hex");
1321
+ const built2 = await buildApp({ payload: null, edit: true, title: opts.edit ? "chiken\uFF08\u7DE8\u96C6\u30E2\u30FC\u30C9\uFF09" : "chiken" });
1322
+ const html = built2.replace("<head>", `<head><meta name="chiken-token" content="${token}">`);
1323
+ const hosts = /* @__PURE__ */ new Set([`127.0.0.1:${opts.port}`, `localhost:${opts.port}`]);
1324
+ let photoOf = null;
1325
+ let photoFiles = /* @__PURE__ */ new Set();
1326
+ const payload = async () => {
1327
+ const v = readRoot(root);
1328
+ photoOf ??= await preparePhotos(v);
1329
+ const found = v.config.exports.find((x) => x.name === opts.exportName);
1330
+ const e = found ? { ...found, include: void 0, exclude: void 0, rules: void 0, firsthand: false } : { name: "edit", title: v.config.title, subtitle: v.config.lead, problems: "all", out: "" };
1331
+ photoFiles = new Set([...photoOf.values()].flat().flatMap((x) => [x.t, x.f]));
1332
+ const { payload: p } = await makePayload(v, e, photoOf, (abs) => `/file/${encodeURIComponent(path11.relative(root, abs))}`);
1333
+ if (opts.edit) p.edit = { files: Object.fromEntries([...v.files].map(([id, f]) => [id, path11.relative(root, f)])) };
1334
+ return p;
1335
+ };
1336
+ const send = (res, code, body, type = "application/json") => {
1337
+ res.writeHead(code, { "content-type": `${type}; charset=utf-8`, "cache-control": "no-store" });
1338
+ res.end(typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body));
1339
+ };
1340
+ const readBody = (req) => new Promise((ok) => {
1341
+ let b = "";
1342
+ req.on("data", (c) => {
1343
+ b += c;
1344
+ });
1345
+ req.on("end", () => ok(b));
1346
+ });
1347
+ const server = http.createServer(async (req, res) => {
1348
+ const url = new URL(req.url ?? "/", "http://localhost");
1349
+ try {
1350
+ if (!hosts.has(req.headers.host ?? "")) return send(res, 403, "forbidden", "text/plain");
1351
+ if (url.pathname.startsWith("/api/")) {
1352
+ if (req.headers["x-chiken-token"] !== token) return send(res, 403, { error: "\u30C8\u30FC\u30AF\u30F3\u304C\u5408\u308F\u306A\u3044\uFF08\u753B\u9762\u3092\u958B\u304D\u76F4\u3059\uFF09" });
1353
+ if (req.method === "POST" && !(req.headers["content-type"] ?? "").startsWith("application/json")) return send(res, 415, { error: "JSON \u3067\u9001\u308B" });
1354
+ }
1355
+ if (req.method === "GET" && url.pathname === "/") return send(res, 200, html, "text/html");
1356
+ if (req.method === "GET" && url.pathname === "/api/payload") return send(res, 200, await payload());
1357
+ if (req.method === "POST" && url.pathname === "/api/op") {
1358
+ if (!opts.edit) return send(res, 403, { error: "\u7DE8\u96C6\u30E2\u30FC\u30C9\u3067\u306F\u306A\u3044\uFF08--edit \u3092\u4ED8\u3051\u3066\u958B\u304F\uFF09" });
1359
+ const { op, args } = JSON.parse(await readBody(req));
1360
+ if (!ALLOWED.includes(op)) return send(res, 400, { error: `\u4F7F\u3048\u306A\u3044\u547D\u4EE4: ${op}` });
1361
+ const fn = ops[op];
1362
+ const r = transact(root, (tx, v) => fn(tx, v, ...args));
1363
+ const errors = r.check ? [...r.check.schema ? [r.check.schema] : [], ...r.check.findings.filter((x) => x.level === "error").map((x) => x.msg)] : [];
1364
+ console.log(`${op} ${JSON.stringify(args)} \u2192 ${r.rolledBack ? "\u623B\u3057\u305F" : "\u66F8\u3044\u305F"}`);
1365
+ return send(res, r.rolledBack ? 409 : 200, { ok: !r.rolledBack, result: r.result, errors });
1366
+ }
1367
+ if (req.method === "POST" && url.pathname === "/api/open") {
1368
+ if (!opts.edit) return send(res, 403, { error: "\u7DE8\u96C6\u30E2\u30FC\u30C9\u3067\u306F\u306A\u3044" });
1369
+ const { id } = JSON.parse(await readBody(req));
1370
+ const f = readRoot(root).files.get(id);
1371
+ if (!f) return send(res, 404, { error: `\u898B\u3064\u304B\u3089\u306A\u3044: ${id}` });
1372
+ const [cmd, ...pre] = process.platform === "darwin" ? ["open"] : process.platform === "win32" ? ["cmd", "/c", "start", ""] : ["xdg-open"];
1373
+ execFile(cmd, [...pre, f]);
1374
+ return send(res, 200, { ok: true });
1375
+ }
1376
+ if (req.method === "GET" && url.pathname.startsWith("/file/")) {
1377
+ const f = path11.resolve(root, decodeURIComponent(url.pathname.slice("/file/".length)));
1378
+ if (!photoFiles.has(f) || !fs11.existsSync(f)) return send(res, 404, "not found", "text/plain");
1379
+ return send(res, 200, fs11.readFileSync(f), "image/jpeg");
1380
+ }
1381
+ send(res, 404, "not found", "text/plain");
1382
+ } catch (e) {
1383
+ send(res, 400, { error: e.message });
1384
+ }
1385
+ });
1386
+ server.listen(opts.port, "127.0.0.1", () => console.log(`http://127.0.0.1:${opts.port}/ ${opts.edit ? "\uFF08\u7DE8\u96C6\u30E2\u30FC\u30C9\uFF09" : ""}`));
1387
+ }
1388
+
1389
+ // node/root/init.ts
1390
+ import fs12 from "node:fs";
1391
+ import path12 from "node:path";
1392
+ function initRoot(dir, title2 = "chiken") {
1393
+ if (fs12.existsSync(path12.join(dir, LAYOUT.config))) throw new Error(`\u3059\u3067\u306B chiken \u306E\u30C7\u30FC\u30BF\u30D5\u30A9\u30EB\u30C0\u304C\u3042\u308B: ${dir}`);
1394
+ const files = {
1395
+ [LAYOUT.config]: `name: chiken
1396
+ title: ${title2}
1397
+ lead: \u62FE\u3063\u305F\u77E5\u898B\u3068\u3001\u5411\u304D\u5408\u3063\u3066\u3044\u308B\u8AB2\u984C\u3001\u6B21\u306B\u3084\u308B\u30A2\u30AF\u30B7\u30E7\u30F3\u3092\u3064\u306A\u3044\u3060\u5730\u56F3\u3002
1398
+ exports:
1399
+ - name: all
1400
+ title: ${title2}
1401
+ problems: all
1402
+ out: exports/all.html
1403
+ `,
1404
+ [LAYOUT.areas]: `---
1405
+ contexts:
1406
+ - id: main
1407
+ name: \u81EA\u5206\u306E\u4ED5\u4E8B
1408
+ areas:
1409
+ - id: general
1410
+ name: \u5168\u822C
1411
+ context: main
1412
+ sum: \u307E\u3060\u5206\u3051\u3066\u3044\u306A\u3044\u8AB2\u984C\u3002
1413
+ ---
1414
+
1415
+ # \u9818\u57DF
1416
+
1417
+ \u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\uFF08\u8AB2\u984C\u304C\u5C5E\u3059\u308B\u7D44\u7E54\u3084\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\uFF09\u3068\u3001\u8AB2\u984C\u3092\u5206\u3051\u308B\u9818\u57DF\u3092 frontmatter \u306B\u66F8\u304F\u3002
1418
+ `,
1419
+ ".gitignore": "exports/\n.chiken/\n"
1420
+ };
1421
+ const made = [];
1422
+ for (const d of [LAYOUT.problems, LAYOUT.actions, path12.join(LAYOUT.sources, "items")]) {
1423
+ fs12.mkdirSync(path12.join(dir, d), { recursive: true });
1424
+ fs12.writeFileSync(path12.join(dir, d, ".gitkeep"), "");
1425
+ made.push(`${d}/`);
1426
+ }
1427
+ for (const [f, body] of Object.entries(files)) {
1428
+ fs12.writeFileSync(path12.join(dir, f), body);
1429
+ made.push(f);
1430
+ }
1431
+ return made;
1432
+ }
1433
+
1434
+ // node/cli.ts
1435
+ var argv = process.argv.slice(2);
1436
+ var BOOL = /* @__PURE__ */ new Set(["json", "force", "edit", "help"]);
1437
+ var KNOWN = /* @__PURE__ */ new Set([...BOOL, "root", "port", "export", "name", "area", "now", "why", "origin", "problem", "kind", "also", "basis", "check", "done", "title", "id", "collection", "type", "taken", "date", "day", "time", "file", "url", "org", "who", "text", "problems", "verify", "reason", "source", "author"]);
1438
+ var flags = /* @__PURE__ */ new Map();
1439
+ var pos = [];
1440
+ for (let i = 0; i < argv.length; i++) {
1441
+ const a = argv[i];
1442
+ if (a.startsWith("--")) {
1443
+ const eq = a.indexOf("=");
1444
+ const k = eq < 0 ? a.slice(2) : a.slice(2, eq);
1445
+ const v = eq < 0 ? void 0 : a.slice(eq + 1);
1446
+ if (v !== void 0) flags.set(k, v);
1447
+ else if (!BOOL.has(k) && argv[i + 1] && !argv[i + 1].startsWith("--")) flags.set(k, argv[++i]);
1448
+ else flags.set(k, true);
1449
+ } else pos.push(a);
1450
+ }
1451
+ var flag = (k) => {
1452
+ const v = flags.get(k);
1453
+ return typeof v === "string" ? v : void 0;
1454
+ };
1455
+ var json = flags.has("json");
1456
+ var list = (v) => v ? v.split(",").map((x) => x.trim()).filter(Boolean) : [];
1457
+ function findRoot() {
1458
+ const given = flag("root") ?? process.env.CHIKEN_ROOT;
1459
+ if (given) return path13.resolve(given);
1460
+ let dir = process.cwd();
1461
+ while (true) {
1462
+ if (fs13.existsSync(path13.join(dir, LAYOUT.config))) return dir;
1463
+ if (fs13.existsSync(path13.join(dir, "chiken", LAYOUT.config))) return path13.join(dir, "chiken");
1464
+ const up = path13.dirname(dir);
1465
+ if (up === dir) throw new Error("chiken \u306E\u30C7\u30FC\u30BF\u30D5\u30A9\u30EB\u30C0\u304C\u898B\u3064\u304B\u3089\u306A\u3044\u3002--root \u304B CHIKEN_ROOT \u3067\u6E21\u3059");
1466
+ dir = up;
1467
+ }
1468
+ }
1469
+ var out = (human, data) => console.log(json ? JSON.stringify(data, null, 2) : human);
1470
+ var fail2 = (msg) => {
1471
+ throw new Error(msg);
1472
+ };
1473
+ function printCheck(c) {
1474
+ const own = c.findings.filter((x) => x.level === "error").length;
1475
+ const errors = own + (c.schema ? 1 : 0);
1476
+ const schema = c.schema ? [own ? "\u30A8\u30E9\u30FC schema \u306E\u691C\u67FB\u3082\u6B62\u307E\u3063\u305F\uFF08\u8A73\u3057\u304F\u306F --json\uFF09" : `\u30A8\u30E9\u30FC ${c.schema}`] : [];
1477
+ out([...c.findings.map((x) => `${x.level === "error" ? "\u30A8\u30E9\u30FC" : "\u8B66\u544A "} ${x.msg}`), ...schema, `\u30A8\u30E9\u30FC ${errors}\u3001\u8B66\u544A ${c.findings.length - errors + (c.schema ? 1 : 0)}`].join("\n"), c);
1478
+ }
1479
+ function write(root, fn, human) {
1480
+ const r = transact(root, fn, { force: flags.has("force") });
1481
+ if (r.check && !r.check.ok) {
1482
+ printCheck(r.check);
1483
+ console.error(r.rolledBack ? "\u70B9\u691C\u3067\u6B62\u307E\u3063\u305F\u306E\u3067\u3001\u66F8\u304D\u63DB\u3048\u3092\u623B\u3057\u305F\uFF08\u6B8B\u3059\u306A\u3089 --force\uFF09" : `\u70B9\u691C\u3067\u6B62\u307E\u3063\u305F\u304C --force \u306A\u306E\u3067\u6B8B\u3057\u305F\u3002\u66F8\u304D\u63DB\u3048\u308B\u524D\u306E\u30D5\u30A1\u30A4\u30EB\u306F ${r.history} \u306B\u3042\u308B`);
1484
+ process.exitCode = 1;
1485
+ return;
1486
+ }
1487
+ out(human(r.result), r.result);
1488
+ }
1489
+ var HELP = `chiken [--root <\u30C7\u30FC\u30BF\u30D5\u30A9\u30EB\u30C0>] [--json] [--force] <\u547D\u4EE4> \u2026
1490
+
1491
+ \u30C7\u30FC\u30BF\u30D5\u30A9\u30EB\u30C0\u306F --root\u3001\u74B0\u5883\u5909\u6570 CHIKEN_ROOT\u3001\u4ECA\u3044\u308B\u30D5\u30A9\u30EB\u30C0\u304B\u3089\u4E0A\u306B chiken.yaml \u3092\u63A2\u3059\u3001\u306E\u9806\u306B\u6C7A\u3081\u308B\u3002
1492
+ \u66F8\u304D\u63DB\u3048\u308B\u547D\u4EE4\u306F\u3001\u66F8\u304D\u63DB\u3048\u308B\u524D\u306E\u30D5\u30A1\u30A4\u30EB\u3092 <\u30C7\u30FC\u30BF\u30D5\u30A9\u30EB\u30C0>/.chiken/history/ \u306B\u30D0\u30C3\u30AF\u30A2\u30C3\u30D7\u3057\u3001\u70B9\u691C\u3067\u30A8\u30E9\u30FC\u304C\u3042\u308C\u3070\u623B\u3059\uFF08--force \u3067\u6B8B\u3059\uFF09\u3002
1493
+
1494
+ \u59CB\u3081\u308B
1495
+ init [<\u30D5\u30A9\u30EB\u30C0>] [--title \u2026] \u65B0\u3057\u3044\u30C7\u30FC\u30BF\u30D5\u30A9\u30EB\u30C0\u306E\u96DB\u5F62\u3092\u4F5C\u308B
1496
+
1497
+ \u898B\u308B
1498
+ ls problems [--area <\u9818\u57DF>]
1499
+ ls actions [--problem <\u8AB2\u984C>] [--kind study|try|change]
1500
+ ls insights [--problem <\u8AB2\u984C>] [--source <\u30A4\u30F3\u30D7\u30C3\u30C8>]
1501
+ ls sources
1502
+ show <ID> 1 \u4EF6\u306E\u4E2D\u8EAB\u3068\u3001\u9006\u5411\u304D\u3092\u542B\u3080\u3064\u306A\u304C\u308A
1503
+ search <\u8A9E> \u540D\u524D\u3068\u6587\u7AE0\u304B\u3089\u63A2\u3059
1504
+ check \u70B9\u691C
1505
+
1506
+ \u8DB3\u3059\u30FB\u76F4\u3059\uFF08--origin \u3092\u7701\u304F\u3068 AI \u306E\u63D0\u6848\uFF08ai\uFF09\u306B\u306A\u308B\u3002\u81EA\u5206\u3067\u51FA\u3057\u305F\u3082\u306E\u306F --origin self\uFF09
1507
+ new problem --name \u2026 --area <\u9818\u57DF> --now \u2026\uFF08\u30AB\u30F3\u30DE\u533A\u5207\u308A\u3067\u8907\u6570\uFF09 [--why \u2026]
1508
+ new action --name \u2026 --problem <\u8AB2\u984C> --kind study|try|change [--basis <\u77E5\u898B>,\u2026] [--also <\u8AB2\u984C>,\u2026]
1509
+ [--check \u2026] [--done \u2026] [--why \u2026] \u672C\u6587\u306E\u300C\u78BA\u304B\u3081\u308B\u3053\u3068\u300D\u300C\u7D42\u308F\u308A\u306E\u6761\u4EF6\u300D\u300C\u52B9\u304D\u305D\u3046\u306A\u7406\u7531\u300D
1510
+ source add <\u5A92\u4F53> --id <\u77ED\u3044\u540D\u524D> --title \u2026 --taken live|watched|read|skimmed
1511
+ [--collection <\u307E\u3068\u307E\u308A>] [--day <\u4F55\u65E5\u76EE> --time HH:MM] [--date \u2026] [--url \u2026] [--org \u2026] [--who \u2026]
1512
+ [--type <\u30E1\u30E2\u306E\u7A2E\u5225\u30FB\u30A4\u30D9\u30F3\u30C8\u306E\u7A2E\u5225>] [--file <\u30D5\u30A1\u30A4\u30EB\u540D>]
1513
+ \uFF08\u5A92\u4F53\u304C note \u306A\u3089 --taken \u306F\u8981\u3089\u306A\u3044\u3002\u30A4\u30D9\u30F3\u30C8\u306E\u767B\u58C7\u306F --day \u3092\u4ED8\u3051\u308B\u3068\u30BB\u30C3\u30B7\u30E7\u30F3\u306B\u306A\u308B\uFF09
1514
+ insight add <\u30A4\u30F3\u30D7\u30C3\u30C8> --text \u2026 --kind fact|impression --author self|external|ai [--problems P01,P02] [--verify \u2026]
1515
+ insight set <\u30A4\u30F3\u30D7\u30C3\u30C8>#<n> kind|author|text|who|verify|groups <\u5024>
1516
+ link <\u5F8C\u306E ID> <\u524D\u306E ID> --kind \u2026 --reason \u2026 \u8AB2\u984C\u3069\u3046\u3057\u306F pre|ease|same\u3001\u30A2\u30AF\u30B7\u30E7\u30F3\u3069\u3046\u3057\u306F pre|alt
1517
+ unlink <\u5F8C\u306E ID> <\u524D\u306E ID>
1518
+ tag <\u30A4\u30F3\u30D7\u30C3\u30C8>#<n> <\u8AB2\u984C\u2026> / untag <\u30A4\u30F3\u30D7\u30C3\u30C8>#<n> <\u8AB2\u984C\u2026> \u77E5\u898B\u3092\u624B\u304C\u304B\u308A\u306B\u306A\u308B\u8AB2\u984C\u306B\u7D50\u3076\u30FB\u5916\u3059
1519
+ set <ID> <\u9805\u76EE> <\u5024> \u9805\u76EE: kind\u30FBarea\u30FBorigin\u30FBproblem\u30FBalso\u30FBbasis\u30FBgroups\u30FBsession
1520
+ \uFF08also\u30FBbasis\u30FBgroups \u306F\u30AB\u30F3\u30DE\u533A\u5207\u308A\u3002\u5024\u3092\u7A7A\u306B\u3059\u308B\u3068\u5916\u3059\uFF09
1521
+ rename <ID> <\u65B0\u3057\u3044\u540D\u524D> origin: self \u306E\u540D\u524D\u306F --force \u304C\u8981\u308B
1522
+ merge <\u6B8B\u3059\u77E5\u898B> <\u6D88\u3059\u77E5\u898B> \u540C\u3058\u30A4\u30F3\u30D7\u30C3\u30C8\u306E\u4E2D\u3060\u3051
1523
+ rm <ID> \u8AB2\u984C\u30FB\u30A2\u30AF\u30B7\u30E7\u30F3\u30FB\u77E5\u898B\u3092\u6D88\u3057\u3001\u6307\u3057\u3066\u3044\u308B\u3068\u3053\u308D\u3082\u5916\u3059
1524
+
1525
+ \u66F8\u304D\u51FA\u3059
1526
+ build [<\u66F8\u304D\u51FA\u3057\u306E\u540D\u524D>] chiken.yaml \u306E exports \u306E HTML
1527
+ release [<\u66F8\u304D\u51FA\u3057\u306E\u540D\u524D>] release \u3092\u6301\u3064\u66F8\u304D\u51FA\u3057\u306E zip
1528
+ serve [--edit] [--port 5178] [--export <\u66F8\u304D\u51FA\u3057\u306E\u540D\u524D>]
1529
+ \u753B\u9762\u3092\u624B\u5143\u3067\u958B\u304F\uFF08--edit \u3067\u7DE8\u96C6\u30E2\u30FC\u30C9\uFF09
1530
+
1531
+ --json \u306F\u3001\u4E00\u89A7\u30FB\u4E2D\u8EAB\u30FB\u70B9\u691C\u30FB\u66F8\u304D\u63DB\u3048\u306E\u7D50\u679C\u3092 JSON \u3067\u51FA\u3059\u3002\u8A73\u3057\u304F\u306F docs/data-layout.md \u306E\u300CCLI\u300D\u3002`;
1532
+ function main() {
1533
+ const [cmd, ...rest] = pos;
1534
+ const unknown = [...flags.keys()].filter((k) => !KNOWN.has(k));
1535
+ if (unknown.length) fail2(`\u77E5\u3089\u306A\u3044\u30AA\u30D7\u30B7\u30E7\u30F3: ${unknown.map((k) => `--${k}`).join(" ")}\uFF08chiken help\uFF09`);
1536
+ if (!cmd || cmd === "help" || flags.has("help")) return console.log(HELP);
1537
+ if (cmd === "init") {
1538
+ const dir = path13.resolve(rest[0] ?? ".");
1539
+ const made = initRoot(dir, flag("title"));
1540
+ return out(`\u4F5C\u3063\u305F: ${dir}
1541
+ ${made.map((f) => ` ${f}`).join("\n")}
1542
+ \u6B21\u306F areas.md \u306E\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u3068\u9818\u57DF\u3092\u76F4\u3057\u3001chiken check \u3092\u6D41\u3059`, { dir, files: made });
1543
+ }
1544
+ const root = findRoot();
1545
+ const v = () => readRoot(root);
1546
+ switch (cmd) {
1547
+ case "ls": {
1548
+ const what = rest[0];
1549
+ const m = v().map;
1550
+ if (what === "problems") {
1551
+ const xs = m.problems.filter((p) => !flag("area") || p.area === flag("area"));
1552
+ return out(["# ID \u9818\u57DF \u51FA\u3069\u3053\u308D\uFF08AI \u306F AI \u306E\u63D0\u6848\uFF09 \u540D\u524D", ...xs.map((p) => `${p.id} ${p.area.padEnd(8)} ${p.origin === "ai" ? "AI " : " "}${p.name}`)].join("\n"), xs.map(({ id, area, origin, name }) => ({ id, area, origin, name })));
1553
+ }
1554
+ if (what === "actions") {
1555
+ const xs = m.actions.filter((a) => (!flag("problem") || a.problem === flag("problem")) && (!flag("kind") || a.kind === flag("kind")));
1556
+ return out(["# ID \u4E3B\u306A\u8AB2\u984C \u7A2E\u985E \u8A73\u7D30\u306E\u6709\u7121 \u540D\u524D", ...xs.map((a) => `${a.id} ${a.problem} ${a.kind.padEnd(6)} ${a.doc ? "\u8A73\u7D30 " : " "}${a.name}`)].join("\n"), xs.map(({ id, problem, kind, origin, name, also, basis }) => ({ id, problem, kind, origin, name, also, basis, detailed: !!m.actions.find((x) => x.id === id)?.doc })));
1557
+ }
1558
+ if (what === "insights") {
1559
+ const xs = m.insights.filter((i) => (!flag("problem") || i.problems.includes(flag("problem"))) && (!flag("source") || i.source === flag("source")));
1560
+ return out(["# \u77E5\u898B [\u624B\u304C\u304B\u308A\u306B\u306A\u308B\u8AB2\u984C] \u6587", ...xs.map((i) => `${i.id} [${i.problems.join(",")}] ${i.text.slice(0, 60)}`)].join("\n"), xs);
1561
+ }
1562
+ if (what === "sources") {
1563
+ const vv = v();
1564
+ const xs = [...vv.sourceOf.entries()].map(([id, collection]) => ({ id, collection, medium: vv.map.insightSources.find((s) => s.id === id)?.medium ?? null, insights: vv.map.insights.filter((i) => i.source === id).length, file: path13.relative(root, vv.files.get(id)) }));
1565
+ return out(["# \u30A4\u30F3\u30D7\u30C3\u30C8 \u77E5\u898B\u306E\u6570 \u30D5\u30A1\u30A4\u30EB", ...xs.map((s) => `${s.id.padEnd(32)} ${String(s.insights).padStart(3)} ${s.file}`)].join("\n"), xs);
1566
+ }
1567
+ return fail2("ls <problems|actions|insights|sources>");
1568
+ }
1569
+ case "show": {
1570
+ const id = rest[0] ?? fail2("show <ID>");
1571
+ const vv = v();
1572
+ const m = vv.map;
1573
+ const p = m.problems.find((x) => x.id === id);
1574
+ if (p) {
1575
+ const data = { ...p, before: m.problemLinks.filter((l) => l.down === id), after: m.problemLinks.filter((l) => l.up === id), actions: m.actions.filter((a2) => a2.problem === id || a2.also?.includes(id)).map((a2) => a2.id), insights: m.insights.filter((i2) => i2.problems.includes(id)).map((i2) => i2.id), file: path13.relative(root, vv.files.get(id)) };
1576
+ return out(`${p.id} ${p.name}
1577
+ \u9818\u57DF ${p.area} \u51FA\u3069\u3053\u308D ${p.origin}
1578
+ \u524D\u306B\u3042\u308B\u8AB2\u984C ${data.before.map((l) => `${l.up}(${l.kind})`).join(" ") || "-"}
1579
+ \u5F8C\u306B\u7D9A\u304F\u8AB2\u984C ${data.after.map((l) => `${l.down}(${l.kind})`).join(" ") || "-"}
1580
+ \u30A2\u30AF\u30B7\u30E7\u30F3 ${data.actions.join(" ") || "-"}
1581
+ \u77E5\u898B ${data.insights.length} \u4EF6
1582
+ ${data.file}`, data);
1583
+ }
1584
+ const a = m.actions.find((x) => x.id === id);
1585
+ if (a) {
1586
+ const { doc: _d, ...rest2 } = a;
1587
+ const data = { ...rest2, needs: m.actionLinks.filter((l) => l.to === id), enables: m.actionLinks.filter((l) => l.from === id), detailed: !!a.doc, file: path13.relative(root, vv.files.get(id)) };
1588
+ return out(`${a.id} ${a.name}
1589
+ \u7A2E\u985E ${a.kind} \u4E3B\u306A\u8AB2\u984C ${a.problem} \u3042\u308F\u305B\u3066 ${a.also?.join(" ") || "-"}
1590
+ \u524D\u306B\u8981\u308B ${data.needs.map((l) => `${l.from}(${l.kind})`).join(" ") || "-"}
1591
+ \u5F8C\u306B\u7D9A\u304F ${data.enables.map((l) => `${l.to}(${l.kind})`).join(" ") || "-"}
1592
+ \u6839\u62E0 ${a.basis?.join(" ") || "-"}
1593
+ ${data.file}`, data);
1594
+ }
1595
+ const i = m.insights.find((x) => x.id === id);
1596
+ if (i) return out(`${i.id} ${i.kind}/${i.author} [${i.problems.join(",")}]
1597
+ ${i.text}${i.verify ? `
1598
+ \u78BA\u304B\u3081\u3089\u308C\u308B\u3053\u3068: ${i.verify}` : ""}
1599
+ \u6839\u62E0\u306B\u3057\u3066\u3044\u308B\u30A2\u30AF\u30B7\u30E7\u30F3 ${m.actions.filter((x) => x.basis?.includes(id)).map((x) => x.id).join(" ") || "-"}`, { ...i, usedBy: m.actions.filter((x) => x.basis?.includes(id)).map((x) => x.id) });
1600
+ if (vv.files.has(id)) {
1601
+ const ins = m.insights.filter((x) => x.source === id);
1602
+ return out(`${id} ${path13.relative(root, vv.files.get(id))}
1603
+ \u77E5\u898B ${ins.length} \u4EF6`, { id, file: path13.relative(root, vv.files.get(id)), insights: ins });
1604
+ }
1605
+ return fail2(`\u898B\u3064\u304B\u3089\u306A\u3044: ${id}${!id.includes("/") && [...vv.sourceOf.keys()].some((k) => k.endsWith(`/${id}`)) ? `\uFF08\u307E\u3068\u307E\u308A\u306E\u4E2D\u306E\u30A4\u30F3\u30D7\u30C3\u30C8\u306F ${[...vv.sourceOf.keys()].filter((k) => k.endsWith(`/${id}`)).join(", ")}\uFF09` : ""}`);
1606
+ }
1607
+ case "search": {
1608
+ const q = (rest.join(" ") || fail2("search <\u8A9E>")).toLowerCase();
1609
+ const m = v().map;
1610
+ const hit = (t) => !!t && t.toLowerCase().includes(q);
1611
+ const res = [
1612
+ ...m.problems.filter((p) => hit(p.name) || p.now.some(hit) || hit(p.why)).map((p) => ({ type: "problem", id: p.id, text: p.name })),
1613
+ ...m.actions.filter((a) => hit(a.name) || hit(a.check) || hit(a.why)).map((a) => ({ type: "action", id: a.id, text: a.name })),
1614
+ ...m.insights.filter((i) => hit(i.text)).map((i) => ({ type: "insight", id: i.id, text: i.text }))
1615
+ ];
1616
+ return out(res.map((r) => `${r.type.padEnd(8)} ${r.id.padEnd(24)} ${r.text.slice(0, 70)}`).join("\n") || "\u898B\u3064\u304B\u3089\u306A\u3044", res);
1617
+ }
1618
+ case "new": {
1619
+ const what = rest[0];
1620
+ const name = flag("name") ?? fail2("--name \u304C\u8981\u308B");
1621
+ const origin = flag("origin");
1622
+ if (what === "problem") return write(root, (tx, vv) => ops.newProblem(tx, vv, { name, area: flag("area") ?? fail2("--area \u304C\u8981\u308B"), now: list(flag("now") ?? fail2("--now\uFF08\u4ECA\u306E\u72B6\u614B\u3002\u30AB\u30F3\u30DE\u533A\u5207\u308A\u3067\u8907\u6570\uFF09\u304C\u8981\u308B")), why: flag("why"), origin }), (r) => `\u4F5C\u3063\u305F: ${r.id} ${r.file}`);
1623
+ if (what === "action") return write(root, (tx, vv) => ops.newAction(tx, vv, { name, problem: flag("problem") ?? fail2("--problem \u304C\u8981\u308B"), kind: flag("kind") ?? fail2("--kind\uFF08study|try|change\uFF09\u304C\u8981\u308B"), also: list(flag("also")), basis: list(flag("basis")), check: flag("check"), done: flag("done"), why: flag("why"), origin }), (r) => `\u4F5C\u3063\u305F: ${r.id} ${r.file}`);
1624
+ return fail2("new <problem|action>");
1625
+ }
1626
+ case "source": {
1627
+ if (rest[0] !== "add") return fail2("source add <\u5A92\u4F53> --id <\u77ED\u3044\u540D\u524D> --title \u2026 --taken live|watched|read|skimmed [--collection <\u307E\u3068\u307E\u308A>] [--day <\u4F55\u65E5\u76EE> --time HH:MM] [--date YYYY-MM-DD] [--type \u2026] [--url \u2026] [--org \u2026] [--who \u2026] [--file \u2026]\uFF08chiken help\uFF09");
1628
+ const medium = rest[1] ?? fail2("\u5A92\u4F53\u304C\u8981\u308B\uFF08talk\u30FBarticle\u30FBvideo\u30FBpodcast\u30FBbook\u30FBpaper\u30FBdoc\u30FBnote\uFF09");
1629
+ return write(root, (tx, vv) => ops.addSource(tx, vv, { medium, title: flag("title") ?? fail2("--title \u304C\u8981\u308B"), id: flag("id") ?? fail2("--id\uFF08\u82F1\u5C0F\u6587\u5B57\u3068\u6570\u5B57\u3068\u30CF\u30A4\u30D5\u30F3\u306E\u77ED\u3044\u540D\u524D\uFF09\u304C\u8981\u308B"), collection: flag("collection"), type: flag("type"), taken: flag("taken"), date: flag("date"), day: flag("day"), time: flag("time"), file: flag("file"), url: flag("url"), org: flag("org"), who: flag("who") }), (r) => `\u4F5C\u3063\u305F: ${r.id} ${r.file}`);
1630
+ }
1631
+ case "insight": {
1632
+ if (rest[0] === "set") {
1633
+ const [, ref, field, ...val] = rest;
1634
+ if (!ref || !field) return fail2("insight set <\u30A4\u30F3\u30D7\u30C3\u30C8\u306E ID>#<n> <\u9805\u76EE> <\u5024>");
1635
+ return write(root, (tx, vv) => ops.setInsight(tx, vv, ref, field, val.join(" ") || void 0), (r) => `${r.id}.${r.field} = ${r.value ?? "\uFF08\u5916\u3057\u305F\uFF09"}`);
1636
+ }
1637
+ if (rest[0] !== "add") return fail2("insight add <\u30A4\u30F3\u30D7\u30C3\u30C8\u306E ID> --text \u2026 --kind fact|impression --author self|external|ai [--problems P01,P02] [--who \u2026] [--verify \u2026]\ninsight set <\u30A4\u30F3\u30D7\u30C3\u30C8\u306E ID>#<n> <\u9805\u76EE> <\u5024>");
1638
+ const sid = rest[1] ?? fail2("\u30A4\u30F3\u30D7\u30C3\u30C8\u306E ID \u304C\u8981\u308B");
1639
+ return write(root, (tx, vv) => ops.addInsight(tx, vv, sid, { text: flag("text") ?? fail2("--text \u304C\u8981\u308B"), kind: flag("kind") ?? fail2("--kind \u304C\u8981\u308B"), author: flag("author") ?? fail2("--author \u304C\u8981\u308B"), who: flag("who"), problems: list(flag("problems")), verify: flag("verify") }), (r) => `\u8DB3\u3057\u305F: ${r.id}`);
1640
+ }
1641
+ case "link":
1642
+ case "unlink": {
1643
+ const [later, earlier] = rest;
1644
+ if (!later || !earlier) return fail2(`${cmd} <\u5F8C\u306E ID> <\u524D\u306E ID> [--kind \u2026] [--reason \u2026]`);
1645
+ return write(root, (tx, vv) => ops.link(tx, vv, later, earlier, cmd === "link" ? { kind: flag("kind"), reason: flag("reason") ?? fail2("--reason \u304C\u8981\u308B") } : null), () => `${cmd === "link" ? "\u3064\u306A\u3044\u3060" : "\u5916\u3057\u305F"}: ${earlier} \u2192 ${later}`);
1646
+ }
1647
+ case "tag":
1648
+ case "untag": {
1649
+ const [ref, ...probs] = rest;
1650
+ if (!ref || !probs.length) return fail2(`${cmd} <\u30A4\u30F3\u30D7\u30C3\u30C8\u306E ID>#<n> <\u8AB2\u984C\u2026>`);
1651
+ return write(root, (tx, vv) => ops.tag(tx, vv, ref, cmd === "tag" ? probs : [], cmd === "untag" ? probs : []), (r) => `${r.id}: [${r.problems.join(",")}]`);
1652
+ }
1653
+ case "set": {
1654
+ const [id, field, ...val] = rest;
1655
+ if (!id || !field) return fail2("set <ID> <\u9805\u76EE> <\u5024>\uFF08also\u30FBbasis\u30FBgroups \u306F\u30AB\u30F3\u30DE\u533A\u5207\u308A\uFF09");
1656
+ const value = val.join(" ");
1657
+ return write(root, (tx, vv) => ops.set(tx, vv, id, field, ["also", "basis", "groups"].includes(field) ? list(value) : value), () => `${id}.${field} = ${value}`);
1658
+ }
1659
+ case "rename": {
1660
+ const [id, ...words] = rest;
1661
+ if (!id || !words.length) return fail2("rename <ID> <\u65B0\u3057\u3044\u540D\u524D>\uFF08origin: self \u306F --force \u304C\u8981\u308B\uFF09");
1662
+ return write(root, (tx, vv) => ops.rename(tx, vv, id, words.join(" "), flags.has("force")), (r) => `${r.id} \u2192 ${r.file}${r.relinked.length ? `\uFF08\u30EA\u30F3\u30AF\u3092\u5F35\u308A\u66FF\u3048\u305F: ${r.relinked.join("\u3001")}\uFF09` : ""}`);
1663
+ }
1664
+ case "merge": {
1665
+ const [keep, drop] = rest;
1666
+ if (!keep || !drop) return fail2("merge <\u6B8B\u3059\u77E5\u898B> <\u6D88\u3059\u77E5\u898B>\uFF08\u540C\u3058\u30A4\u30F3\u30D7\u30C3\u30C8\u306E\u4E2D\u3060\u3051\uFF09");
1667
+ return write(root, (tx, vv) => ops.merge(tx, vv, keep, drop), (r) => `\u307E\u3068\u3081\u305F: ${r.drop} \u2192 ${r.keep} [${r.problems.join(",")}]`);
1668
+ }
1669
+ case "rm": {
1670
+ const id = rest[0] ?? fail2("rm <ID>\uFF08\u8AB2\u984C\u30FB\u30A2\u30AF\u30B7\u30E7\u30F3\u30FB\u77E5\u898B\uFF09");
1671
+ return write(root, (tx, vv) => ops.rm(tx, vv, id), (r) => `\u6D88\u3057\u305F: ${r.id}${r.touched.length ? `\uFF08\u6307\u3057\u3066\u3044\u305F\u3068\u3053\u308D\u3092\u5916\u3057\u305F: ${r.touched.join(" ")}\uFF09` : ""}`);
1672
+ }
1673
+ case "check": {
1674
+ const c = runCheck(root);
1675
+ printCheck(c);
1676
+ process.exitCode = c.ok ? 0 : 1;
1677
+ return;
1678
+ }
1679
+ case "serve":
1680
+ void serve(root, { port: Number(flag("port") ?? 5178), edit: flags.has("edit"), exportName: flag("export") });
1681
+ return;
1682
+ case "build":
1683
+ buildExports(root, rest[0]).catch((e) => {
1684
+ console.error(e.message);
1685
+ process.exitCode = 1;
1686
+ });
1687
+ return;
1688
+ case "release":
1689
+ releaseZip(root, rest[0]);
1690
+ return;
1691
+ default:
1692
+ console.log(HELP);
1693
+ process.exitCode = 1;
1694
+ }
1695
+ }
1696
+ try {
1697
+ main();
1698
+ } catch (e) {
1699
+ console.error(e.message);
1700
+ process.exitCode = 1;
1701
+ }