akari-video 1.5.0-beta.4 → 1.5.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/package.json +1 -1
  2. package/src/cli.mjs +6 -0
  3. package/src/kits.mjs +35 -0
  4. package/src/messages.mjs +1 -1
  5. package/src/playbook-command.mjs +90 -0
  6. package/src/project-command.mjs +372 -0
  7. package/src/project-manifest.mjs +92 -0
  8. package/src/recipe-command.mjs +128 -0
  9. package/src/status-command.mjs +11 -2
  10. package/src/status-core/events.mjs +34 -0
  11. package/src/status-core/review.mjs +3 -1
  12. package/src/status-core/status.mjs +3 -1
  13. package/src/store-command.mjs +4 -0
  14. package/vendor/.akari-capability-sources.json +3 -0
  15. package/vendor/docs/contract-2026-07-20-review-json-v1-annotation-model.md +4 -2
  16. package/vendor/docs/contract-2026-08-23-stroke-persistence.md +2 -0
  17. package/vendor/docs/contract-2026-10-15-playbook-v0.md +1 -1
  18. package/vendor/docs/contract-2026-10-16-recipes-and-connectors-v0.md +14 -7
  19. package/vendor/docs/contract-2026-10-16-showcase-v0.md +150 -0
  20. package/vendor/docs/contract-2026-10-16-template-v0.md +129 -0
  21. package/vendor/docs/contract-2026-10-16-vocabulary-v0.md +175 -0
  22. package/vendor/packages/akari-launcher/package.json +1 -1
  23. package/vendor/packages/edit-lint/src/lint/review.mjs +1 -1
  24. package/vendor/packages/i18n/locales/en/annotations.json +3 -3
  25. package/vendor/packages/i18n/locales/en/annotationscommon.json +1 -0
  26. package/vendor/packages/i18n/locales/en/cli.json +45 -1
  27. package/vendor/packages/i18n/locales/en/preview.json +15 -6
  28. package/vendor/packages/i18n/locales/en/project.json +58 -1
  29. package/vendor/packages/i18n/locales/en/surfaces.json +47 -1
  30. package/vendor/packages/i18n/locales/ja/annotations.json +3 -3
  31. package/vendor/packages/i18n/locales/ja/annotationscommon.json +1 -0
  32. package/vendor/packages/i18n/locales/ja/cli.json +45 -1
  33. package/vendor/packages/i18n/locales/ja/preview.json +13 -4
  34. package/vendor/packages/i18n/locales/ja/project.json +58 -1
  35. package/vendor/packages/i18n/locales/ja/surfaces.json +47 -1
  36. package/vendor/packages/project-scaffold/src/index.mjs +515 -3
  37. package/vendor/packages/schemas/akari-recipe.schema.json +19 -0
  38. package/vendor/packages/schemas/bin/validate-kit-manifest.mjs +38 -1
  39. package/vendor/packages/schemas/bin/validate-project-manifest.mjs +67 -0
  40. package/vendor/packages/schemas/bin/validate-review.mjs +3 -3
  41. package/vendor/packages/schemas/capabilities.json +9 -0
  42. package/vendor/packages/schemas/connections.schema.json +15 -0
  43. package/vendor/packages/schemas/fixtures/review/invalid-strokes-content-rect-empty-sessionref/review.json +6 -0
  44. package/vendor/packages/schemas/fixtures/review/valid-strokes-direct/review.json +6 -0
  45. package/vendor/packages/schemas/kit-manifest.schema.json +11 -0
  46. package/vendor/packages/schemas/playbook.schema.json +27 -2
  47. package/vendor/packages/schemas/project-manifest.schema.json +294 -0
  48. package/vendor/packages/schemas/review.schema.json +2 -2
  49. package/vendor/packages/schemas/test/akari-recipe.test.mjs +52 -0
  50. package/vendor/packages/schemas/test/fixtures/akari-recipes/music.json +11 -0
  51. package/vendor/packages/schemas/test/fixtures/akari-recipes/three-d.json +11 -0
  52. package/vendor/packages/schemas/test/fixtures/project-manifest/cycle/manifest.json +1 -0
  53. package/vendor/packages/schemas/test/fixtures/project-manifest/dotdot/manifest.json +1 -0
  54. package/vendor/packages/schemas/test/fixtures/project-manifest/missing/manifest.json +1 -0
  55. package/vendor/packages/schemas/test/fixtures/project-manifest/valid/manifest.json +1 -0
  56. package/vendor/packages/schemas/test/kit-manifest.test.mjs +28 -1
  57. package/vendor/packages/schemas/test/kit-recipes.test.mjs +35 -0
  58. package/vendor/packages/schemas/test/project-manifest.test.mjs +44 -0
  59. package/vendor/packages/schemas/test/validate-playbook-without-ajv.test.mjs +54 -0
  60. package/vendor/packages/schemas/test/validate-review.test.mjs +66 -0
  61. package/vendor/packages/schemas/test/validate-template.test.mjs +55 -0
  62. package/vendor/packages/schemas/validate-akari-recipe.mjs +60 -0
  63. package/vendor/packages/schemas/validate-playbook.mjs +201 -8
  64. package/vendor/skills/akari/SKILL.md +22 -0
  65. package/vendor/skills/analyze-project/SKILL.md +12 -0
  66. package/vendor/skills/edit-plan/autonomy.md +17 -6
  67. package/vendor/templates/project-default/.akari/workflow.json +1 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akari-video",
3
- "version": "1.5.0-beta.4",
3
+ "version": "1.5.0-beta.6",
4
4
  "description": "AKARI Video launcher CLI — start an AI-edited video project from any directory: scaffold, connection check, then hand over to Claude Code (or opencode). AKARI Video を opencode や Claude Code で、どのディレクトリからでも始めるための `akari` ランチャー CLI。接続確認(doctor)→ 未セットアップならプロジェクト雛形を作成 → AI エージェントを起動する。外部 npm 依存ゼロ(Node.js 組み込みモジュールのみ)。",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.mjs CHANGED
