editorbrain 0.5.0 → 0.6.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/README.md CHANGED
@@ -5,30 +5,28 @@ Editorial references, brand context and portable video projects for Claude Code
5
5
  Inspect the CLI without configuring your agent:
6
6
 
7
7
  ```sh
8
- npx editorbrain@0.5.0 help
8
+ npx editorbrain@0.6.0 help
9
9
  ```
10
10
 
11
11
  For a persistent installation:
12
12
 
13
13
  ```sh
14
- npm install -g editorbrain@0.5.0
14
+ npm install -g editorbrain@0.6.0
15
15
  editorbrain login --url https://api.editorbrain.com
16
16
  editorbrain status --url https://api.editorbrain.com
17
17
  editorbrain pull --dir ./my-videos --url https://api.editorbrain.com
18
18
  editorbrain skill install --dir ./my-videos --agent both
19
19
  ```
20
20
 
21
- Both `editorbrain` and the compatible `editorharness` command run the same CLI. Existing folders and skills remain named `editorharness`. Do not install both distributions globally at the same time; choose one rather than forcing binary conflicts.
22
-
23
21
  Create an account and follow connection instructions at https://editorbrain.com/app/settings. Login requires browser consent. Skills install locally; MCP authentication is configured separately. Preserve existing customized instructions and inspect installation conflicts. The package contains the CLI and skill documentation, not private library content or customer credentials. Editing and rendering use your agent's external tools.
24
22
 
25
23
  ## Installation and permissions
26
24
 
27
25
  - No install/postinstall hooks, runtime package dependencies, native binaries or background services. Installing the package does not register MCP servers or modify agent instructions.
28
26
  - Configuration happens only when you run a command. `skill install` writes the selected project's skill files and instruction pointers; existing customizations are preserved and conflicts reported.
29
- - `login` uses browser consent and stores the CLI credential in `~/.config/editorharness/config.json` (owner-only permissions on POSIX systems). This is a local credential file, not an OS keychain. Never share it or commit it.
27
+ - `login` uses browser consent and stores the CLI credential in `~/.config/editorbrain/config.json` (owner-only permissions on POSIX systems). This is a local credential file, not an OS keychain. Never share it or commit it.
30
28
  - Remote commands contact the selected API endpoint. Use the official `https://api.editorbrain.com` endpoint. Commands such as push and media upload transfer the selected documents or assets; npm installation and help do not upload your projects.
31
- - MCP credentials are separate and must be provided locally through the documented environment variable. Do not paste secrets into chats or project files.
29
+ - MCP uses separate OAuth consent in the browser. Do not paste secrets into chats or project files.
32
30
  - Updates are explicit. Pin a version for reproducibility; do not bypass agent permission prompts or use sudo/--force to resolve installation conflicts.
33
31
 
34
32
  Distribution is proprietary (UNLICENSED); publication on npm does not make the private service or library open source.
@@ -1,10 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // packages/cli/src/index.ts
4
- import { chmod, lstat as lstat3, mkdir as mkdir2, open as open4 } from "node:fs/promises";
5
- import { constants as constants4 } from "node:fs";
6
- import { homedir } from "node:os";
7
- import { basename, dirname as dirname2, extname, join as join2, resolve as resolve3 } from "node:path";
3
+ // packages/cli/src/setup.ts
4
+ import { spawn } from "node:child_process";
5
+ import { resolve as resolve3 } from "node:path";
8
6
 
9
7
  // packages/core/src/index.ts
10
8
  var SCHEMA_VERSION = 1;
@@ -30,9 +28,9 @@ function assertIdentifier(value) {
30
28
  }
31
29
  function safeDocumentPath(path) {
32
30
  if (typeof path !== "string" || path.length > 400 || /[\\\x00-\x1f\x7f%:]/.test(path) || path.startsWith("/") || path.endsWith("/")) throw new Error("Unsafe document path");
33
- const parts = path.split("/");
31
+ const parts = canonicalDocumentPath(path).split("/");
34
32
  if (parts.some((part) => !part || part === "." || part === ".." || part.length > 100 || !/^[a-zA-Z0-9_.-]+$/.test(part) || ["__proto__", "prototype", "constructor"].includes(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part) || /[. ]$/.test(part))) throw new Error("Unsafe or nonportable path segment");
35
- if (![".editorharness", "videos"].includes(parts[0]) || parts.length < 3 || !/\.(json|md)$/.test(parts.at(-1))) throw new Error("Documents must be .md/.json beneath .editorharness/ or videos/");
33
+ if (![".editorbrain", ".editorharness", "videos"].includes(parts[0]) || parts.length < 3 || !/\.(json|md)$/.test(parts.at(-1))) throw new Error("Documents must be .md/.json beneath .editorbrain/ or videos/");
36
34
  if (parts.some((part) => /^\.env(?:\.|$)/i.test(part) || [".sync.json", ".credentials.json", "credentials.json"].includes(part.toLowerCase()))) throw new Error("Credential and local state files cannot be synced");
37
35
  return path;
38
36
  }
@@ -86,10 +84,10 @@ function validateDocument(path, content) {
86
84
  return { valid: false, issues };
87
85
  }
88
86
  if (doc.schemaVersion !== SCHEMA_VERSION) add("schemaVersion must be 1");
89
- const parts = path.split("/");
90
- const isBrand = parts[0] === ".editorharness" && parts[1] === "brands" && parts.length === 4;
91
- const isStyle = parts[0] === ".editorharness" && parts[1] === "styles" && parts.length === 4;
92
- const isOutput = parts[0] === ".editorharness" && parts[1] === "output-profiles" && parts.length === 3;
87
+ const parts = canonicalDocumentPath(path).split("/");
88
+ const isBrand = parts[0] === ".editorbrain" && parts[1] === "brands" && parts.length === 4;
89
+ const isStyle = parts[0] === ".editorbrain" && parts[1] === "styles" && parts.length === 4;
90
+ const isOutput = parts[0] === ".editorbrain" && parts[1] === "output-profiles" && parts.length === 3;
93
91
  const isProject = parts[0] === "videos" && parts.length === 3 && parts[2] === "project.json";
94
92
  const isMedia = parts[0] === "videos" && parts.length === 3 && parts[2] === "media.json";