@@ -30,6 +30,9 @@ import { runSpeakersCommand } from './speakers-command.mjs';
30
30
  import { runToolsCommand } from './tools-command.mjs';
31
31
  import { runWordBookCommand } from './word-book-command.mjs';
32
32
  import { runConnectCommand } from './connect-command.mjs';
33
+ import { runProjectCommand } from './project-command.mjs';
34
+ import { runPlaybookCommand } from './playbook-command.mjs';
35
+ import { runRecipeCommand } from './recipe-command.mjs';
33
36
  import { resolveRuntimePaths } from './runtime-diagnostics.mjs';
34
37
  import { cliText } from './i18n.mjs';
35
38
 
@@ -43,6 +46,9 @@ export const runSubcommands = {
43
46
  tools: runToolsCommand,
44
47
  'word-book': runWordBookCommand,
45
48
  connect: runConnectCommand,
49
+ project: runProjectCommand,
50
+ playbook: runPlaybookCommand,
51
+ recipe: runRecipeCommand,
46
52
  };
47
53
 
48
54
  /**
package/src/kits.mjs CHANGED
@@ -293,6 +293,37 @@ export function linkKitPlaybooks(kitDir, manifest, home, options = {}) {
293
293
  return { linked, warnings };
294
294
  }
295
295
 
296
+ export function linkKitRecipes(kitDir, manifest, home, options = {}) {
297
+ const linked = [];
298
+ const warnings = [];
299
+ for (const entry of manifest.recipes ?? []) {
300
+ if (typeof entry?.dir !== 'string' || !/^recipes\/[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(entry.dir)) {
301
+ throw new Error(cliText('cli.kits.error.pathOutside', { path: String(entry?.dir) }));
302
+ }
303
+ const id = path.posix.basename(entry.dir);
304
+ const source = safeKitPath(kitDir, entry.dir);
305
+ const realKit = realpathSync(kitDir);
306
+ const realSource = realpathSync(source);
307
+ if (!realSource.startsWith(`${realKit}${path.sep}`) || !statSync(realSource).isDirectory()) {
308
+ throw new Error(cliText('cli.kits.error.pathOutside', { path: entry.dir }));
309
+ }
310
+ const destination = path.join(home, 'tool-recipes', id);
311
+ try {
312
+ const stat = lstatSync(destination);
313
+ let owned = false;
314
+ if (stat.isSymbolicLink()) {
315
+ try { owned = realpathSync(destination) === realSource; } catch { /* Broken links are not owned. */ }
316
+ }
317
+ if (!owned) { warnings.push(cliText('cli.kits.warning.directoryKept', { path: destination })); continue; }
318
+ } catch (error) { if (error?.code !== 'ENOENT') throw error; }
319
+ const result = replaceSymlink(source, destination, options);
320
+ if (result.status === 'linked') linked.push(id);
321
+ else warnings.push(cliText(result.status === 'permission-denied'
322
+ ? 'cli.kits.warning.symlinkFailed' : 'cli.kits.warning.directoryKept', { path: destination }));
323
+ }
324
+ return { linked, warnings };
325
+ }
326
+
296
327
  export function readKitsLedger(home) {
297
328
  const ledgerPath = path.join(home, 'kits', 'installed.json');
298
329
  if (!existsSync(ledgerPath)) return { schema: KITS_SCHEMA, kits: [] };
@@ -311,6 +342,9 @@ export function writeKitsLedger(home, entry) {
311
342
  removeOwnedSymlink(path.join(home, 'playbooks', id), previous.kitDir);
312
343
  }
313
344
  }
345
+ for (const id of previous?.recipes ?? []) {
346
+ if (!(entry.recipes ?? []).includes(id)) removeOwnedSymlink(path.join(home, 'tool-recipes', id), previous.kitDir);
347
+ }
314
348
  ledger.kits = [...ledger.kits.filter((kit) => kit.id !== entry.id), entry];
315
349
  const ledgerPath = path.join(home, 'kits', 'installed.json');
316
350
  mkdirSync(path.dirname(ledgerPath), { recursive: true });