95
93
  if (isBrand || isStyle || isProject || isOutput) {
@@ -145,23 +143,24 @@ function validateDocument(path, content) {
145
143
  }
146
144
  function projectSources(project) {
147
145
  return [
148
- `.editorharness/brands/${project.brand}/brand.md`,
149
- `.editorharness/brands/${project.brand}/tokens.json`,
150
- `.editorharness/brands/${project.brand}/language.json`,
151
- `.editorharness/brands/${project.brand}/assets.json`,
152
- `.editorharness/styles/${project.style}/style.md`,
153
- `.editorharness/styles/${project.style}/style.json`,
154
- `.editorharness/styles/${project.style}/examples.json`,
155
- `.editorharness/output-profiles/${project.outputProfile}.json`,
146
+ `.editorbrain/brands/${project.brand}/brand.md`,
147
+ `.editorbrain/brands/${project.brand}/tokens.json`,
148
+ `.editorbrain/brands/${project.brand}/language.json`,
149
+ `.editorbrain/brands/${project.brand}/assets.json`,
150
+ `.editorbrain/styles/${project.style}/style.md`,
151
+ `.editorbrain/styles/${project.style}/style.json`,
152
+ `.editorbrain/styles/${project.style}/examples.json`,
153
+ `.editorbrain/output-profiles/${project.outputProfile}.json`,
156
154
  `videos/${project.id}/project.json`,
157
155
  `videos/${project.id}/brief.md`,
158
156
  `videos/${project.id}/direction.md`
159
157
  ];
160
158
  }
161
159
  function optionalProjectSources(project) {
162
- return [`.editorharness/brands/${project.brand}/design.md`, `.editorharness/styles/${project.style}/effects.md`, `.editorharness/styles/${project.style}/music.md`, `videos/${project.id}/media.json`];
160
+ return [`.editorbrain/brands/${project.brand}/design.md`, `.editorbrain/styles/${project.style}/effects.md`, `.editorbrain/styles/${project.style}/music.md`, `videos/${project.id}/media.json`];
163
161
  }
164
162
  function validateWorkspace(files) {
163
+ files = canonicalFiles(files);
165
164
  const issues = [];
166
165
  for (const [path, content] of Object.entries(files)) issues.push(...validateDocument(path, content).issues);
167
166
  for (const [path, content] of Object.entries(files)) {
@@ -181,6 +180,7 @@ async function sha256(content) {
181
180
  return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
182
181
  }
183
182
  async function resolveProject(files, projectId) {
183
+ files = canonicalFiles(files);
184
184
  assertIdentifier(projectId);
185
185
  const path = `videos/${projectId}/project.json`;
186
186
  if (!own(files, path)) throw new ValidationError([{ path, message: "Project does not exist" }]);
@@ -312,31 +312,39 @@ function createWorkspace(options = {}) {
312
312
  const project = assertIdentifier(options.project ?? "first-video");
313
313
  const json = (value) => stableJson({ schemaVersion: 1, ...value });
314
314
  return {
315
- [`.editorharness/brands/${brand}/brand.md`]: `# ${options.name ?? brand}
315
+ [`.editorbrain/brands/${brand}/brand.md`]: `# ${options.name ?? brand}
316
316
 
317
317
  Describe identity, audience, non-negotiables and preferred visual/audio treatment. Exact colors and fonts belong in tokens.json. Do not inherit reference colors automatically.
318
318
  `,
319
- [`.editorharness/brands/${brand}/design.md`]: "# Visual direction\n\nDescribe how the brand should look in context: hierarchy, readable typography, composition, photographic or illustration treatment, and use of negative space. Exact colors and fonts stay in tokens.json; refer to semantic roles instead of duplicating values here. Adapt positions and scale to the subject, material and output format. Separate graphic brand accents from natural skin tones and photographic grading. Prefer coherence and legibility over copying a reference frame literally.\n",
320
- [`.editorharness/brands/${brand}/tokens.json`]: json({ id: brand, tokens: {} }),
321
- [`.editorharness/brands/${brand}/language.json`]: json({ id: brand, defaultLanguage: "es", glossary: [], pronunciations: [], doNotTranslate: [] }),
322
- [`.editorharness/brands/${brand}/assets.json`]: json({ id: brand, assets: [] }),
323
- [`.editorharness/styles/${style}/style.md`]: "# Adaptive editorial style\n\nBuild a coherent edit around the script, audience and available material. Use B-roll to explain this topic, with a consistent photographic direction. Timing, typography, imagery and sound should support each narrative beat. Omit a technique if it weakens clarity. SFX require listening; do not infer their existence from images.\n",
324
- [`.editorharness/styles/${style}/effects.md`]: "# Effects and motion\n\nChoose each effect for an editorial function: reveal information, direct attention, explain a relationship or support a transition. Time motion to the actual speech, action and reading time. Adapt intensity, easing, scale and placement to the scene; omit effects when a hold or cut works better. Do not require a zoom, transition, animation or SFX in every beat. Keep observed reference effects separate from proposed effects and verified implementations.\n",
325
- [`.editorharness/styles/${style}/music.md`]: "# Music and sound\n\nChoose energy and instrumentation from the story and brand. Preserve voice intelligibility, use silence when it supports a thought, and adjust the mix after listening to the actual recording. Record provenance and available licenses for every music/SFX asset; a reference recording is not an automatically reusable track. Treat unidentified reference sounds as candidates. Avoid fixed track choices, sound quotas or universal loudness settings unless the output brief requires them.\n",
326
- [`.editorharness/styles/${style}/style.json`]: json({ id: style, name: "Adaptive", tokens: {}, references: [], components: [] }),
327
- [`.editorharness/styles/${style}/examples.json`]: json({ id: style, examples: [] }),
328
- ".editorharness/output-profiles/vertical.json": json({ id: "vertical", width: 1080, height: 1920, fps: 30, captions: { enabled: true, language: "es" } }),
329
- ".editorharness/library/index.json": json({ references: [], note: "Fetch references and examples on demand. Private media uses authenticated access." }),
330
- ".editorharness/memory/preferences.json": json({ confirmed: [], note: "Only explicitly confirmed feedback becomes a reusable preference. Keep scope and evidence." }),
319
+ [`.editorbrain/brands/${brand}/design.md`]: "# Visual direction\n\nDescribe how the brand should look in context: hierarchy, readable typography, composition, photographic or illustration treatment, and use of negative space. Exact colors and fonts stay in tokens.json; refer to semantic roles instead of duplicating values here. Adapt positions and scale to the subject, material and output format. Separate graphic brand accents from natural skin tones and photographic grading. Prefer coherence and legibility over copying a reference frame literally.\n",
320
+ [`.editorbrain/brands/${brand}/tokens.json`]: json({ id: brand, tokens: {} }),
321
+ [`.editorbrain/brands/${brand}/language.json`]: json({ id: brand, defaultLanguage: "es", glossary: [], pronunciations: [], doNotTranslate: [] }),
322
+ [`.editorbrain/brands/${brand}/assets.json`]: json({ id: brand, assets: [] }),
323
+ [`.editorbrain/styles/${style}/style.md`]: "# Adaptive editorial style\n\nBuild a coherent edit around the script, audience and available material. Use B-roll to explain this topic, with a consistent photographic direction. Timing, typography, imagery and sound should support each narrative beat. Omit a technique if it weakens clarity. SFX require listening; do not infer their existence from images.\n",
324
+ [`.editorbrain/styles/${style}/effects.md`]: "# Effects and motion\n\nChoose each effect for an editorial function: reveal information, direct attention, explain a relationship or support a transition. Time motion to the actual speech, action and reading time. Adapt intensity, easing, scale and placement to the scene; omit effects when a hold or cut works better. Do not require a zoom, transition, animation or SFX in every beat. Keep observed reference effects separate from proposed effects and verified implementations.\n",
325
+ [`.editorbrain/styles/${style}/music.md`]: "# Music and sound\n\nChoose energy and instrumentation from the story and brand. Preserve voice intelligibility, use silence when it supports a thought, and adjust the mix after listening to the actual recording. Record provenance and available licenses for every music/SFX asset; a reference recording is not an automatically reusable track. Treat unidentified reference sounds as candidates. Avoid fixed track choices, sound quotas or universal loudness settings unless the output brief requires them.\n",
326
+ [`.editorbrain/styles/${style}/style.json`]: json({ id: style, name: "Adaptive", tokens: {}, references: [], components: [] }),
327
+ [`.editorbrain/styles/${style}/examples.json`]: json({ id: style, examples: [] }),
328
+ ".editorbrain/output-profiles/vertical.json": json({ id: "vertical", width: 1080, height: 1920, fps: 30, captions: { enabled: true, language: "es" } }),
329
+ ".editorbrain/library/index.json": json({ references: [], note: "Fetch references and examples on demand. Private media uses authenticated access." }),
330
+ ".editorbrain/memory/preferences.json": json({ confirmed: [], note: "Only explicitly confirmed feedback becomes a reusable preference. Keep scope and evidence." }),
331
331
  [`videos/${project}/project.json`]: json({ id: project, brand, style, outputProfile: "vertical", intent: { topic: options.topic ?? "Define the subject of this video", goal: options.goal ?? "Explain the subject clearly" }, script: "", overrides: {} }),
332
332
  [`videos/${project}/brief.md`]: "# Brief\n\nDescribe the objective, audience, script or source video, constraints and available assets.\n",
333
- [`videos/${project}/direction.md`]: "# Direction\n\nDIRECTION_PENDING\n\nRead the installed Editor Harness skill and its AGENTS.md. Inspect the actual script, media, brand and selected evidence. State the intended transfer: faithful preset, editorial family or inspiration. Connect each beat to its meaning, resource/action, composition, motion, real timing and verification. Distinguish observed evidence, inference and new design. Define layer treatments, justify source reuse, and review movement and SFX in the final render. Preserve reference hashes and project-scoped feedback. A plan is not an executed or verified edit.\n"
333
+ [`videos/${project}/direction.md`]: "# Direction\n\nDIRECTION_PENDING\n\nRead the installed EditorBrain skill and its AGENTS.md. Inspect the actual script, media, brand and selected evidence. State the intended transfer: faithful preset, editorial family or inspiration. Connect each beat to its meaning, resource/action, composition, motion, real timing and verification. Distinguish observed evidence, inference and new design. Define layer treatments, justify source reuse, and review movement and SFX in the final render. Preserve reference hashes and project-scoped feedback. A plan is not an executed or verified edit.\n"
334
334
  };
335
335
  }
336
-
337
- // packages/cli/src/doctor.ts
338
- import { readFile } from "node:fs/promises";
339
- import { resolve as resolve2 } from "node:path";
336
+ function canonicalDocumentPath(path) {
337
+ return path.replace(/^\.editorharness\//, ".editorbrain/");
338
+ }
339
+ function canonicalFiles(files) {
340
+ const result = {};
341
+ for (const [path, content] of Object.entries(files)) {
342
+ const canonical = canonicalDocumentPath(path);
343
+ if (Object.prototype.hasOwnProperty.call(result, canonical) && result[canonical] !== content) throw new Error("Conflicting workspace layouts. Keep both copies and resolve their differences before continuing.");
344
+ result[canonical] = content;
345
+ }
346
+ return result;
347
+ }
340
348
 
341
349
  // packages/cli/src/io.ts
342
350
  import { constants } from "node:fs";
@@ -432,8 +440,9 @@ async function readWorkspace(root) {
432
440
  }
433
441
  }
434
442
  await walk(".editorharness");
443
+ await walk(".editorbrain");
435
444
  await walk("videos");
436
- return files;
445
+ return canonicalFiles(files);
437
446
  }
438
447
 
439
448
  // packages/cli/src/client.ts
@@ -577,7 +586,7 @@ var Client = class {
577
586
  return this.request(`/v1/documents/${safeDocumentPath(path).split("/").map(encodeURIComponent).join("/")}`, { method: "PUT", body: { content, expectedRevision } });
578
587
  }
579
588
  async media(path, options = {}) {
580
- if (!/^\/v1\/assets\/[a-f0-9]{64}(?:\?|$)/.test(path)) throw new Error("Invalid asset endpoint");
589
+ if (!/^\/v1\/assets\/[a-f0-9]{64}(?:\?|$)/.test(path) && !(!options.content && /^\/v1\/library\/[^/?#]+\/media\/[a-f0-9]{64}$/.test(path))) throw new Error("Invalid asset endpoint");
581
590
  const headers = { Authorization: `Bearer ${this.config.apiKey}` };
582
591
  if (options.content) {
583
592
  headers["Content-Type"] = options.mimeType ?? "application/octet-stream";
@@ -590,21 +599,31 @@ var Client = class {
590
599
  };
591
600
  async function loadSyncState(root, endpoint, workspaceId) {
592
601
  try {
593
- const state = JSON.parse(await readText(root, ".editorharness/.sync.json", false));
602
+ const raw = await readText(root, ".editorbrain/.sync.json", false).catch((error) => {
603
+ if (error.code !== "ENOENT") throw error;
604
+ return readText(root, ".editorharness/.sync.json", false);
605
+ });
606
+ const state = JSON.parse(raw);
594
607
  if (state.schemaVersion !== 1 || typeof state.documents !== "object") throw new Error("Invalid local sync state");
595
608
  if (state.endpoint !== endpoint || state.workspaceId !== workspaceId) throw new CliError("WORKSPACE_MISMATCH", "This folder is bound to a different endpoint/workspace.", "Use a separate folder; never merge private documents across spaces.");
596
609
  for (const [path, item] of Object.entries(state.documents)) {
597
610
  safeDocumentPath(path);
598
611
  if (!Number.isInteger(item.revision) || item.revision < 1 || !/^[a-f0-9]{64}$/.test(item.sha256)) throw new Error("Invalid local revision");
599
612
  }
600
- return state;
613
+ const documents = {};
614
+ for (const [path, item] of Object.entries(state.documents)) {
615
+ const canonical = canonicalDocumentPath(path);
616
+ if (documents[canonical] && (documents[canonical].revision !== item.revision || documents[canonical].sha256 !== item.sha256)) throw new Error("Conflicting sync state aliases");
617
+ documents[canonical] = item;
618
+ }
619
+ return { ...state, documents };
601
620
  } catch (error) {
602
621
  if (error.code !== "ENOENT") throw error;
603
622
  return { schemaVersion: 1, endpoint, workspaceId, documents: {} };
604
623
  }
605
624
  }
606
625
  async function saveSyncState(root, state) {
607
- await atomicWrite(root, ".editorharness/.sync.json", stableJson(state), { document: false, mode: 384 });
626
+ await atomicWrite(root, ".editorbrain/.sync.json", stableJson(state), { document: false, mode: 384 });
608
627
  }
609
628
  function checkRemote(summary) {
610
629
  safeDocumentPath(summary.path);
@@ -710,19 +729,21 @@ ${conflicts.join("\n")}`, "Run pull --dry-run and reconcile the reported paths."
710
729
  }
711
730
 
712
731
  // packages/cli/src/agent-guidance.ts
732
+ import { createHash } from "node:crypto";
713
733
  import { constants as constants2 } from "node:fs";
714
- import { lstat as lstat2, open as open2, readdir as readdir2 } from "node:fs/promises";
734
+ import { lstat as lstat2, open as open2, readdir as readdir2, rename as rename2 } from "node:fs/promises";
715
735
  import { fileURLToPath } from "node:url";
736
+ var previousSkillHashes = { "SKILL.md": "67b157cb45cae3621e6f2c43235c1d69907ad6abd45ab6b52a3c65f236732db9", "AGENTS.md": "4f3ef860ade3a31aa7c6a6aab5cf6ec2a700850bf19ea2320324c12c2e0fbf5b", "references/cli-mcp.md": "8e011c31368cef2117a28ee972b39aab9535eeb0f601a4a0f9d6fc019b22c1c2", "references/production-and-review.md": "055c6df9e0f167be148b0a5c0bba5b43e108eb1f58f478d88b3536c6589ac7b3", "references/workspace-files.md": "e72af2871f42cd776be1bfff8009ed5562780e7f8a65b12c27887f3880631f81" };
716
737
  var destinations = {
717
- codex: { directory: ".agents/skills/editorharness", entryPoint: "AGENTS.md" },
718
- claude: { directory: ".claude/skills/editorharness", entryPoint: "CLAUDE.md" }
738
+ codex: { directory: ".agents/skills/editorbrain", entryPoint: "AGENTS.md" },
739
+ claude: { directory: ".claude/skills/editorbrain", entryPoint: "CLAUDE.md" }
719
740
  };
720
741
  function parseAgentTarget(value = "both") {
721
742
  if (value !== "codex" && value !== "claude" && value !== "both") throw new Error("--agent must be codex, claude or both");
722
743
  return value;
723
744
  }
724
745
  function bundledSkillDirectory(moduleUrl = import.meta.url) {
725
- return fileURLToPath(new URL("../skill/editorharness/", moduleUrl));
746
+ return fileURLToPath(new URL("../skill/editorbrain/", moduleUrl));
726
747
  }
727
748
  async function readBytes(root, path) {
728
749
  const target = await checkedPath(root, path, false);
@@ -758,7 +779,7 @@ async function loadSkill(directory) {
758
779
  }
759
780
  }
760
781
  await walk();
761
- if (!files.has("SKILL.md")) throw new Error("Bundled Editor Harness skill is missing SKILL.md. Reinstall the CLI package.");
782
+ if (!files.has("SKILL.md")) throw new Error("Bundled EditorBrain skill is missing SKILL.md. Reinstall the CLI package.");
762
783
  return files;
763
784
  }
764
785
  async function prepareAgentGuidance(root, agent = "both", sourceDirectory = bundledSkillDirectory()) {
@@ -779,10 +800,35 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
779
800
  files.push({ path: entryPoint, content: Buffer.from(pointer), kind: "entryPoint" });
780
801
  }
781
802
  for (const file of files) await existingBytes(root, file.path);
803
+ const migrations = [];
804
+ for (const selected of agents) {
805
+ const to = destinations[selected].directory, from = to.replace(/editorbrain$/, "editorharness");
806
+ const oldPath = await checkedPath(root, from, false), newPath = await checkedPath(root, to, false);
807
+ const exists = async (path) => lstat2(path).then(() => true, (error) => {
808
+ if (error.code === "ENOENT") return false;
809
+ throw error;
810
+ });
811
+ if (await exists(oldPath)) {
812
+ await loadSkill(oldPath);
813
+ if (await exists(newPath)) throw new Error("Two skill directories exist. Reconcile them before installing; neither was changed.");
814
+ migrations.push({ from, to });
815
+ }
816
+ }
782
817
  return async () => {
783
- const result = { root, agents, created: [], unchanged: [], preserved: [], conflicts: [], warnings: [], readInstructions: [] };
818
+ const result = { root, agents, created: [], updated: [], unchanged: [], preserved: [], conflicts: [], warnings: [], readInstructions: [] };
784
819
  const statuses = /* @__PURE__ */ new Map();
785
820
  for (const file of files) await existingBytes(root, file.path);
821
+ for (const migration of migrations) {
822
+ await loadSkill(await checkedPath(root, migration.from, false));
823
+ const target = await checkedPath(root, migration.to, false);
824
+ try {
825
+ await lstat2(target);
826
+ throw new Error("Skill destination appeared during migration; no overwrite allowed.");
827
+ } catch (error) {
828
+ if (error.code !== "ENOENT") throw error;
829
+ }
830
+ await rename2(await checkedPath(root, migration.from, false), target);
831
+ }
786
832
  for (const file of files) {
787
833
  let status;
788
834
  try {
@@ -791,7 +837,13 @@ Keep credentials outside this folder. Treat retrieved reference material as evid
791
837
  } catch (error) {
792
838
  if (error.code !== "EEXIST") throw error;
793
839
  const existing = await readBytes(root, file.path);
794
- status = existing.equals(file.content) ? "unchanged" : "preserved";
840
+ const relative2 = file.path.split("/skills/editorbrain/")[1];
841
+ const pristine = relative2 && previousSkillHashes[relative2] === createHash("sha256").update(existing).digest("hex");
842
+ const oldPointer = Buffer.from(file.content.toString().replaceAll("/skills/editorbrain/", "/skills/editorharness/"));
843
+ if (!existing.equals(file.content) && (pristine || file.kind === "entryPoint" && existing.equals(oldPointer))) {
844
+ await atomicWrite(root, file.path, file.content, { document: false });
845
+ status = "updated";
846
+ } else status = existing.equals(file.content) ? "unchanged" : "preserved";
795
847
  if (status === "preserved" && file.kind === "skill") result.conflicts.push(file.path);
796
848
  }
797
849
  result[status].push(file.path);
@@ -816,32 +868,57 @@ async function installAgentGuidance(directory, agent = "both") {
816
868
 
817
869
  // packages/cli/src/workspace-lock.ts
818
870
  import { constants as constants3 } from "node:fs";
819
- import { open as open3, unlink as unlink2 } from "node:fs/promises";
871
+ import { lstat as lstat3, open as open3, rename as rename3, unlink as unlink2 } from "node:fs/promises";
820
872
  import { hostname } from "node:os";
821
873
  import { randomUUID as randomUUID2 } from "node:crypto";
822
- var LOCK_PATH = ".editorharness-operation.lock";
874
+ var LOCK_PATH = ".editorbrain-operation.lock";
823
875
  async function withWorkspaceLock(root, operation) {
824
- const path = await checkedPath(root, LOCK_PATH, false);
825
- let handle;
876
+ const legacyLock = await checkedPath(root, ".editorharness-operation.lock", false);
877
+ let legacy;
826
878
  try {
827
- handle = await open3(path, constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW, 384);
879
+ legacy = await open3(legacyLock, constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW, 384);
828
880
  } catch (error) {
829
- if (error.code !== "EEXIST") throw error;
830
- throw new CliError("WORKSPACE_BUSY", "Another CLI operation holds this workspace lock.", "Wait for the other operation. If it crashed, verify no process is using the folder before removing .editorharness-operation.lock. Locks are never removed automatically.");
881
+ if (error.code === "EEXIST") throw new CliError("WORKSPACE_BUSY", "Another CLI operation holds this workspace lock.", "Wait for the other operation to finish.");
882
+ throw error;
831
883
  }
832
- const owner = JSON.stringify({ pid: process.pid, host: hostname(), nonce: randomUUID2(), startedAt: (/* @__PURE__ */ new Date()).toISOString() });
833
884
  try {
834
- await handle.writeFile(owner);
835
- await handle.close();
836
- return await operation();
885
+ const path = await checkedPath(root, LOCK_PATH, false);
886
+ let handle;
887
+ try {
888
+ handle = await open3(path, constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW, 384);
889
+ } catch (error) {
890
+ if (error.code !== "EEXIST") throw error;
891
+ throw new CliError("WORKSPACE_BUSY", "Another CLI operation holds this workspace lock.", "Wait for the other operation. If it crashed, verify no process is using the folder before removing .editorbrain-operation.lock. Locks are never removed automatically.");
892
+ }
893
+ const owner = JSON.stringify({ pid: process.pid, host: hostname(), nonce: randomUUID2(), startedAt: (/* @__PURE__ */ new Date()).toISOString() });
894
+ try {
895
+ await handle.writeFile(owner);
896
+ await handle.close();
897
+ const oldRoot = await checkedPath(root, ".editorharness", false);
898
+ const newRoot = await checkedPath(root, ".editorbrain", false);
899
+ const exists = async (path2) => lstat3(path2).then(() => true, (error) => {
900
+ if (error.code === "ENOENT") return false;
901
+ throw error;
902
+ });
903
+ if (await exists(oldRoot)) {
904
+ if (await exists(newRoot)) throw new CliError("WORKSPACE_PATH_CONFLICT", "This folder contains two versions of the workspace directory.", "Reconcile the directories before continuing; neither was changed.");
905
+ await rename3(oldRoot, newRoot);
906
+ }
907
+ return await operation();
908
+ } finally {
909
+ await handle.close().catch(() => {
910
+ });
911
+ if (await readText(root, LOCK_PATH, false).catch(() => void 0) === owner) await unlink2(await checkedPath(root, LOCK_PATH, false));
912
+ }
837
913
  } finally {
838
- await handle.close().catch(() => {
839
- });
840
- if (await readText(root, LOCK_PATH, false).catch(() => void 0) === owner) await unlink2(await checkedPath(root, LOCK_PATH, false));
914
+ await legacy.close();
915
+ await unlink2(legacyLock);
841
916
  }
842
917
  }
843
918
 
844
919
  // packages/cli/src/doctor.ts
920
+ import { readFile } from "node:fs/promises";
921
+ import { resolve as resolve2 } from "node:path";
845
922
  async function cliVersion() {
846
923
  const metadata = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
847
924
  return metadata.version;
@@ -871,7 +948,7 @@ async function diagnose(options, fetcher = fetch) {
871
948
  else throw error;
872
949
  }
873
950
  for (const agent of options.agent === "both" ? ["codex", "claude"] : [options.agent]) {
874
- const directory = agent === "codex" ? ".agents/skills/editorharness" : ".claude/skills/editorharness";
951
+ const directory = agent === "codex" ? ".agents/skills/editorbrain" : ".claude/skills/editorbrain";
875
952
  let different = false;
876
953
  try {
877
954
  for (const file of guidanceFiles) {
@@ -909,8 +986,120 @@ async function diagnose(options, fetcher = fetch) {
909
986
  return { schemaVersion: 1, cliVersion: await cliVersion(), ok: !checks.some((check) => check.status === "fail"), directory: root ?? resolve2(options.directory), workspaceId, checks, mcpClient: "not_verified", renderVerified: false };
910
987
  }
911
988
 
989
+ // packages/cli/src/setup.ts
990
+ var runHost = (command, args, cwd, interactive = false) => new Promise((done, reject) => {
991
+ const child = spawn(command, args, { cwd, shell: false, stdio: ["ignore", interactive ? 2 : "pipe", interactive ? 2 : "pipe"], windowsHide: !interactive });
992
+ let stdout = "", stderr = "", size = 0;
993
+ const collect = (kind, data) => {
994
+ size += data.length;
995
+ if (size > 1024 * 1024) {
996
+ child.kill();
997
+ reject(new CliError("HOST_OUTPUT_LIMIT", "Agent CLI returned too much output.", "Configure MCP using the documented manual command."));
998
+ return;
999
+ }
1000
+ if (kind === "stdout") stdout += data;
1001
+ else stderr += data;
1002
+ };
1003
+ child.stdout?.on("data", (chunk) => collect("stdout", chunk));
1004
+ child.stderr?.on("data", (chunk) => collect("stderr", chunk));
1005
+ const timer = setTimeout(() => {
1006
+ child.kill();
1007
+ reject(new CliError("HOST_TIMEOUT", "Agent configuration did not finish.", "Check the agent configuration before running setup again."));
1008
+ }, interactive ? 18e4 : 15e3);
1009
+ child.once("error", (error) => {
1010
+ clearTimeout(timer);
1011
+ reject(error);
1012
+ });
1013
+ child.once("close", (code) => {
1014
+ clearTimeout(timer);
1015
+ done({ code, stdout, stderr });
1016
+ });
1017
+ });
1018
+ async function configureMcp(agent, directory, url, noBrowser, runner = runHost) {
1019
+ const endpoint = url + "/mcp";
1020
+ const args = agent === "codex" ? ["mcp", "add", "editorbrain", "--url", endpoint] : ["mcp", "add", "--transport", "http", "--scope", "project", "editorbrain", endpoint];
1021
+ const next = agent === "codex" ? "Run codex mcp login editorbrain, then verify workspace_info inside Codex." : "Open Claude Code in this folder, approve the project MCP and use /mcp to authorize. Then verify workspace_info.";
1022
+ if (noBrowser) return { agent, status: "action_required", command: [agent, ...args], next, hostVerified: false };
1023
+ const version = await runner(agent, ["--version"], directory);
1024
+ if (version.code !== 0) throw new CliError("AGENT_UNAVAILABLE", `${agent} CLI is unavailable.`, "Install the official agent CLI, or use setup --skip-mcp.");
1025
+ const inspect = await runner(agent, agent === "codex" ? ["mcp", "list", "--json"] : ["mcp", "get", "editorbrain"], directory);
1026
+ let exists = false;
1027
+ if (agent === "codex") {
1028
+ if (inspect.code !== 0) throw new CliError("MCP_INSPECTION_FAILED", "Could not inspect Codex MCP configuration.", "Inspect it manually; setup did not overwrite it.");
1029
+ let list;
1030
+ try {
1031
+ list = JSON.parse(inspect.stdout);
1032
+ } catch {
1033
+ throw new CliError("MCP_INSPECTION_FAILED", "Codex returned an unsupported configuration format.", "Inspect MCP configuration manually.");
1034
+ }
1035
+ if (!Array.isArray(list)) throw new CliError("MCP_INSPECTION_FAILED", "Unsupported MCP configuration response.", "Inspect MCP configuration manually.");
1036
+ exists = list.some((item) => item?.name === "editorbrain");
1037
+ } else {
1038
+ exists = inspect.code === 0;
1039
+ if (!exists && !/^No MCP server named "editorbrain"[.\s]/.test(inspect.stderr + inspect.stdout)) throw new CliError("MCP_INSPECTION_FAILED", "Could not inspect Claude MCP configuration.", "Inspect it manually; setup did not overwrite it.");
1040
+ }
1041
+ if (exists) return { agent, status: "preserved", next: "An existing editorbrain server was preserved. Check its endpoint and authentication, then " + next, hostVerified: false };
1042
+ const added = await runner(agent, args, directory, true);
1043
+ return { agent, status: added.code === 0 ? "registered" : "action_required", next, hostVerified: false };
1044
+ }
1045
+ async function setup(options, runner = runHost) {
1046
+ const steps = {};
1047
+ let selected = await options.getConfig();
1048
+ let client = new Client(selected);
1049
+ let me;
1050
+ try {
1051
+ if (!selected.apiKey) throw new CliError("AUTH_REQUIRED", "Login required.", "Run login.");
1052
+ me = await client.me();
1053
+ } catch (error) {
1054
+ if (!(error instanceof CliError) || error.code !== "AUTH_REQUIRED") throw error;
1055
+ await options.login();
1056
+ selected = await options.getConfig();
1057
+ client = new Client(selected);
1058
+ me = await client.me();
1059
+ }
1060
+ if (options.workspaceId && me.workspaceId !== options.workspaceId) throw new CliError("WORKSPACE_MISMATCH", "The authorized account selected a different workspace.", "Run login for the intended workspace. No project files were changed.");
1061
+ steps.account = { status: "verified", workspaceId: me.workspaceId, endpoint: client.url };
1062
+ const root = await ensureRoot(resolve3(options.directory), true);
1063
+ let folderReady = false, skillReady = false;
1064
+ await withWorkspaceLock(root, async () => {
1065
+ try {
1066
+ steps.documents = { status: "ready", ...await pullWorkspace(client, root, await readWorkspace(root)) };
1067
+ folderReady = true;
1068
+ } catch (error) {
1069
+ steps.documents = { status: "failed", ...errorOutput(error) };
1070
+ }
1071
+ try {
1072
+ const result = await installAgentGuidance(root, options.agent);
1073
+ steps.skill = { status: result.conflicts.length ? "review_required" : "ready", ...result };
1074
+ skillReady = !result.conflicts.length;
1075
+ } catch (error) {
1076
+ steps.skill = { status: "failed", ...errorOutput(error) };
1077
+ }
1078
+ });
1079
+ const hosts = [];
1080
+ if (!options.skipMcp && folderReady) {
1081
+ for (const agent of options.agent === "both" ? ["codex", "claude"] : [options.agent]) {
1082
+ try {
1083
+ hosts.push(await configureMcp(agent, root, client.url, !!options.noBrowser, runner));
1084
+ } catch (error) {
1085
+ hosts.push({ agent, status: "action_required", ...errorOutput(error), hostVerified: false });
1086
+ }
1087
+ }
1088
+ }
1089
+ steps.mcp = { status: options.skipMcp ? "skipped" : "verification_required", hosts, expectedWorkspaceId: me.workspaceId, next: "Inside your agent, call workspace_info and confirm this workspace ID. Configuration alone does not verify a connection." };
1090
+ const diagnosis = await diagnose({ directory: root, agent: options.agent, config: selected });
1091
+ steps.diagnostics = diagnosis;
1092
+ return { schemaVersion: 1, directory: root, workspaceId: me.workspaceId, cliReady: folderReady && skillReady && diagnosis.ok, status: folderReady && skillReady && diagnosis.ok && options.skipMcp ? "ready" : "action_required", steps, renderVerified: false };
1093
+ }
1094
+
1095
+ // packages/cli/src/index.ts
1096
+ import { chmod, lstat as lstat4, mkdir as mkdir2, open as open4 } from "node:fs/promises";
1097
+ import { constants as constants4 } from "node:fs";
1098
+ import { homedir } from "node:os";
1099
+ import { basename, dirname as dirname2, extname, join as join2, resolve as resolve4 } from "node:path";
1100
+
912
1101
  // packages/cli/src/device-auth.ts
913
- import { spawn } from "node:child_process";
1102
+ import { spawn as spawn2 } from "node:child_process";
914
1103
  import { setTimeout as delay2 } from "node:timers/promises";
915
1104
  var DEFAULT_API_URL = "https://api.editorbrain.com";
916
1105
  var DeviceLoginError = class extends Error {
@@ -928,12 +1117,12 @@ function browserCommand(url, platform = process.platform) {
928
1117
  }
929
1118
  async function openSystemBrowser(url) {
930
1119
  const { command, args } = browserCommand(url);
931
- await new Promise((resolve4, reject) => {
932
- const child = spawn(command, args, { shell: false, stdio: "ignore", detached: true, windowsHide: true });
1120
+ await new Promise((resolve5, reject) => {
1121
+ const child = spawn2(command, args, { shell: false, stdio: "ignore", detached: true, windowsHide: true });
933
1122
  child.once("error", reject);
934
1123
  child.once("spawn", () => {
935
1124
  child.unref();
936
- resolve4();
1125
+ resolve5();
937
1126
  });
938
1127
  });
939
1128
  }
@@ -1113,30 +1302,34 @@ async function prepareDirectionContext(root, client, projectId) {
1113
1302
  var HELP = `EditorBrain \u2014 portable editorial context for AI video agents
1114
1303
 
1115
1304
  editorbrain version
1305
+ editorbrain setup --dir folder --agent codex|claude|both [--workspace id] [--no-browser] [--skip-mcp]
1116
1306
  editorbrain doctor [--dir folder] [--agent codex|claude|both] [--offline]
1117
- editorharness init [--dir folder] [--brand id] [--style id] [--project id] [--topic text] [--goal text] [--agent codex|claude|both]
1118
- editorharness skill install [--dir folder] [--agent codex|claude|both]
1119
- editorharness validate [--dir folder]
1120
- editorharness resolve <project-id> [--dir folder]
1121
- editorharness export <project-id> --adapter neutral|hyperframes|remotion [--out folder] [--dir folder]
1122
- editorharness login [--url https://server] [--no-browser] [--timeout seconds]
1123
- editorharness login [--url https://server] --key-stdin
1124
- editorharness register --url https://server --name workspace --invite-stdin
1125
- editorharness status
1126
- editorharness push|pull [--dir folder] [--dry-run]
1127
- editorharness library search [query]
1128
- editorharness library get <video-id> [--document relative-source-path]
1129
- editorharness styles list
1130
- editorharness styles recommend <project-id> [--assets tag,tag] [--capabilities tag,tag] [--style pack-id] [--duration seconds]
1131
- editorharness direction draft <project-id> [--assets tag,tag] [--capabilities tag,tag] [--style pack-id] [--duration seconds] [--out new-folder]
1132
- editorharness assets list [--limit 200] [--cursor opaque-cursor]
1133
- editorharness assets upload <file> [--mime supported-media-type]
1134
- editorharness assets download <sha256> --out file
1135
- editorharness keys list
1136
- editorharness keys create --label name [--role reader|editor|owner]
1137
- editorharness keys revoke <key-id>
1307
+ editorbrain init [--dir folder] [--brand id] [--style id] [--project id] [--topic text] [--goal text] [--agent codex|claude|both]
1308
+ editorbrain skill install [--dir folder] [--agent codex|claude|both]
1309
+ editorbrain validate [--dir folder]
1310
+ editorbrain resolve <project-id> [--dir folder]
1311
+ editorbrain export <project-id> --adapter neutral|hyperframes|remotion [--out folder] [--dir folder]
1312
+ editorbrain login [--url https://server] [--no-browser] [--timeout seconds]
1313
+ editorbrain login [--url https://server] --key-stdin
1314
+ editorbrain register --url https://server --name workspace --invite-stdin
1315
+ editorbrain status
1316
+ editorbrain push|pull [--dir folder] [--dry-run]
1317
+ editorbrain library search [query]
1318
+ editorbrain library get <video-id> [--document relative-source-path] [--sha256 source-hash]
1319
+ editorbrain library media <video-id> --sha256 media-hash --out file
1320
+ editorbrain narrative search [query] [--kind hook|cta|...] [--channel visual|spoken|...] [--limit 10]
1321
+ editorbrain narrative get <video-id> [--sha256 document-hash] [--event-offset 0] [--relation-offset 0] [--limit 50]
1322
+ editorbrain styles list
1323
+ editorbrain styles recommend <project-id> [--assets tag,tag] [--capabilities tag,tag] [--style pack-id] [--duration seconds]
1324
+ editorbrain direction draft <project-id> [--assets tag,tag] [--capabilities tag,tag] [--style pack-id] [--duration seconds] [--out new-folder]
1325
+ editorbrain assets list [--limit 200] [--cursor opaque-cursor]
1326
+ editorbrain assets upload <file> [--mime supported-media-type]
1327
+ editorbrain assets download <sha256> --out file
1328
+ editorbrain keys list
1329
+ editorbrain keys create --label name [--role reader|editor|owner]
1330
+ editorbrain keys revoke <key-id>
1138
1331
 
1139
- Authentication: EDITORHARNESS_URL and EDITORHARNESS_API_KEY, or login.
1332
+ Authentication: EDITORBRAIN_URL and EDITORBRAIN_API_KEY, or login.
1140
1333
  Secrets go to a user config with mode 0600, never the portable project.
1141
1334
  Resolve writes the source-hash lock. Export produces a handoff, not a rendered video.
1142
1335
  Push/pull preserve conflicting changes; media uploads use the separate assets command.
@@ -1147,8 +1340,8 @@ Output is JSON except help; login progress/code goes to stderr. --url overrides
1147
1340
  function parseArgs(argv) {
1148
1341
  const positional = [];
1149
1342
  const flags = {};
1150
- const booleans = /* @__PURE__ */ new Set(["help", "version", "offline", "dry-run", "key-stdin", "invite-stdin", "no-browser"]);
1151
- const known = /* @__PURE__ */ new Set(["dir", "brand", "style", "project", "topic", "goal", "name", "adapter", "out", "url", "document", "mime", "label", "role", "limit", "cursor", "timeout", "assets", "capabilities", "duration", "agent", ...booleans]);
1343
+ const booleans = /* @__PURE__ */ new Set(["help", "version", "offline", "dry-run", "key-stdin", "invite-stdin", "no-browser", "skip-mcp"]);
1344
+ const known = /* @__PURE__ */ new Set(["dir", "brand", "style", "project", "topic", "goal", "name", "adapter", "out", "url", "document", "mime", "label", "role", "limit", "cursor", "timeout", "assets", "capabilities", "duration", "agent", "workspace", "sha256", "kind", "channel", "epistemic-status", "event-offset", "relation-offset", ...booleans]);
1152
1345
  for (let i = 0; i < argv.length; i++) {
1153
1346
  const arg = argv[i];
1154
1347
  if (!arg.startsWith("--")) {
@@ -1174,7 +1367,15 @@ function output(value) {
1174
1367
  process.stdout.write(stableJson(value));
1175
1368
  }
1176
1369
  async function configRoot(create = false) {
1177
- const path = process.env.EDITORHARNESS_CONFIG_DIR ?? join2(homedir(), ".config", "editorharness");
1370
+ let path = process.env.EDITORBRAIN_CONFIG_DIR ?? process.env.EDITORHARNESS_CONFIG_DIR ?? join2(homedir(), ".config", "editorbrain");
1371
+ if (!create && !process.env.EDITORBRAIN_CONFIG_DIR && !process.env.EDITORHARNESS_CONFIG_DIR) {
1372
+ try {
1373
+ await lstat4(path);
1374
+ } catch (error) {
1375
+ if (error.code !== "ENOENT") throw error;
1376
+ path = join2(homedir(), ".config", "editorharness");
1377
+ }
1378
+ }
1178
1379
  if (create) await mkdir2(path, { recursive: true, mode: 448 });
1179
1380
  return ensureRoot(path);
1180
1381
  }
@@ -1196,10 +1397,10 @@ async function saveConfig(config2) {
1196
1397
  }
1197
1398
  async function config(args, requireKey = true) {
1198
1399
  const stored = await loadConfig();
1199
- const url = normalizeUrl(str(args, "url") ?? process.env.EDITORHARNESS_URL ?? stored.url ?? DEFAULT_API_URL);
1400
+ const url = normalizeUrl(str(args, "url") ?? process.env.EDITORBRAIN_URL ?? process.env.EDITORHARNESS_URL ?? stored.url ?? DEFAULT_API_URL);
1200
1401
  const storedKey = stored.url && normalizeUrl(stored.url) === url ? stored.apiKey : void 0;
1201
- const apiKey = process.env.EDITORHARNESS_API_KEY ?? storedKey ?? "";
1202
- if (requireKey && !apiKey) throw new CliError("AUTH_REQUIRED", "Run editorbrain login or set EDITORHARNESS_API_KEY for this endpoint.", "Authorize the selected endpoint using browser consent.");
1402
+ const apiKey = process.env.EDITORBRAIN_API_KEY ?? process.env.EDITORHARNESS_API_KEY ?? storedKey ?? "";
1403
+ if (requireKey && !apiKey) throw new CliError("AUTH_REQUIRED", "Run editorbrain login or set EDITORBRAIN_API_KEY for this endpoint.", "Authorize the selected endpoint using browser consent.");
1203
1404
  return { url, apiKey };
1204
1405
  }
1205
1406
  async function secretFromStdin(label) {
@@ -1220,7 +1421,7 @@ async function init(args) {
1220
1421
  for (const path of Object.keys(files)) {
1221
1422
  const target = await checkedPath(root, path);
1222
1423
  try {
1223
- await lstat3(target);
1424
+ await lstat4(target);
1224
1425
  throw new Error(`Refusing to replace existing file: ${path}`);
1225
1426
  } catch (error) {
1226
1427
  if (error.code !== "ENOENT") throw error;
@@ -1232,7 +1433,7 @@ async function init(args) {
1232
1433
  for (const path of directories) {
1233
1434
  const target = await checkedPath(root, path, false);
1234
1435
  try {
1235
- if (!(await lstat3(target)).isDirectory()) throw new Error(`Not a directory: ${path}`);
1436
+ if (!(await lstat4(target)).isDirectory()) throw new Error(`Not a directory: ${path}`);
1236
1437
  } catch (error) {
1237
1438
  if (error.code !== "ENOENT") throw error;
1238
1439
  }
@@ -1241,7 +1442,47 @@ async function init(args) {
1241
1442
  for (const path of directories) await mkdir2(await checkedPath(root, path, false), { recursive: true });
1242
1443
  const guidance = await installGuidance();
1243
1444
  const entryPoints = guidance.readInstructions.filter((item) => item.entryPointStatus === "created").map((item) => item.entryPoint);
1244
- output({ root, created: Object.keys(files), entryPoints, guidance, next: `Edit brand tokens and brief, then run editorharness resolve ${project}` });
1445
+ output({ root, created: Object.keys(files), entryPoints, guidance, next: `Edit brand tokens and brief, then run editorbrain resolve ${project}` });
1446
+ }
1447
+ async function login(args, quiet = false) {
1448
+ const selected = await config(args, false);
1449
+ if (args.flags["key-stdin"] && args.flags["no-browser"]) throw new Error("Choose --key-stdin or --no-browser, not both.");
1450
+ if (args.flags["key-stdin"] || process.env.EDITORBRAIN_API_KEY && !args.flags["no-browser"]) {
1451
+ const apiKey = args.flags["key-stdin"] ? await secretFromStdin("API key") : process.env.EDITORBRAIN_API_KEY;
1452
+ const saved = { url: selected.url, apiKey };
1453
+ const me = await new Client(saved).me();
1454
+ await saveConfig(saved);
1455
+ if (!quiet) output({ authenticated: true, endpoint: saved.url, workspaceId: me.workspaceId });
1456
+ return;
1457
+ }
1458
+ const controller = new AbortController();
1459
+ const cancel = () => controller.abort();
1460
+ const terminate = () => {
1461
+ process.exitCode = 143;
1462
+ controller.abort();
1463
+ };
1464
+ process.once("SIGINT", cancel);
1465
+ process.once("SIGTERM", terminate);
1466
+ try {
1467
+ const authorization = await loginWithDevice({
1468
+ url: selected.url,
1469
+ noBrowser: !!args.flags["no-browser"],
1470
+ timeoutSeconds: str(args, "timeout") === void 0 ? void 0 : Number(str(args, "timeout")),
1471
+ signal: controller.signal,
1472
+ onChallenge: (challenge) => process.stderr.write(`Authorize this device in your browser:
1473
+ ${challenge.verificationUri}
1474
+ Code: ${challenge.userCode}
1475
+ Waiting for authorization. Press Ctrl+C to cancel.
1476
+ `),
1477
+ onBrowserUnavailable: () => process.stderr.write("The browser could not be opened. Use the URL and code above on any device.\n")
1478
+ });
1479
+ await saveConfig({ url: selected.url, apiKey: authorization.apiKey });
1480
+ if (!quiet) output({ authenticated: true, endpoint: selected.url, workspaceId: authorization.workspace.id, workspaceName: authorization.workspace.name, role: authorization.role, credentialStored: true });
1481
+ } finally {
1482
+ process.removeListener("SIGINT", cancel);
1483
+ process.removeListener("SIGTERM", terminate);
1484
+ }
1485
+ return;
1245
1486
  }
1246
1487
  async function main() {
1247
1488
  const args = parseArgs(process.argv.slice(2));
@@ -1278,46 +1519,13 @@ async function main() {
1278
1519
  output(await withWorkspaceLock(root2, () => installAgentGuidance(root2, agent)));
1279
1520
  return;
1280
1521
  }
1281
- if (command === "login") {
1282
- const selected = await config(args, false);
1283
- if (args.flags["key-stdin"] && args.flags["no-browser"]) throw new Error("Choose --key-stdin or --no-browser, not both.");
1284
- if (args.flags["key-stdin"] || process.env.EDITORHARNESS_API_KEY && !args.flags["no-browser"]) {
1285
- const apiKey = args.flags["key-stdin"] ? await secretFromStdin("API key") : process.env.EDITORHARNESS_API_KEY;
1286
- const saved = { url: selected.url, apiKey };
1287
- const me = await new Client(saved).me();
1288
- await saveConfig(saved);
1289
- output({ authenticated: true, endpoint: saved.url, workspaceId: me.workspaceId });
1290
- return;
1291
- }
1292
- const controller = new AbortController();
1293
- const cancel = () => controller.abort();
1294
- const terminate = () => {
1295
- process.exitCode = 143;
1296
- controller.abort();
1297
- };
1298
- process.once("SIGINT", cancel);
1299
- process.once("SIGTERM", terminate);
1300
- try {
1301
- const authorization = await loginWithDevice({
1302
- url: selected.url,
1303
- noBrowser: !!args.flags["no-browser"],
1304
- timeoutSeconds: str(args, "timeout") === void 0 ? void 0 : Number(str(args, "timeout")),
1305
- signal: controller.signal,
1306
- onChallenge: (challenge) => process.stderr.write(`Authorize this device in your browser:
1307
- ${challenge.verificationUri}
1308
- Code: ${challenge.userCode}
1309
- Waiting for authorization. Press Ctrl+C to cancel.
1310
- `),
1311
- onBrowserUnavailable: () => process.stderr.write("The browser could not be opened. Use the URL and code above on any device.\n")
1312
- });
1313
- await saveConfig({ url: selected.url, apiKey: authorization.apiKey });
1314
- output({ authenticated: true, endpoint: selected.url, workspaceId: authorization.workspace.id, workspaceName: authorization.workspace.name, role: authorization.role, credentialStored: true });
1315
- } finally {
1316
- process.removeListener("SIGINT", cancel);
1317
- process.removeListener("SIGTERM", terminate);
1318
- }
1522
+ if (command === "setup") {
1523
+ const result = await setup({ directory: str(args, "dir") ?? "./mis-videos", agent: parseAgentTarget(str(args, "agent")), workspaceId: str(args, "workspace"), skipMcp: !!args.flags["skip-mcp"], noBrowser: !!args.flags["no-browser"], getConfig: () => config(args, false), login: () => login(args, true) });
1524
+ output(result);
1525
+ if (result.status !== "ready") process.exitCode = 2;
1319
1526
  return;
1320
1527
  }
1528
+ if (command === "login") return login(args);
1321
1529
  if (command === "register") {
1322
1530
  const selected = await config(args, false);
1323
1531
  if (!args.flags["invite-stdin"]) throw new Error("Registration requires --invite-stdin (workspace invite provided by the service owner)");
@@ -1357,10 +1565,10 @@ Waiting for authorization. Press Ctrl+C to cancel.
1357
1565
  const destination = str(args, "out");
1358
1566
  if (destination) {
1359
1567
  if (command !== "direction" || !result.files) throw new Error("--out is supported only for direction draft.");
1360
- const outRoot = await ensureRoot(resolve3(str(args, "dir") ?? process.cwd(), destination), true);
1568
+ const outRoot = await ensureRoot(resolve4(str(args, "dir") ?? process.cwd(), destination), true);
1361
1569
  for (const path of Object.keys(result.files)) {
1362
1570
  try {
1363
- await lstat3(await checkedPath(outRoot, path, false));
1571
+ await lstat4(await checkedPath(outRoot, path, false));
1364
1572
  throw new Error(`Refusing to replace existing proposal: ${path}`);
1365
1573
  } catch (error) {
1366
1574
  if (error.code !== "ENOENT") throw error;
@@ -1410,7 +1618,7 @@ Waiting for authorization. Press Ctrl+C to cancel.
1410
1618
  return;
1411
1619
  }
1412
1620
  if (subcommand === "upload" && argument) {
1413
- const target = resolve3(str(args, "dir") ?? process.cwd(), argument);
1621
+ const target = resolve4(str(args, "dir") ?? process.cwd(), argument);
1414
1622
  const handle = await open4(target, constants4.O_RDONLY | constants4.O_NOFOLLOW);
1415
1623
  let bytes;
1416
1624
  try {
@@ -1432,7 +1640,7 @@ Waiting for authorization. Press Ctrl+C to cancel.
1432
1640
  }
1433
1641
  if (subcommand === "download" && argument && str(args, "out")) {
1434
1642
  if (!/^[a-f0-9]{64}$/.test(argument)) throw new Error("Asset ID must be its SHA-256");
1435
- const destination = resolve3(str(args, "dir") ?? process.cwd(), str(args, "out"));
1643
+ const destination = resolve4(str(args, "dir") ?? process.cwd(), str(args, "out"));
1436
1644
  const root2 = await ensureRoot(dirname2(destination), true);
1437
1645
  await checkedPath(root2, basename(destination), false);
1438
1646
  const response = await client.media(`/v1/assets/${argument}`);
@@ -1444,6 +1652,22 @@ Waiting for authorization. Press Ctrl+C to cancel.
1444
1652
  }
1445
1653
  throw new Error("Use assets list, assets upload <file>, or assets download <sha256> --out file");
1446
1654
  }
1655
+ if (command === "narrative") {
1656
+ const client = new Client(await config(args));
1657
+ const query = new URLSearchParams();
1658
+ if (subcommand === "search") {
1659
+ query.set("query", args.positional.slice(2).join(" "));
1660
+ for (const [flag, key] of [["kind", "kind"], ["channel", "channel"], ["epistemic-status", "epistemicStatus"], ["limit", "limit"]]) if (str(args, flag) !== void 0) query.set(key, str(args, flag));
1661
+ output(await client.request("/v1/narrative?" + query));
1662
+ return;
1663
+ }
1664
+ if (subcommand === "get" && argument) {
1665
+ for (const [flag, key] of [["sha256", "sha256"], ["event-offset", "eventOffset"], ["relation-offset", "relationOffset"], ["limit", "limit"]]) if (str(args, flag) !== void 0) query.set(key, str(args, flag));
1666
+ output(await client.request(`/v1/library/${encodeURIComponent(argument)}/narrative?${query}`));
1667
+ return;
1668
+ }
1669
+ throw new Error("Use narrative search [query] or narrative get <video-id>.");
1670
+ }
1447
1671
  if (command === "library") {
1448
1672
  const client = new Client(await config(args));
1449
1673
  if (subcommand === "search") {
@@ -1452,10 +1676,41 @@ Waiting for authorization. Press Ctrl+C to cancel.
1452
1676
  }
1453
1677
  if (subcommand === "get" && argument) {
1454
1678
  const document = str(args, "document");
1455
- output(await client.request(`/v1/library/${encodeURIComponent(argument)}${document ? `/documents?path=${encodeURIComponent(document)}` : ""}`));
1679
+ const hash = str(args, "sha256");
1680
+ if (hash && !document) throw new Error("--sha256 requires --document for library get.");
1681
+ const result = await client.request(`/v1/library/${encodeURIComponent(argument)}${document ? `/documents?${new URLSearchParams({ path: document, ...hash ? { sha256: hash } : {} })}` : ""}`);
1682
+ if (document && (typeof result.content !== "string" || await sha256(result.content) !== result.sha256 || hash && result.sha256 !== hash)) throw new CliError("HASH_MISMATCH", "Reference document verification failed.", "Do not use this evidence; retry the pinned version.");
1683
+ output(result);
1684
+ return;
1685
+ }
1686
+ if (subcommand === "media" && argument && str(args, "out")) {
1687
+ const hash = str(args, "sha256");
1688
+ if (!hash || !/^[a-f0-9]{64}$/.test(hash)) throw new Error("--sha256 must be a media SHA-256 from library get.");
1689
+ const destination = resolve4(str(args, "dir") ?? process.cwd(), str(args, "out"));
1690
+ const root2 = await ensureRoot(dirname2(destination), true);
1691
+ await checkedPath(root2, basename(destination), false);
1692
+ const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash}`);
1693
+ const reader = response.body?.getReader();
1694
+ if (!reader) throw new Error("Media body missing.");
1695
+ const chunks = [];
1696
+ let size = 0;
1697
+ for (; ; ) {
1698
+ const { done, value } = await reader.read();
1699
+ if (done) break;
1700
+ size += value.length;
1701
+ if (size > 90 * 1024 * 1024) {
1702
+ await reader.cancel();
1703
+ throw new CliError("MEDIA_TOO_LARGE", "Reference media exceeds the 90 MiB CLI limit.", "Select a smaller derivative from the reference inventory.");
1704
+ }
1705
+ chunks.push(value);
1706
+ }
1707
+ const bytes = Buffer.concat(chunks);
1708
+ if (await sha256(bytes) !== hash) throw new CliError("HASH_MISMATCH", "Reference media verification failed.", "Do not use this file as evidence.");
1709
+ await atomicWrite(root2, basename(destination), bytes, { document: false, overwrite: false });
1710
+ output({ videoId: argument, path: destination, sha256: hash, bytes: size, mimeType: response.headers.get("Content-Type"), reviewed: false });
1456
1711
  return;
1457
1712
  }
1458
- throw new Error("Use library search [query] or library get <video-id>");
1713
+ throw new Error("Use library search, library get, or library media <video-id> --sha256 hash --out file.");
1459
1714
  }
1460
1715
  if (!["validate", "resolve", "export", "push", "pull"].includes(command)) throw new Error(`Unknown command: ${command}`);
1461
1716
  const root = await ensureRoot(str(args, "dir") ?? process.cwd(), command === "pull" && !args.flags["dry-run"]);
@@ -1487,7 +1742,7 @@ Waiting for authorization. Press Ctrl+C to cancel.
1487
1742
  const adapter = str(args, "adapter") ?? "neutral";
1488
1743
  if (!["neutral", "hyperframes", "remotion"].includes(adapter)) throw new Error("Adapter must be neutral, hyperframes or remotion");
1489
1744
  const generated = exportProject(resolved, adapter);
1490
- const destination = resolve3(root, str(args, "out") ?? `videos/${project}/plans/${adapter}`);
1745
+ const destination = resolve4(root, str(args, "out") ?? `videos/${project}/plans/${adapter}`);
1491
1746
  const outRoot = await ensureRoot(destination, true);
1492
1747
  for (const [path, content] of Object.entries(generated)) await atomicWrite(outRoot, path, content, { document: false });
1493
1748
  output({ adapter, kind: "editorial_handoff", rendered: false, directory: outRoot, files: Object.keys(generated), warnings: resolved.warnings });
package/package.json CHANGED
@@ -1,12 +1,11 @@
1
1
  {
2
2
  "name": "editorbrain",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "EditorBrain editorial knowledge, portable workspaces and skills for AI video agents",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
7
7
  "bin": {
8
- "editorbrain": "bin/editorharness.mjs",
9
- "editorharness": "bin/editorharness.mjs"
8
+ "editorbrain": "bin/editorbrain.mjs"
10
9
  },
11
10
  "files": [
12
11
  "bin",
@@ -1,11 +1,11 @@
1
1
  ---
2
- name: editorharness
3
- description: Use EditorBrain (formerly Editor Harness) to edit a user's video, adapt an editorial style, find reference evidence, or manage brand and video project context through its CLI or MCP. Connect the project's actual footage, script and brand to editing decisions, then implement and review the result with the available editing tools. Also use when the user names EditorBrain or Editor Harness, requests its library or asks to follow a saved preset.
2
+ name: editorbrain
3
+ description: Use EditorBrain to edit a user's video, adapt an editorial style, find reference evidence, or manage brand and video project context through its CLI or MCP. Connect the project's actual footage, script and brand to editing decisions, then implement and review the result with the available editing tools. Also use when the user names EditorBrain, requests its library or asks to follow a saved preset.
4
4
  ---
5
5
 
6
6
  # EditorBrain
7
7
 
8
- The public product is EditorBrain. The compatible CLI command, skill name and folder paths remain `editorharness`; do not invent an `editorbrain` command. Web: https://editorbrain.com. API/MCP: https://api.editorbrain.com/mcp.
8
+ The public product is EditorBrain. The npm package is `editorbrain`; `editorbrain` is the CLI command. Skill name and portable folder paths use `editorbrain`. Web: https://editorbrain.com. API/MCP: https://api.editorbrain.com/mcp.
9
9
 
10
10
  Convert reference evidence into an appropriate edit for this project. Reading the library starts the work; quality is demonstrated in the delivered video.
11
11
 
@@ -1,6 +1,6 @@
1
1
  # CLI and MCP: read, retrieve, save
2
2
 
3
- Use the connected MCP schema and `editorharness help` to confirm the installed contract. Examples below describe the 0.5.0 customer workflow; older installations may lack the skill installer or reference-media tool. Do not invent commands from historical architecture documents.
3
+ Use the connected MCP schema and `editorbrain help` to confirm the installed contract. Examples below describe the 0.6.0 customer workflow; older installations may lack the skill installer or reference-media tool. Do not invent commands from historical architecture documents.
4
4
 
5
5
  API/MCP: `https://api.editorbrain.com/mcp`. The host must connect this server separately; installing a skill does not register or authorize MCP.
6
6
 
@@ -9,18 +9,18 @@ API/MCP: `https://api.editorbrain.com/mcp`. The host must connect this server se
9
9
  An existing account normally starts with:
10
10
 
11
11
  ```sh
12
- editorharness status
13
- editorharness pull --dir ./my-videos
14
- editorharness skill install --dir ./my-videos --agent both
12
+ editorbrain status
13
+ editorbrain pull --dir ./my-videos
14
+ editorbrain skill install --dir ./my-videos --agent both
15
15
  ```
16
16
 
17
- If unauthenticated, `editorharness login --url https://api.editorbrain.com` uses browser/device consent. Request the user's participation only for this required login step. Credentials stay outside project files. CLI login does not automatically authenticate a separate MCP host: that host needs the configured workspace bearer credential through its secret mechanism.
17
+ If unauthenticated, `editorbrain login --url https://api.editorbrain.com` uses browser/device consent. Request the user's participation only for this required login step. Credentials stay outside project files. CLI login does not automatically authenticate a separate MCP host: register the MCP URL without a bearer header and authorize through the host’s OAuth login. Choose the same workspace in the consent page. Existing bearer-key connections remain compatible; do not overwrite one during setup.
18
18
 
19
- Skill installation is offline and independent of login. It creates `.agents/skills/editorharness/` for Codex and `.claude/skills/editorharness/` for Claude. Open the target folder in the agent and explicitly ask it to read the installed `SKILL.md` if automatic discovery has not refreshed. The skill directs the agent to its bundled `AGENTS.md`; a bundled file alone is not assumed to load automatically.
19
+ Skill installation is offline and independent of login. It creates `.agents/skills/editorbrain/` for Codex and `.claude/skills/editorbrain/` for Claude. Open the target folder in the agent and explicitly ask it to read the installed `SKILL.md` if automatic discovery has not refreshed. The skill directs the agent to its bundled `AGENTS.md`; a bundled file alone is not assumed to load automatically.
20
20
 
21
21
  Existing root `AGENTS.md`/`CLAUDE.md` are preserved. Read the install result's instruction paths and conflict reports. A preserved root guide does not mean the native skill failed; a conflicting existing skill needs a deliberate merge, not an overwrite. Do not replace the user's custom instructions to finish setup.
22
22
 
23
- For a separate local workspace, `editorharness init --dir ./new-video --brand <id> --style <id> --project <id>` creates portable context and installs guidance. Do not initialize over a pulled workspace to reset it. `pull` and `push` synchronize documents, not the installed native skill folders or local render media.
23
+ For a separate local workspace, `editorbrain init --dir ./new-video --brand <id> --style <id> --project <id>` creates portable context and installs guidance. Do not initialize over a pulled workspace to reset it. `pull` and `push` synchronize documents, not the installed native skill folders or local render media.
24
24
 
25
25
  ## Reading the project
26
26
 
@@ -34,13 +34,13 @@ MCP sequence:
34
34
  Use the local files after a successful `pull` when working through CLI. Commands:
35
35
 
36
36
  ```sh
37
- editorharness validate --dir ./my-videos
38
- editorharness resolve <project-id> --dir ./my-videos
39
- editorharness assets list --limit 200
40
- editorharness assets download <sha256> --out ./media/clip.mp4
37
+ editorbrain validate --dir ./my-videos
38
+ editorbrain resolve <project-id> --dir ./my-videos
39
+ editorbrain assets list --limit 200
40
+ editorbrain assets download <sha256> --out ./media/clip.mp4
41
41
  ```
42
42
 
43
- `assets list` returns `nextCursor`; continue with `--cursor` when needed. MCP `list_assets({})` returns the newest 100 assets, not necessarily the full collection. Project `media.json` is the primary source for project-specific IDs. Asset tags passed to recommendations describe declared resources, not tool-verified contents.
43
+ `assets list` returns `nextCursor`; continue with `--cursor` when needed. MCP `list_assets` also returns `nextCursor`; pass it as `cursor` to retrieve the next page (default 100, maximum 1000). Project `media.json` is the primary source for project-specific IDs. Asset tags passed to recommendations describe declared resources, not tool-verified contents.
44
44
 
45
45
  ## Selecting a method and examining examples
46
46
 
@@ -58,16 +58,16 @@ Discover current argument schemas before calling:
58
58
  CLI counterparts for discovery/documents:
59
59
 
60
60
  ```sh
61
- editorharness styles list
62
- editorharness styles recommend <project-id> --dir ./my-videos
63
- editorharness library search "comparison"
64
- editorharness library get <video-id>
65
- editorharness library get <video-id> --document <returned-path>
61
+ editorbrain styles list
62
+ editorbrain styles recommend <project-id> --dir ./my-videos
63
+ editorbrain library search "comparison"
64
+ editorbrain library get <video-id>
65
+ editorbrain library get <video-id> --document <returned-path>
66
66
  ```
67
67
 
68
68
  Recommendations and direction drafts use the saved remote project, require a non-empty script and check that local source context matches it. After `init` or local edits, validate and successfully `push` the intended project context before those calls. Do not discard unsynced local changes to silence a context mismatch. An offline draft can be written by the agent from available evidence without claiming a remote recommendation ran.
69
69
 
70
- The current CLI document command retrieves the latest version; it does not expose a hash pin. For exact historical retrieval use the MCP `sha256` argument, or the authenticated reference-document REST route with its `sha256` query parameter. Do not label an unpinned read as pinned. Keep the actual returned hash in the production record.
70
+ Pin historical evidence with `editorbrain library get <video-id> --document <path> --sha256 <source-hash>`, or MCP `read_reference_document` with `sha256`. CLI checks the returned content hash. Without a pin, the latest version is retrieved; keep the returned hash.
71
71
 
72
72
  ### Complete enough evidence
73
73
 
@@ -88,8 +88,8 @@ Access is scoped to the current workspace's reference grant and credential. A kn
88
88
  `draft_direction` proposes an initial method and techniques. Inspect its pending requirements and transfer status, complete the per-beat decisions using evidence and the actual material, then implement the user's requested output. Available CLI:
89
89
 
90
90
  ```sh
91
- editorharness direction draft <project-id> --dir ./my-videos --out ./direction-draft
92
- editorharness export <project-id> --dir ./my-videos --adapter neutral --out ./handoff
91
+ editorbrain direction draft <project-id> --dir ./my-videos --out ./direction-draft
92
+ editorbrain export <project-id> --dir ./my-videos --adapter neutral --out ./handoff
93
93
  ```
94
94
 
95
95
  `export_project({projectId,adapter})` supports `neutral`, `hyperframes` and `remotion`. It returns plans for an external rendering agent/engine; it does not create a video. Inspect the engine's real capabilities before committing to an effect.
@@ -97,20 +97,30 @@ editorharness export <project-id> --dir ./my-videos --adapter neutral --out ./ha
97
97
  Save through local portable documents plus `push`, or MCP `write_document` with the revision returned by the last read and the actual schema. To create a new document, use `expectedRevision: 0`; to update an existing one, use its current read revision. Do not guess a revision or force over a conflict; reread, reconcile and retry only if still authorized. Keep generated production notes small enough for the document limit (128 KiB per document); do not duplicate every raw catalog response into a customer workspace.
98
98
 
99
99
  ```sh
100
- editorharness validate --dir ./my-videos
101
- editorharness resolve <project-id> --dir ./my-videos
102
- editorharness push --dir ./my-videos
100
+ editorbrain validate --dir ./my-videos
101
+ editorbrain resolve <project-id> --dir ./my-videos
102
+ editorbrain push --dir ./my-videos
103
103
  ```
104
104
 
105
105
  `push` is not a media upload. Use `assets upload <file>` for authorized production files within current limits and then record returned IDs/hashes. Keep large renders/evidence in the appropriate media store, with permanent identifiers in the project. Preserve old revisions and disclose unsynchronized local work if saving fails.
106
106
 
107
107
 
108
- ## Recovery and diagnostics (CLI 0.5.0)
108
+ ## Recovery and diagnostics (CLI 0.6.0)
109
109
 
110
110
  Use `editorbrain version` to discover the installed release. Run `editorbrain doctor --dir <folder> --agent codex|claude|both` before troubleshooting; `--offline` deliberately skips credentials and remote checks. Doctor is read-only. Its `mcpClient: not_verified` is not a claim that the host is connected. A customized skill is reported as a warning, not replaced automatically.
111
111
 
112
112
  Before reconciling sync problems, use `push --dry-run` or `pull --dry-run`. Read `conflicts` and the planned paths. A preview neither writes nor reserves revisions. Never use a separate workspace to evade a binding mismatch.
113
113
 
114
- Errors include `code`, `hint`, `retryable` and the legacy text `error`. `AUTH_REQUIRED` needs user authorization, `ACCESS_DENIED` needs the right permission, `SYNC_CONFLICT` needs reconciliation, and `WORKSPACE_MISMATCH` requires the correct separate folder. `WORKSPACE_BUSY` means another CLI operation owns `.editorharness-operation.lock`; do not auto-delete it. After a crash, verify no process is using the folder before removing a leftover lock.
114
+ Errors include `code`, `hint`, `retryable` and the legacy text `error`. `AUTH_REQUIRED` needs user authorization, `ACCESS_DENIED` needs the right permission, `SYNC_CONFLICT` needs reconciliation, and `WORKSPACE_MISMATCH` requires the correct separate folder. `WORKSPACE_BUSY` means another CLI operation owns `.editorbrain-operation.lock`; do not auto-delete it. After a crash, verify no process is using the folder before removing a leftover lock.
115
115
 
116
116
  GET requests use bounded retries and respect Retry-After. Writes are not retried automatically: after a network error, inspect remote state before repeating them. Do not treat `retryable` as permission for an unbounded loop. HTTP error bodies are not printed. The MCP now provides matching structuredContent and text; consume either without counting them as separate results. Writing a document is declared mutating and may update existing content even though revision history is preserved.
117
+
118
+ ## Guided setup and OAuth (0.6.0)
119
+
120
+ `editorbrain setup --dir ./mis-videos --agent codex --workspace <expected-id>` authorizes the CLI when necessary, pulls documents, installs the complete skill and registers an absent MCP connection. Use `claude` or `both` for other hosts. The expected ID is a check, never authorization. Setup preserves existing MCP entries and customized guidance. Exit 2 means action is still required; inspect each step instead of repeating blindly. `--no-browser` defers MCP registration; `--skip-mcp` prepares only the CLI/skill.
121
+
122
+ Codex can use `codex mcp login editorbrain`; Claude Code completes OAuth from `/mcp`. Native host configuration is not proof of an authenticated MCP. Call `workspace_info` inside the host and compare it with CLI `status`. A read-only consent cannot save documents: ask for editing scope only when needed. Revoke OAuth connections from the app’s connection settings. CLI device credentials and MCP OAuth connections are separate.
123
+
124
+ `editorbrain narrative search [query] --kind hook --channel visual` finds candidates. `narrative get <video-id> --sha256 <document-hash> --event-offset 0 --relation-offset 0 --limit 50` pages through one pinned narrative document; follow returned offsets. Missing narrative coverage stays explicit.
125
+
126
+ `editorbrain library media <video-id> --sha256 <media-hash> --out <new-file>` downloads an authorized frame/audio/video and verifies its hash (90 MiB maximum). It will not overwrite an existing file. Downloading is not reviewing: inspect it with available visual/audio tools and record the intervals actually checked. Neither CLI nor MCP ingest customer references.
@@ -1,17 +1,17 @@
1
1
  # EditorBrain workspace files
2
2
 
3
- Use this reference when creating a project, changing branding or styles, resolving conflicting settings, or deciding where to save feedback. Technical paths and the CLI remain named `editorharness`; the public product is EditorBrain.
3
+ Use this reference when creating a project, changing branding or styles, resolving conflicting settings, or deciding where to save feedback. Technical paths and the CLI remain named `editorbrain`; the public product is EditorBrain.
4
4
 
5
5
  ## Discover before editing
6
6
 
7
- Read `videos/<project-id>/project.json` first: its `brand`, `style` and `outputProfile` fields select the context. Discover IDs using the returned documents or local files. Folder names below are placeholders, not literal IDs. For a new local workspace use `editorharness init`; for an existing account use `pull`. Read the generated documents before changing their schema.
7
+ Read `videos/<project-id>/project.json` first: its `brand`, `style` and `outputProfile` fields select the context. Discover IDs using the returned documents or local files. Folder names below are placeholders, not literal IDs. For a new local workspace use `editorbrain init`; for an existing account use `pull`. Read the generated documents before changing their schema.
8
8
 
9
9
  ```text
10
10
  AGENTS.md Codex entry point (existing instructions preserved)
11
11
  CLAUDE.md Claude Code entry point (existing instructions preserved)
12
- .agents/skills/editorharness/ Codex skill, contract and references
13
- .claude/skills/editorharness/ Claude Code skill, contract and references
14
- .editorharness/
12
+ .agents/skills/editorbrain/ Codex skill, contract and references
13
+ .claude/skills/editorbrain/ Claude Code skill, contract and references
14
+ .editorbrain/
15
15
  brands/<brand-id>/
16
16
  brand.md Identity, audience, constraints
17
17
  design.md Composition and visual treatment (optional)
@@ -38,7 +38,7 @@ videos/<project-id>/
38
38
  reviews/ Reviews tied to a particular delivered version
39
39
  ```
40
40
 
41
- The native skill folders are local instructions, not portable documents synchronized by `push`. Local media/render folders are not media uploads. `.editorharness/.sync.json` is CLI-managed sync state; do not edit it to bypass conflicts. An older valid workspace may omit the optional files and local production directories.
41
+ The native skill folders are local instructions, not portable documents synchronized by `push`. Local media/render folders are not media uploads. `.editorbrain/.sync.json` is CLI-managed sync state; do not edit it to bypass conflicts. An older valid workspace may omit the optional files and local production directories.
42
42
 
43
43
  The resolver requires the selected brand's `brand.md`, `tokens.json`, `language.json`, `assets.json`; the selected style's `style.md`, `style.json`, `examples.json`; the selected output profile; and the project's `project.json`, `brief.md`, `direction.md`. Preserve them even when a declaration is empty. Additional guidance such as `adaptation-rules.json`, library indexes or memory may be present: read it explicitly when relevant. It is not automatically included in `resolve` merely because it exists.
44
44
 
@@ -76,6 +76,6 @@ Save reusable feedback at its stated scope: project-only changes in the project,
76
76
 
77
77
  ## Updating the installed skill
78
78
 
79
- Updating the global CLI does not replace skills already copied into a project. Run `editorharness skill install --dir <workspace> --agent both` and inspect `conflicts`, `preserved`, `warnings` and `readInstructions`.
79
+ Updating the global CLI does not replace skills already copied into a project. Run `editorbrain skill install --dir <workspace> --agent both` and inspect `conflicts`, `preserved`, `warnings` and `readInstructions`.
80
80
 
81
81
  If skill files differ, the installer keeps them. Prepare the new version in a separate temporary directory, compare it with the project's installed copy, and merge changes while preserving custom instructions. Do not assume a successful exit means all guidance was upgraded. Root `AGENTS.md`/`CLAUDE.md` remain user-owned: if already present, use the returned skill path explicitly, or add a narrowly scoped pointer when the user asks to integrate it. There is no automatic global installation for every future project.
File without changes