@@ -326,6 +360,7 @@ export function removeKit(home, productId, env = process.env) {
326
360
  if (!entry) return false;
327
361
  for (const name of entry.skills ?? []) removeOwnedSymlink(path.join(home, 'kits', 'plugin', 'skills', name), entry.kitDir);
328
362
  for (const id of entry.playbooks ?? []) removeOwnedSymlink(path.join(home, 'playbooks', id), entry.kitDir);
363
+ for (const id of entry.recipes ?? []) removeOwnedSymlink(path.join(home, 'tool-recipes', id), entry.kitDir);
329
364
  for (const asset of entry.assets ?? []) {
330
365
  for (const root of resolveAssetLibraryRoots({ ...env, AKARI_HOME: home }).read) removeOwnedSymlink(path.join(root, asset.category, asset.id), entry.kitDir);
331
366
  }
package/src/messages.mjs CHANGED
@@ -335,7 +335,7 @@ export function describeCliHelp() {
335
335
  cliText('cli.help.header.usage'),
336
336
  '',
337
337
  cliText('cli.help.commands.heading'),
338
- ...['launch', 'store', 'sounds', 'doctor', 'speakers', 'toolsVoice', 'update', 'status', 'migrate', 'migrateLook', 'generate', 'storyboard', 'clean'].map((name) => cliText(`cli.help.commands.${name}`)),
338
+ ...['launch', 'store', 'sounds', 'doctor', 'speakers', 'toolsVoice', 'update', 'status', 'migrate', 'migrateLook', 'generate', 'storyboard', 'project', 'playbook', 'recipe', 'clean'].map((name) => cliText(`cli.help.commands.${name}`)),
339
339
  '',
340
340
  cliText('cli.help.developer.heading'),
341
341
  ...['opencode', 'claude', 'yes', 'version', 'new', 'init', 'other', 'help'].map((name) => cliText(`cli.help.developer.${name}`)),
@@ -0,0 +1,90 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ import { cliText } from './i18n.mjs';
6
+ import { resolveLauncherAssets } from './repo-assets.mjs';
7
+
8
+ const usage = () => `${cliText('cli.playbook.help.usage')}\n${cliText('cli.playbook.template.usage')}`;
9
+ const safeChannel = value => typeof value === 'string' && value.trim() && value.length <= 64
10
+ && value !== '.' && !value.includes('..') && !/[/\\<>:"|?*\x00-\x1f]/.test(value);
11
+
12
+ function parse(args) {
13
+ const action = args[0];
14
+ if (action === '--help' || action === '-h' || args.includes('--help') || args.includes('-h')) return { action: 'help' };
15
+ if (!['list', 'apply', 'template'].includes(action)) throw new Error(usage());
16
+ const result = { action, id: action === 'apply' ? args[1] : null, project: action === 'template' ? args[1] : null };
17
+ if (action === 'apply' && (!result.id || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(result.id))) throw new Error(usage());
18
+ if (action === 'template' && !result.project) throw new Error(usage());
19
+ for (let i = action === 'apply' || action === 'template' ? 2 : 1; i < args.length; i++) {
20
+ const arg = args[i];
21
+ if ((action === 'list' && arg === '--json') || (action === 'apply' && arg === '--dry-run')) {
22
+ result[arg.slice(2).replace('-', '')] = true;
23
+ } else if ((action === 'list' && ['--category', '--tag', '--channel'].includes(arg))
24
+ || (action === 'apply' && arg === '--into')
25
+ || (action === 'template' && ['--item', '--id', '--name', '--out', '--license-own'].includes(arg))) {
26
+ if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(usage());
27
+ result[arg.slice(2)] = args[++i];
28
+ } else throw new Error(usage());
29
+ }
30
+ if (action === 'apply' && !result.into) throw new Error(usage());
31
+ if (action === 'template' && (!result.item || !result.id || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(result.id))) throw new Error(usage());
32
+ if (result.channel && !safeChannel(result.channel)) throw new Error(usage());
33
+ return result;
34
+ }
35
+
36
+ export async function runPlaybookCommand(args, options = {}) {
37
+ const log = options.log ?? console.log;
38
+ const error = options.error ?? console.error;
39
+ let parsed;
40
+ try { parsed = parse(args); }
41
+ catch (cause) { error(cause.message); return { exitCode: 1 }; }
42
+ if (parsed.action === 'help') { log(usage()); return { exitCode: 0 }; }
43
+ try {
44
+ const env = options.env ?? process.env;
45
+ const cwd = options.cwd ?? process.cwd();
46
+ const assets = options.assets ?? resolveLauncherAssets();
47
+ const akariHome = env.AKARI_HOME || path.join(options.home ?? os.homedir(), '.akari');
48
+ if (!assets.scaffoldModulePath) throw new Error(cliText('cli.playbook.error.scaffoldMissing'));
49
+ const scaffold = await import(pathToFileURL(assets.scaffoldModulePath).href);
50
+ if (parsed.action === 'template') {
51
+ const result = await scaffold.exportPlaybookTemplate({ projectDir: path.resolve(cwd, parsed.project),
52
+ itemId: parsed.item, id: parsed.id, name: parsed.name, out: parsed.out ?? path.join(akariHome, 'playbooks'),
53
+ licenseOwn: parsed['license-own'] });
54
+ log(result.dir);
55
+ return { exitCode: 0, ...result };
56
+ }
57
+ const projectDir = parsed.into ? path.resolve(cwd, parsed.into) : null;
58
+ let root = null;
59
+ if (assets.creatorRootModulePath) {
60
+ const creator = await import(pathToFileURL(assets.creatorRootModulePath).href);
61
+ root = await creator.resolveCreatorRoot({ cwd: projectDir ?? cwd, env });
62
+ if (root?.error) throw root.error;
63
+ }
64
+ let channel = parsed.channel;
65
+ if (!channel && projectDir && root) {
66
+ const segments = path.relative(root.rootDir, projectDir).split(path.sep);
67
+ channel = segments[0] === 'channels' && root.manifest?.channels?.includes(segments[1])
68
+ ? segments[1] : root.manifest?.channels?.[0];
69
+ }
70
+ const channelDir = root && channel
71
+ ? path.join(root.rootDir, 'channels', channel, 'playbooks') : undefined;
72
+ const entries = await scaffold.listPlaybooks({ akariHome, channelDir,
73
+ category: parsed.category, tag: parsed.tag,
74
+ onWarning: (dir, cause) => error(cliText('cli.playbook.warning.broken', { dir, message: cause.message })) });
75
+ if (parsed.action === 'list') {
76
+ if (parsed.json) log(JSON.stringify(entries));
77
+ else for (const entry of entries) log(cliText('cli.playbook.list.row', { id: entry.id, name: entry.name,
78
+ category: entry.category, source: entry.source,
79
+ duration: entry.targetDurationSec ?? cliText('cli.playbook.list.durationUnknown') }));
80
+ return { exitCode: 0, entries };
81
+ }
82
+ const entry = entries.find(item => item.id === parsed.id);
83
+ if (!entry) throw new Error(cliText('cli.playbook.error.notFound', { id: parsed.id }));
84
+ const result = await scaffold.applyPlaybookToExisting({ projectDir, playbookDir: entry.dir, dryRun: parsed.dryrun });
85
+ log(cliText(parsed.dryrun ? 'cli.playbook.apply.dryRun' : 'cli.playbook.apply.applied', {
86
+ name: entry.name, changes: result.changes.join('、') || cliText('cli.playbook.apply.noChanges'), report: result.reportPath
87
+ }));
88
+ return { exitCode: 0, ...result };
89
+ } catch (cause) { error(cause.message); return { exitCode: 1 }; }
90
+ }
@@ -0,0 +1,372 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ import { resolveLauncherAssets } from './repo-assets.mjs';
6
+ import { cliText } from './i18n.mjs';
7
+ import { manifestPath, readJson, readManifest, resolveWhere, sha256, writeJsonAtomic, writeManifest } from './project-manifest.mjs';
8
+
9
+ const idPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
10
+ const entries = value => Array.isArray(value) ? value : [];
11
+ const slug = value => idPattern.test(value) ? value : 'project';
12
+ const text = (key, params) => cliText(`cli.project.${key}`, params);
13
+ const missing = error => error?.code === 'ENOENT';
14
+
15
+ async function resolveAssetNode(root, node, env, localWhere) {
16
+ const suffix = node.id.startsWith('asset:') ? node.id.slice(6) : '';
17
+ const [category, id, ...extra] = suffix.split('/');
18
+ if (!category || !id || extra.length || [category, id].some(part => part === '.' || part === '..' || part.includes('\\'))) return null;
19
+ const where = localWhere ?? `assets/${category}/${id}`;
20
+ const local = await resolveWhere(root, where);
21
+ if (local.exists) return { path: local.path, source: 'own', where };
22
+ const { resolveAssetLibraryRoots } = await import('../../creator-root/src/index.mjs');
23
+ for (const library of resolveAssetLibraryRoots(env).read) {
24
+ if (!await isDirectory(library)) continue;
25
+ const found = await resolveWhere(library, `${category}/${id}`);
26
+ if (found.exists) {
27
+ const relative = path.relative(await fs.realpath(library), found.path);
28
+ const meta = await isDirectory(found.path) ? await readLedger(path.join(found.path, 'meta.json')) : {};
29
+ const inStore = relative === 'store' || relative.startsWith(`store${path.sep}`);
30
+ return { path: found.path, source: inStore || meta?.sourceKind === 'lab' ? 'lab' : 'builtin' };
31
+ }
32
+ }
33
+ return null;
34
+ }
35
+ async function assetRevision(target) {
36
+ const stat = await fs.stat(target);
37
+ const candidates = stat.isDirectory()
38
+ ? [path.join(target, '.meta.json'), path.join(target, 'meta.json')]
39
+ : [`${target}.meta.json`];
40
+ for (const file of candidates) {
41
+ const meta = await readJson(file);
42
+ const revision = meta?.version ?? meta?.revision ?? meta?.rev;
43
+ if (Number.isInteger(revision)) return revision;
44
+ }
45
+ return null;
46
+ }
47
+ async function assetRevisionIsNewer(target, node) {
48
+ const revision = await assetRevision(target);
49
+ return revision !== null && revision > node.rev;
50
+ }
51
+
52
+ async function isDirectory(file) {
53
+ try { return (await fs.stat(file)).isDirectory(); } catch (error) { if (missing(error)) return false; throw error; }
54
+ }
55
+ async function isFile(file) {
56
+ try { return (await fs.stat(file)).isFile(); } catch (error) { if (missing(error)) return false; throw error; }
57
+ }
58
+ async function projectRootFor(folder) {
59
+ const parent = path.dirname(folder);
60
+ const project = path.dirname(parent);
61
+ return path.basename(parent) === 'scenes' && await isDirectory(path.join(project, '.akari'))
62
+ ? project : folder;
63
+ }
64
+ async function readLedger(file) {
65
+ try { return await readJson(file, {}); }
66
+ catch (error) { if (error instanceof SyntaxError) return {}; throw error; }
67
+ }
68
+ function parse(args) {
69
+ const [action, ...rest] = args;
70
+ if (!['sync', 'check', 'scene'].includes(action)) throw new Error(text('command.help'));
71
+ if (action === 'scene' && rest.shift() !== 'add') throw new Error(text('command.help'));
72
+ let project;
73
+ let id;
74
+ let json = false;
75
+ for (let i = 0; i < rest.length; i++) {
76
+ const arg = rest[i];
77
+ if (arg === '--json' && action !== 'scene') json = true;
78
+ else if (arg === '--project' && action === 'scene' && rest[i + 1] && !rest[i + 1].startsWith('--')) project = rest[++i];
79
+ else if (!arg.startsWith('-') && action === 'scene' && id === undefined) id = arg;
80
+ else if (!arg.startsWith('-') && action !== 'scene' && project === undefined) project = arg;
81
+ else throw new Error(text('error.argument', { argument: arg }));
82
+ }
83
+ if (action === 'scene' && !idPattern.test(id ?? '')) throw new Error(text('error.id'));
84
+ return { action, project, id, json };
85
+ }
86
+
87
+ async function channelPeoplePath(root) {
88
+ let cursor = path.dirname(root);
89
+ while (cursor !== path.dirname(cursor)) {
90
+ if (path.basename(path.dirname(cursor)) === 'channels') {
91
+ const candidate = path.join(cursor, 'people.json');
92
+ if (await isFile(candidate)) {
93
+ const channel = await fs.realpath(cursor);
94
+ const actual = await fs.realpath(candidate);
95
+ if (actual.startsWith(`${channel}${path.sep}`)) return candidate;
96
+ }
97
+ break;
98
+ }
99
+ cursor = path.dirname(cursor);
100
+ }
101
+ return null;
102
+ }
103
+
104
+ async function gatherLedgers(root, sceneId, generated, edges, parentId, env) {
105
+ const folder = sceneId ? path.join(root, 'scenes', sceneId) : root;
106
+ const references = await readLedger(path.join(folder, '.akari', 'asset-references.json'));
107
+ for (const reference of entries(Array.isArray(references) ? references : references?.references)) {
108
+ if (typeof reference?.category !== 'string' || typeof reference?.id !== 'string') continue;
109
+ const id = `asset:${reference.category}/${reference.id}`;
110
+ const relative = `${sceneId ? `scenes/${sceneId}/` : ''}assets/${reference.category}/${reference.id}`;
111
+ const resolved = await resolveAssetNode(root, { id }, env, relative);
112
+ const localRevision = resolved?.where ? await assetRevision(resolved.path) : null;
113
+ const rev = localRevision ?? (Number.isInteger(reference.revision) ? reference.revision : 0);
114
+ const prior = generated.get(id);
115
+ const source = prior?.source === 'own' && !resolved?.where ? 'own' : resolved?.source ?? reference.sourceKind ?? prior?.source;
116
+ generated.set(id, { id, kind: 'asset', rev: Math.max(rev, prior?.rev ?? 0),
117
+ ...(source ? { source } : {}), ...(resolved?.where ? { where: relative } : prior?.where ? { where: prior.where } : {}),
118
+ category: reference.category, by: 'sync' });
119
+ edges.push({ from: parentId, uses: id, by: 'sync' });
120
+ }
121
+ const styles = await readLedger(path.join(folder, '.akari', 'style-usage.json'));
122
+ for (const entry of entries(Array.isArray(styles) ? styles : styles?.entries)) {
123
+ const uid = entry?.style_uid;
124
+ if (typeof uid !== 'string' || !uid) continue;
125
+ const id = `style:${entry.id || uid}`;
126
+ const rev = Number.isInteger(entry.revision) ? entry.revision : 0;
127
+ generated.set(id, { id, kind: 'style', rev: Math.max(rev, generated.get(id)?.rev ?? 0), uid, by: 'sync' });
128
+ edges.push({ from: parentId, uses: id, by: 'sync' });
129
+ }
130
+ }
131
+
132
+ async function gatherDocuments(root, generated, edges, parentId) {
133
+ const planning = path.join(root, 'planning');
134
+ if (!await isDirectory(planning)) return;
135
+ async function walk(folder) {
136
+ for (const item of await fs.readdir(folder, { withFileTypes: true })) {
137
+ const file = path.join(folder, item.name);
138
+ if (item.isDirectory()) await walk(file);
139
+ else if (item.isFile() && !item.name.startsWith('.')) {
140
+ const where = path.relative(root, file).split(path.sep).join('/');
141
+ const id = `doc:${where.slice('planning/'.length)}`;
142
+ const mtime = (await fs.stat(file)).mtime.toISOString();
143
+ generated.set(id, { id, kind: 'doc', rev: 0, where, mtime, by: 'sync' });
144
+ edges.push({ from: parentId, uses: id, by: 'sync' });
145
+ }
146
+ }
147
+ }
148
+ await walk(planning);
149
+ }
150
+
151
+ export async function syncProject(root, { env = process.env } = {}) {
152
+ const previous = await readManifest(root);
153
+ const old = new Map(previous.nodes.map(node => [node.id, node]));
154
+ const generated = new Map();
155
+ const edges = [];
156
+ const projectId = `project:${slug(path.basename(root))}`;
157
+ generated.set(projectId, { id: projectId, kind: 'project', rev: previous.project?.revision ?? 0, by: 'sync' });
158
+ const sceneRoot = path.join(root, 'scenes');
159
+ const sceneIds = await isDirectory(sceneRoot)
160
+ ? (await fs.readdir(sceneRoot, { withFileTypes: true })).filter(entry => entry.isDirectory() && idPattern.test(entry.name)).map(entry => entry.name).sort()
161
+ : [];
162
+ for (const id of sceneIds) {
163
+ const sceneId = `scene:${id}`;
164
+ const editPath = path.join(sceneRoot, id, 'edit.json');
165
+ const edited = await isFile(editPath) ? (await fs.stat(editPath)).mtime.toISOString() : undefined;
166
+ generated.set(sceneId, { id: sceneId, kind: 'scene', rev: 0, where: `scenes/${id}`, ...(edited ? { edited } : {}), by: 'sync' });
167
+ edges.push({ from: projectId, uses: sceneId, by: 'sync' });
168
+ await gatherLedgers(root, id, generated, edges, sceneId, env);
169
+ }
170
+ await gatherLedgers(root, null, generated, edges, projectId, env);
171
+ const peopleFile = await isFile(path.join(root, 'people.json')) ? path.join(root, 'people.json') : await channelPeoplePath(root);
172
+ if (peopleFile) {
173
+ const people = await readJson(peopleFile, {});
174
+ for (const person of entries(Array.isArray(people) ? people : people?.entries)) {
175
+ if (typeof person?.id !== 'string' || !person.id) continue;
176
+ const id = `person:${person.id}`;
177
+ generated.set(id, { id, kind: 'person', rev: 0, ...(peopleFile === path.join(root, 'people.json') ? { where: `people.json#${person.id}` } : { source: 'channel' }),
178
+ ...(person.edited ? { edited: person.edited } : {}), by: 'sync' });
179
+ edges.push({ from: projectId, uses: id, by: 'sync' });
180
+ }
181
+ }
182
+ await gatherDocuments(root, generated, edges, projectId);
183
+ for (const [id, node] of generated) {
184
+ const prior = old.get(id);
185
+ if (!prior || prior.by !== 'sync') { if (prior) generated.set(id, prior); continue; }
186
+ if (node.kind === 'person' || node.kind === 'scene') {
187
+ node.rev = prior.rev + (node.edited !== prior.edited ? 1 : 0);
188
+ } else if (node.kind === 'doc') {
189
+ node.rev = prior.rev + (node.mtime !== prior.mtime ? 1 : 0);
190
+ } else if (node.kind === 'asset' || node.kind === 'style') node.rev = Math.max(node.rev, prior.rev);
191
+ else node.rev = prior.rev;
192
+ if (node.kind === 'asset') {
193
+ const { source: _source, where: _where, ...rest } = prior;
194
+ generated.set(id, { ...rest, ...node });
195
+ } else generated.set(id, { ...prior, ...node });
196
+ }
197
+ for (const node of previous.nodes) {
198
+ if (node.by === 'sync') continue;
199
+ if (node.kind === 'tool-output' && typeof node.sha256 === 'string' && node.where) {
200
+ try {
201
+ const target = await resolveWhere(root, node.where);
202
+ if (target.exists) {
203
+ const actual = await sha256(target.path);
204
+ if (actual !== node.sha256) {
205
+ generated.set(node.id, { ...node, sha256: actual, rev: node.rev + 1 });
206
+ continue;
207
+ }
208
+ }
209
+ } catch { /* check reports a rejected or missing path */ }
210
+ }
211
+ generated.set(node.id, node);
212
+ }
213
+ const uniqueEdges = new Map();
214
+ for (const edge of [...previous.edges.filter(edge => edge.by !== 'sync'), ...edges]) {
215
+ const key = `${edge.from}\0${edge.uses}`;
216
+ if (!uniqueEdges.has(key)) uniqueEdges.set(key, edge);
217
+ }
218
+ const manifest = { ...previous, nodes: [...generated.values()], edges: [...uniqueEdges.values()] };
219
+ const changed = await writeManifest(root, manifest);
220
+ const counts = {};
221
+ for (const node of manifest.nodes) counts[node.kind] = (counts[node.kind] ?? 0) + 1;
222
+ return { changed, counts, nodes: manifest.nodes.length, edges: manifest.edges.length };
223
+ }
224
+
225
+ export async function checkProject(root, { env = process.env } = {}) {
226
+ if (!await isFile(manifestPath(root))) return { absent: true, exitCode: 0 };
227
+ const manifest = await readManifest(root);
228
+ const findings = [];
229
+ const add = (code, severity, message, extra = {}) => findings.push({ code, severity, ...extra, message });
230
+ const nodes = new Map(manifest.nodes.map(node => [node.id, node]));
231
+ for (const edge of manifest.edges) {
232
+ if (!nodes.has(edge.from) || !nodes.has(edge.uses)) add('MISSING_NODE', 'error', text('finding.missingNode', { from: edge.from, uses: edge.uses }), { edge });
233
+ if (edge.from === edge.uses) add('SELF_REFERENCE', 'error', text('finding.selfReference', { id: edge.from }), { edge });
234
+ }
235
+ const adjacency = new Map();
236
+ for (const edge of manifest.edges) {
237
+ if (!nodes.has(edge.from) || !nodes.has(edge.uses) || edge.from === edge.uses) continue;
238
+ if (!adjacency.has(edge.from)) adjacency.set(edge.from, []);
239
+ adjacency.get(edge.from).push(edge.uses);
240
+ }
241
+ const color = new Map();
242
+ const visit = id => {
243
+ color.set(id, 1);
244
+ for (const next of adjacency.get(id) ?? []) {
245
+ if (color.get(next) === 1) add('CYCLE', 'error', text('finding.cycle', { from: id, uses: next }), { edge: { from: id, uses: next } });
246
+ else if (!color.has(next)) visit(next);
247
+ }
248
+ color.set(id, 2);
249
+ };
250
+ for (const id of nodes.keys()) if (!color.has(id)) visit(id);
251
+ for (const node of manifest.nodes) {
252
+ if (node.kind === 'asset' && !node.where) {
253
+ try {
254
+ const target = await resolveAssetNode(root, node, env);
255
+ if (!target) {
256
+ const unacquired = node.source === 'lab';
257
+ add(unacquired ? 'UNACQUIRED' : 'MISSING_WHERE', unacquired ? 'warning' : 'error',
258
+ text(unacquired ? 'finding.unacquired' : 'finding.missingWhere', { id: node.id }), { node: node.id });
259
+ } else if (await assetRevisionIsNewer(target.path, node)) add('STALE', 'info', text('finding.stale', { id: node.id }), { node: node.id });
260
+ } catch { add('INVALID_WHERE', 'error', text('finding.invalidWhere', { id: node.id }), { node: node.id }); }
261
+ continue;
262
+ }
263
+ if (node.kind === 'person' && node.source === 'channel' && !node.where) {
264
+ const channelFile = await channelPeoplePath(root);
265
+ const people = channelFile ? await readJson(channelFile, {}) : {};
266
+ const person = entries(people?.entries).find(entry => entry.id === node.id.slice(7));
267
+ if (!person) add('MISSING_WHERE', 'error', text('finding.missingWhere', { id: node.id }), { node: node.id });
268
+ else if (node.edited && person.edited && Date.parse(person.edited) > Date.parse(node.edited)) add('STALE', 'info', text('finding.stale', { id: node.id }), { node: node.id });
269
+ continue;
270
+ }
271
+ if (!node.where) continue;
272
+ try {
273
+ const target = await resolveWhere(root, node.where);
274
+ if (!target.exists) {
275
+ const unacquired = node.kind === 'asset' && node.source === 'lab';
276
+ add(unacquired ? 'UNACQUIRED' : 'MISSING_WHERE', unacquired ? 'warning' : 'error', text(unacquired ? 'finding.unacquired' : 'finding.missingWhere', { id: node.id }), { node: node.id });
277
+ continue;
278
+ }
279
+ if (node.kind === 'person' && target.fragment) {
280
+ const people = await readJson(target.path, {});
281
+ const person = entries(people?.entries).find(entry => entry.id === target.fragment);
282
+ if (!person) add('MISSING_WHERE', 'error', text('finding.missingWhere', { id: node.id }), { node: node.id });
283
+ else if (node.edited && person.edited && Date.parse(person.edited) > Date.parse(node.edited)) add('STALE', 'info', text('finding.stale', { id: node.id }), { node: node.id });
284
+ }
285
+ if (node.kind === 'doc' || node.kind === 'scene') {
286
+ const file = node.kind === 'scene' ? path.join(target.path, 'edit.json') : target.path;
287
+ const recorded = node.kind === 'doc' ? (node.mtime ?? node.edited) : node.edited;
288
+ if (await isFile(file) && recorded && (await fs.stat(file)).mtimeMs > Date.parse(recorded) + 1) add('STALE', 'info', text('finding.stale', { id: node.id }), { node: node.id });
289
+ }
290
+ if (node.kind === 'asset' && await assetRevisionIsNewer(target.path, node)) add('STALE', 'info', text('finding.stale', { id: node.id }), { node: node.id });
291
+ if (node.kind === 'tool-output' && node.sha256 && await isFile(target.path) && await sha256(target.path) !== node.sha256) add('STALE', 'info', text('finding.stale', { id: node.id }), { node: node.id });
292
+ } catch {
293
+ add('INVALID_WHERE', 'error', text('finding.invalidWhere', { id: node.id }), { node: node.id });
294
+ }
295
+ }
296
+ const summary = { error: 0, warning: 0, info: 0 };
297
+ for (const finding of findings) summary[finding.severity]++;
298
+ const report = { version: 0, checkedAt: new Date().toISOString(), summary, findings };
299
+ await resolveWhere(root, '.akari/reports/manifest-check.json');
300
+ await writeJsonAtomic(path.join(root, '.akari', 'reports', 'manifest-check.json'), report);
301
+ return { ...report, exitCode: summary.error ? 1 : 0 };
302
+ }
303
+
304
+ export async function addScene(root, id, assets = resolveLauncherAssets()) {
305
+ if (!idPattern.test(id)) throw new Error(text('error.id'));
306
+ const scenes = path.join(root, 'scenes');
307
+ await fs.mkdir(scenes, { recursive: true });
308
+ await resolveWhere(root, 'scenes');
309
+ const target = path.join(scenes, id);
310
+ await fs.mkdir(target); // EEXIST is a hard failure, including a symlink.
311
+ try {
312
+ if (!assets.scaffoldModulePath || !assets.templateDir) throw new Error(text('error.template'));
313
+ const scaffold = await import(pathToFileURL(assets.scaffoldModulePath).href);
314
+ for (const name of ['assets', 'planning', '.akari']) {
315
+ const source = path.join(assets.templateDir, name);
316
+ if (await isDirectory(source)) await scaffold.copyTemplateTree(source, path.join(target, name));
317
+ else await fs.mkdir(path.join(target, name), { recursive: true });
318
+ }
319
+ let editStoreUrl;
320
+ for (const relative of ['../../edit-store/lib/index.js', '../vendor/packages/edit-store/lib/index.js']) {
321
+ const candidate = new URL(relative, import.meta.url);
322
+ if (await fs.stat(candidate).then(stat => stat.isFile(), () => false)) { editStoreUrl = candidate; break; }
323
+ }
324
+ if (!editStoreUrl) throw new Error('edit-store module not found');
325
+ const { default: editStore } = await import(editStoreUrl.href);
326
+ await writeJsonAtomic(path.join(target, 'edit.json'), editStore.createEmptyEditV2());
327
+ await writeJsonAtomic(path.join(target, 'captions.json'), []);
328
+ const manifest = await readManifest(root);
329
+ const nodeId = `scene:${id}`;
330
+ if (!manifest.nodes.some(node => node.id === nodeId)) {
331
+ const edited = (await fs.stat(path.join(target, 'edit.json'))).mtime.toISOString();
332
+ manifest.nodes.push({ id: nodeId, kind: 'scene', rev: 0, where: `scenes/${id}`, edited, by: 'sync' });
333
+ }
334
+ const projectId = `project:${slug(path.basename(root))}`;
335
+ if (!manifest.nodes.some(node => node.id === projectId)) manifest.nodes.push({ id: projectId, kind: 'project', rev: manifest.project?.revision ?? 0, by: 'sync' });
336
+ if (!manifest.edges.some(edge => edge.from === projectId && edge.uses === nodeId)) manifest.edges.push({ from: projectId, uses: nodeId, by: 'sync' });
337
+ await writeManifest(root, manifest);
338
+ return { id, path: target };
339
+ } catch (error) {
340
+ await fs.rm(target, { recursive: true, force: true });
341
+ throw error;
342
+ }
343
+ }
344
+
345
+ export async function runProjectCommand(args, options = {}) {
346
+ const log = options.log ?? console.log;
347
+ const logError = options.logError ?? console.error;
348
+ if (args.includes('--help') || args.includes('-h') || !args.length) { log(text('command.help')); return { exitCode: 0 }; }
349
+ try {
350
+ const parsed = parse(args);
351
+ const root = await projectRootFor(path.resolve(options.cwd ?? process.cwd(), parsed.project ?? '.'));
352
+ if (!await isDirectory(root) || (!await isDirectory(path.join(root, '.akari')) && !await isFile(path.join(root, 'edit.json')))) {
353
+ throw new Error(text('error.project', { path: root }));
354
+ }
355
+ if (parsed.action === 'sync') {
356
+ const result = await syncProject(root, { env: options.env ?? process.env });
357
+ log(parsed.json ? JSON.stringify(result) : text('result.sync', { counts: Object.entries(result.counts).map(([kind, count]) => `${kind}:${count}`).join(' '), edges: result.edges }));
358
+ return { exitCode: 0, result };
359
+ }
360
+ if (parsed.action === 'check') {
361
+ const result = await checkProject(root, { env: options.env ?? process.env });
362
+ log(parsed.json ? JSON.stringify(result) : result.absent ? text('result.absent') : text('result.check', result.summary));
363
+ return { exitCode: result.exitCode, result };
364
+ }
365
+ const result = await addScene(root, parsed.id, options.assets ?? resolveLauncherAssets());
366
+ log(text('result.scene', { id: result.id }));
367
+ return { exitCode: 0, result };
368
+ } catch (error) {
369
+ logError(error?.code === 'EEXIST' ? text('error.exists') : error instanceof Error ? error.message : String(error));
370
+ return { exitCode: 1 };
371
+ }
372
+ }
@@ -0,0 +1,92 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ export const emptyManifest = () => ({ version: 0, kind: 'akari-project-manifest', nodes: [], edges: [] });
6
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
7
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
8
+ const validNode = value => object(value) && typeof value.id === 'string' && typeof value.kind === 'string';
9
+ const validEdge = value => object(value) && typeof value.from === 'string' && typeof value.uses === 'string';
10
+
11
+ export function normalizeManifest(value) {
12
+ const input = object(value) ? value : {};
13
+ return {
14
+ ...input,
15
+ version: Number.isInteger(input.version) ? input.version : 0,
16
+ kind: typeof input.kind === 'string' ? input.kind : 'akari-project-manifest',
17
+ nodes: Array.isArray(input.nodes) ? input.nodes.filter(validNode).map(node => ({ ...node, rev: Number.isInteger(node.rev) && node.rev >= 0 ? node.rev : 0 })) : [],
18
+ edges: Array.isArray(input.edges) ? input.edges.filter(validEdge) : []
19
+ };
20
+ }
21
+
22
+ export function sortManifest(value) {
23
+ const manifest = normalizeManifest(value);
24
+ manifest.nodes.sort((a, b) => compare(a.kind, b.kind) || compare(a.id, b.id));
25
+ manifest.edges.sort((a, b) => compare(a.from, b.from) || compare(a.uses, b.uses));
26
+ return manifest;
27
+ }
28
+
29
+ export async function readJson(file, fallback = null) {
30
+ try { return JSON.parse(await fs.readFile(file, 'utf8')); }
31
+ catch (error) { if (error?.code === 'ENOENT') return fallback; throw error; }
32
+ }
33
+
34
+ export async function readManifest(projectRoot) {
35
+ await resolveWhere(projectRoot, '.akari/manifest.json');
36
+ return normalizeManifest(await readJson(path.join(projectRoot, '.akari', 'manifest.json')));
37
+ }
38
+
39
+ export async function writeJsonAtomic(file, value) {
40
+ const body = `${JSON.stringify(value, null, 2)}\n`;
41
+ await fs.mkdir(path.dirname(file), { recursive: true });
42
+ try { if (await fs.readFile(file, 'utf8') === body) return false; }
43
+ catch (error) { if (error?.code !== 'ENOENT') throw error; }
44
+ const temporary = `${file}.${randomUUID()}.tmp`;
45
+ try {
46
+ await fs.writeFile(temporary, body, { flag: 'wx' });
47
+ await fs.rename(temporary, file);
48
+ } finally { await fs.rm(temporary, { force: true }); }
49
+ return true;
50
+ }
51
+
52
+ export function manifestPath(projectRoot) { return path.join(projectRoot, '.akari', 'manifest.json'); }
53
+ export async function writeManifest(projectRoot, manifest) {
54
+ await resolveWhere(projectRoot, '.akari/manifest.json');
55
+ return writeJsonAtomic(manifestPath(projectRoot), sortManifest(manifest));
56
+ }
57
+
58
+ export async function resolveWhere(projectRoot, where) {
59
+ if (typeof where !== 'string' || !where || path.isAbsolute(where) || /^[A-Za-z]:/.test(where)
60
+ || where.includes('\\') || where.includes('..')) throw new Error('where is outside the project');
61
+ const relative = where.split('#', 1)[0];
62
+ if (!relative || relative.split('/').includes('..')) throw new Error('where is outside the project');
63
+ const root = await fs.realpath(projectRoot);
64
+ const candidate = path.resolve(root, relative);
65
+ const contains = target => target === root || target.startsWith(`${root}${path.sep}`);
66
+ if (!contains(candidate)) throw new Error('where is outside the project');
67
+ let cursor = candidate;
68
+ for (;;) {
69
+ try {
70
+ const real = await fs.realpath(cursor);
71
+ if (!contains(real)) throw new Error('where escapes the project through a symlink');
72
+ break;
73
+ } catch (error) {
74
+ if (error?.code !== 'ENOENT') throw error;
75
+ const parent = path.dirname(cursor);
76
+ if (parent === cursor) throw error;
77
+ cursor = parent;
78
+ }
79
+ }
80
+ try {
81
+ const actual = await fs.realpath(candidate);
82
+ if (!contains(actual)) throw new Error('where escapes the project through a symlink');
83
+ return { path: actual, exists: true, fragment: where.includes('#') ? where.slice(where.indexOf('#') + 1) : null };
84
+ } catch (error) {
85
+ if (error?.code === 'ENOENT') return { path: candidate, exists: false, fragment: null };
86
+ throw error;
87
+ }
88
+ }
89
+
90
+ export async function sha256(file) {
91
+ return createHash('sha256').update(await fs.readFile(file)).digest('hex');
92
+ }