From 1f95250e874832a1602cca7249626c49052dafdb Mon Sep 17 00:00:00 2001 From: pitfa19 <166558275+pitfa19@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:48:11 +0100 Subject: [PATCH 01/10] Add mozak scope move: copy a scope into a vault folder and point its entry there Why: 0.6.0 makes mozak vault-only (spec step 2). Scopes outside a vault and repo scopes need one owner route that moves their plan files into a vault without hand edits to mozak.json or the inventory. What: - core scope-move.ts: moveScope copies mozak.json, mozak.md (or the pre-0.4 names), mozak.annotations.json, README.md and AGENTS.md through flushed temp files, verifies every copy byte for byte, then rewrites only that inventory entry to { id, root } (other keys such as focus and x kept, every other entry untouched) under the inventory lock with the same validated atomic write as focus. It refuses a target outside a vault (no .obsidian at or above it), a target that holds mozak files or any file it would write, another scope's root and a source that fails check. Works on local entries, legacy vault-plans entries (in place: entry only) and repo-cache entries. The old files stay. A failure before the inventory rename removes the copies and folders it made. A change to the source under the scope lock stops it with stale-input. Idempotent. --dry-run writes nothing. --drop removes a 0-plan entry (spec step 11 names this form). A pinned spec left behind is a spec-not-moved warning. - core inventory-file.ts: the inventory lock, JSON style and validated write, shared by focus and scope move (focus behaviour unchanged). - vault-config.ts: vaultOf, the one place the vault rule lives. - CLI: mozak scope move --scope ID (--to PATH | --drop) --owner-ref --owner-message-at --reason [--dry-run] [--json]. Owner route, not in MCP. Proof: scope-move.test.ts and scope-move-cli.test.ts failed first (missing module, unknown route) and pass: local scope, vault-plans entry, repo-cache entry, refused targets, failure halfway through (two injected phases), stale source, plans and receipts byte-identical, drop. npm test 646 of 646 under default TMPDIR, /tmp and a realpath folder, test:install 73 + 1 skipped. ub-mode: CRAP planMove 8.0, moveScope 7.1, assertTargetFree 7.0, parseMoveArgs 6.0, renderMove 6.0, copyVerified 6.0, others under 5. dryer: no candidates. mutator scope-move.ts + inventory-file.ts: 62 of 62 killed (dead fallbacks it found were removed). --- packages/cli/src/index.ts | 22 +- packages/cli/test/scope-move-cli.test.ts | 72 ++++++ packages/core/src/focus.ts | 41 +--- packages/core/src/index.ts | 2 + packages/core/src/inventory-file.ts | 47 ++++ packages/core/src/scope-index.ts | 2 +- packages/core/src/scope-move.ts | 280 +++++++++++++++++++++++ packages/core/src/vault-config.ts | 14 +- packages/core/test/scope-move.test.ts | 260 +++++++++++++++++++++ 9 files changed, 702 insertions(+), 38 deletions(-) create mode 100644 packages/cli/test/scope-move-cli.test.ts create mode 100644 packages/core/src/inventory-file.ts create mode 100644 packages/core/src/scope-move.ts create mode 100644 packages/core/test/scope-move.test.ts diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 215e97b..3c3bcfd 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -5,7 +5,7 @@ import { closeSync, fstatSync, openSync, readSync } from "node:fs"; import { parseArgs } from "node:util"; -import { decideWithFlags, deleteWithFlags, observePayload, observeWithFlags, planShow, executeOperation, loadInventory, MAX_REQUEST_BYTES, scopeForWorkingCopy, gitCommitScope, DomainError, focusChange, focusList, renderFocus, type OperationOutput, type ScopeInventory } from "@mozak/core"; +import { decideWithFlags, deleteWithFlags, observePayload, observeWithFlags, planShow, executeOperation, loadInventory, MAX_REQUEST_BYTES, scopeForWorkingCopy, gitCommitScope, DomainError, focusChange, focusList, renderFocus, renderMove, scopeMoveOutput, type OperationOutput, type ScopeInventory } from "@mozak/core"; import { runningVersion, upgrade } from "./upgrade.js"; import { doctor, renderDoctor } from "./doctor.js"; @@ -62,6 +62,7 @@ const ROUTES: Record = { "focus list": { operation: "focus-list", flags: ["config", "scope", "json"], requires: ["config"], requestFile: false }, "focus add": { operation: "focus-add", flags: ["config", "scope", "plan", "json"], requires: ["config", "scope", "plan"], requestFile: false }, "focus remove": { operation: "focus-remove", flags: ["config", "scope", "plan", "json"], requires: ["config", "scope", "plan"], requestFile: false }, + "scope move": { operation: "scope-move", flags: ["config", "scope", "to", "drop", "dry-run", "owner-ref", "owner-message-at", "reason", "json"], requires: ["config", "scope", "owner-ref", "owner-message-at", "reason"], requestFile: false }, observe: { operation: "observe", flags: ["config", "scope", "request", ...OBSERVE_FLAGS], requires: ["config", "scope"], requestFile: true }, "review decide": { operation: "decide", flags: ["config", "scope", "request", ...DECIDE_FLAGS], requires: ["config", "scope"], requestFile: true }, "plan prune": { operation: "prune", flags: ["config", "scope", "rejected", "request"], requires: ["config", "scope", "rejected", "request"], requestFile: true }, @@ -77,7 +78,7 @@ const ROUTES: Record = { }; const ROUTE_NAMES = Object.keys(ROUTES); -const BOOLEAN_FLAGS = new Set(["json", "include-rejected", "all", "write", "brief", "dry-run", "allow-completed", "commit", "rejected", "local", "print", "include-private"]); +const BOOLEAN_FLAGS = new Set(["json", "include-rejected", "all", "write", "brief", "dry-run", "allow-completed", "commit", "rejected", "local", "print", "include-private", "drop"]); class UsageError extends Error {} @@ -86,6 +87,9 @@ function usage(): string { "usage: mozak [--config FILE] [--config FILE] [flags]", " mozak scope init --scope ID --request FILE (owner)", " mozak scope retitle --scope ID --request FILE (owner; change the scope's display title)", + " mozak scope move --scope ID (--to PATH | --drop) --owner-ref REF --owner-message-at ISO --reason TEXT [--dry-run] [--json]", + " (owner; copy the scope's files into a vault folder, verify them,", + " point its inventory entry there; old files stay. --drop: 0-plan entry only)", " mozak context [--scope ID] [--brief] [--plan ID] [--json]", " mozak plans [--scope ID | --all] [--include-rejected] [--limit 1..100] [--sort deadline] [--continuation TOKEN] [--json]", " mozak graph (--scope ID | --all) [--json] (cross-plan refs from owner annotations, with resolution)", @@ -454,6 +458,19 @@ function focusRoute(configPath: string, inventory: ScopeInventory, operation: st return out.exitCode; } +/** + * `mozak scope move`: an owner route on the inventory file, like focus, so it calls core's moveScope directly instead of + * the scope operation facade. MCP never exposes it. + */ +function moveRoute(configPath: string, values: Record): number { + const out = scopeMoveOutput(configPath, { + scope: values.scope, ...(values.to !== undefined ? { to: values.to } : {}), ...(values.drop ? { drop: true } : {}), ...(values["dry-run"] ? { dryRun: true } : {}), + ownerRef: values["owner-ref"], ownerMessageAt: values["owner-message-at"], reason: values.reason, + }); + process.stdout.write(values.json === true ? `${JSON.stringify(out.data, null, 2)}\n` : renderMove(out.data)); + return out.exitCode; +} + /** upgrade and doctor work on the installation, not on scopes, so they have their own flags and no --config rule. */ function maintenance(name: "upgrade" | "doctor", argv: string[]): number { let values: Record; @@ -535,6 +552,7 @@ function run(argv: string[]): number { const cwdScope = CWD_SCOPE_ROUTES.has(routeName) && values.scope === undefined && values.all === undefined && values.continuation === undefined; if (route.operation.startsWith("focus-")) return focusRoute(configPath, inventory, route.operation, values); + if (route.operation === "scope-move") return moveRoute(configPath, values); if (cwdScope) { try { values.scope = scopeForWorkingCopy(inventory, process.cwd()).id; diff --git a/packages/cli/test/scope-move-cli.test.ts b/packages/cli/test/scope-move-cli.test.ts new file mode 100644 index 0000000..e4e3fc9 --- /dev/null +++ b/packages/cli/test/scope-move-cli.test.ts @@ -0,0 +1,72 @@ +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { cleanup, world } from "../../core/test/annotations-fixture.ts"; + +// Real CLI subprocess runs of `mozak scope move` against synthetic temp scopes and a scratch inventory only. +const cliPath = resolve(fileURLToPath(new URL(".", import.meta.url)), "..", "dist", "index.js"); +after(cleanup); + +function cli(args: string[]) { + if (!existsSync(cliPath)) throw new Error(`built CLI missing at ${cliPath}; run "npm run build" first`); + const r = spawnSync(process.execPath, ["--no-warnings", cliPath, ...args], { encoding: "utf8", timeout: 30000 }); + return { code: r.status ?? -1, out: r.stdout, err: r.stderr }; +} +const OWNER = ["--owner-ref", "synthetic:owner", "--owner-message-at", "2026-11-01T17:25:00.000Z", "--reason", "Synthetic move"]; + +/** alpha lives outside any vault; base/vault is a vault (it has a .obsidian folder). */ +function setup() { + const w = world(["alpha"]); + w.propose("alpha", "a1"); + mkdirSync(join(w.base, "vault", ".obsidian"), { recursive: true }); + return w; +} + +test("CLI: scope move --dry-run shows files and the new entry; the real run moves; the rerun changes nothing", () => { + const w = setup(); + const text = readFileSync(w.config, "utf8"); + const dry = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--to", "vault/alpha", "--dry-run", ...OWNER]); + assert.equal(dry.code, 0, dry.out + dry.err); + assert.match(dry.out, /status: dry-run \(nothing written\)/); + assert.match(dry.out, /copy mozak\.json/); + assert.match(dry.out, /new entry: \{"id":"alpha","root":"vault\/alpha"\}/); + assert.equal(readFileSync(w.config, "utf8"), text); + const real = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--to", "vault/alpha", "--json", ...OWNER]); + assert.equal(real.code, 0, real.out + real.err); + assert.equal(JSON.parse(real.out).status, "ok"); + assert.deepEqual(JSON.parse(readFileSync(w.config, "utf8")).scopes, [{ id: "alpha", root: "vault/alpha" }]); + assert.ok(readFileSync(join(w.base, "vault", "alpha", "mozak.json")).equals(readFileSync(join(w.base, "alpha", "mozak.json")))); + const again = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--to", "vault/alpha", ...OWNER]); + assert.equal(again.code, 0, again.out); + assert.match(again.out, /already done/); +}); + +test("CLI: scope move needs the owner flags and exactly one of --to or --drop, and refuses a target outside a vault", () => { + const w = setup(); + const missing = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--to", "vault/alpha"]); + assert.equal(missing.code, 2); + assert.match(missing.err, /missing --owner-ref/); + const outside = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--to", "elsewhere", ...OWNER]); + assert.equal(outside.code, 2); + assert.equal(JSON.parse(outside.out).status, "move-target-outside-vault"); + const both = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--to", "vault/x", "--drop", ...OWNER]); + assert.equal(both.code, 2); + // The route is listed in help. + assert.match(cli(["--help"]).out, /mozak scope move --scope ID/); +}); + +test("CLI: scope move --drop removes a 0-plan entry and refuses a scope with plans", () => { + const w = world(["alpha", "empty"]); + w.propose("alpha", "a1"); + const r = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--drop", ...OWNER]); + assert.equal(r.code, 2); + assert.equal(JSON.parse(r.out).status, "drop-refused-has-plans"); + const ok = cli(["scope", "move", "--config", w.config, "--scope", "empty", "--drop", ...OWNER]); + assert.equal(ok.code, 0, ok.out + ok.err); + assert.match(ok.out, /drop empty: remove its inventory entry/); + assert.deepEqual(JSON.parse(readFileSync(w.config, "utf8")).scopes.map((s: { id: string }) => s.id), ["alpha"]); + assert.ok(existsSync(join(w.base, "empty", "mozak.json"))); +}); diff --git a/packages/core/src/focus.ts b/packages/core/src/focus.ts index 1098670..50202cf 100644 --- a/packages/core/src/focus.ts +++ b/packages/core/src/focus.ts @@ -2,16 +2,15 @@ // A sidebar marker only. It is not plan state: mozak.json and mozak.md never change, and the inventory digest // (format plus sorted id and root) ignores it. Only owner routes write it (`mozak focus add|remove`, the plugin star). -import { readFileSync, rmSync } from "node:fs"; -import { dirname, join } from "node:path"; +import { readFileSync } from "node:fs"; import { DomainError } from "./errors.ts"; -import { acquireDirLock, type LockOptions } from "./dir-lock.ts"; -import { replaceFileDurable } from "./durable.ts"; +import type { LockOptions } from "./dir-lock.ts"; +import { inventoryText, withInventoryLock, writeInventoryValidated } from "./inventory-file.ts"; import { loadInventory, resolveScope, type ScopeInventory } from "./scope-index.ts"; import { readScope } from "./scope-store.ts"; import type { OperationOutput } from "./api.ts"; -export const INVENTORY_LOCK_DIR = ".mozak-inventory-lock"; +export { INVENTORY_LOCK_DIR, jsonStyle } from "./inventory-file.ts"; export type FocusAction = "add" | "remove"; export interface FocusChange { scope: string; plan: string; action: FocusAction } @@ -72,12 +71,6 @@ export function nextFocus(current: readonly string[], plan: string, action: Focu return current.includes(plan) ? current.filter((id) => id !== plan) : null; } -/** The file's own indent (spaces or a tab) and whether it ends with a newline, so a rewrite keeps its style. */ -export function jsonStyle(text: string): { indent: string; newline: boolean } { - const m = /\n([ \t]+)\S/.exec(text); - return { indent: m ? m[1]! : " ", newline: text.endsWith("\n") }; -} - function assertPlan(inv: ScopeInventory, scope: string, plan: string): void { const state = readScope(resolveScope(inv, scope)).state; if (!state.plans.some((p) => p.id === plan)) { @@ -92,8 +85,7 @@ function assertPlan(inv: ScopeInventory, scope: string, plan: string): void { */ export function setFocus(inventoryPath: string, change: FocusChange, options: LockOptions = {}): FocusResult { if (change.action !== "add" && change.action !== "remove") throw new DomainError("invalid-input", `focus action must be add or remove, not "${String(change.action)}"`, 2); - const release = acquireDirLock(join(dirname(inventoryPath), INVENTORY_LOCK_DIR), "inventory", options); - try { + return withInventoryLock(inventoryPath, () => { const text = readFileSync(inventoryPath, "utf8"); const inv = loadInventory(inventoryPath); if (!inv.scopes.some((s) => s.id === change.scope)) { @@ -105,26 +97,7 @@ export function setFocus(inventoryPath: string, change: FocusChange, options: Lo const next = nextFocus(entry.focus ?? [], change.plan, change.action); if (next === null) return { scope: change.scope, focus: [...(entry.focus ?? [])], changed: false }; entry.focus = next; - const style = jsonStyle(text); - const bytes = JSON.stringify(doc, null, style.indent) + (style.newline ? "\n" : ""); - writeValidated(inventoryPath, bytes); + writeInventoryValidated(inventoryPath, inventoryText(doc, text)); return { scope: change.scope, focus: next, changed: true }; - } finally { - release(); - } -} - -/** - * Replace the inventory with `bytes`: the temp file next to it is flushed and loaded with the normal inventory loader - * (same folder, so relative roots resolve the same) before the rename. On any failure the temp file is removed and the - * old inventory stays as it was. - */ -function writeValidated(inventoryPath: string, bytes: string): void { - let temporary: string | null = null; - try { - replaceFileDurable(inventoryPath, bytes, (t) => { temporary = t; }, () => { loadInventory(temporary!); }); - } catch (e) { - if (temporary !== null) rmSync(temporary, { force: true }); - throw e; - } + }, options); } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 6b3b3fa..aee06fd 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -13,6 +13,8 @@ export * from "./scope-list.ts"; export * from "./review.ts"; export * from "./delete.ts"; export * from "./focus.ts"; +export * from "./inventory-file.ts"; +export * from "./scope-move.ts"; export * from "./roadmap.ts"; export { mdText, stopLabel, completedPlanLine, planHeading, planDisplayState, progressStrip, type PlanDisplayState } from "./bridge.ts"; export * from "./api.ts"; diff --git a/packages/core/src/inventory-file.ts b/packages/core/src/inventory-file.ts new file mode 100644 index 0000000..579942a --- /dev/null +++ b/packages/core/src/inventory-file.ts @@ -0,0 +1,47 @@ +// Shared pieces for owner routes that rewrite mozak-inventory.json (focus, scope move, scope link): the inventory +// lock, the file's own JSON style, and a validated atomic replace. + +import { rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { acquireDirLock, type LockOptions } from "./dir-lock.ts"; +import { replaceFileDurable } from "./durable.ts"; +import { loadInventory } from "./scope-index.ts"; + +export const INVENTORY_LOCK_DIR = ".mozak-inventory-lock"; + +/** Run `work` while holding the inventory write lock next to the inventory file. */ +export function withInventoryLock(inventoryPath: string, work: () => T, options: LockOptions = {}): T { + const release = acquireDirLock(join(dirname(inventoryPath), INVENTORY_LOCK_DIR), "inventory", options); + try { + return work(); + } finally { + release(); + } +} + +/** The file's own indent (spaces or a tab) and whether it ends with a newline, so a rewrite keeps its style. */ +export function jsonStyle(text: string): { indent: string; newline: boolean } { + const m = /\n([ \t]+)\S/.exec(text); + return { indent: m ? m[1]! : " ", newline: text.endsWith("\n") }; +} + +/** `doc` serialized in the style of `original`. */ +export function inventoryText(doc: unknown, original: string): string { + const style = jsonStyle(original); + return JSON.stringify(doc, null, style.indent) + (style.newline ? "\n" : ""); +} + +/** + * Replace the inventory with `bytes`: the temp file next to it is flushed and loaded with the normal inventory loader + * (same folder, so relative roots resolve the same) before the rename. On any failure the temp file is removed and the + * old inventory stays as it was. Call it while holding the inventory lock. + */ +export function writeInventoryValidated(inventoryPath: string, bytes: string, beforeRename?: () => void): void { + let temporary: string | null = null; + try { + replaceFileDurable(inventoryPath, bytes, (t) => { temporary = t; }, () => { loadInventory(temporary!); beforeRename?.(); }); + } catch (e) { + if (temporary !== null) rmSync(temporary, { force: true }); + throw e; + } +} diff --git a/packages/core/src/scope-index.ts b/packages/core/src/scope-index.ts index 4a3144a..1d77cae 100644 --- a/packages/core/src/scope-index.ts +++ b/packages/core/src/scope-index.ts @@ -93,7 +93,7 @@ function assertFocus(entry: Record, file: string): void { * exist yet keeps its canonical ancestor plus the remaining lexical segments, so a root that * appears later can still be compared by identity. */ -function canonicalPath(path: string): string { +export function canonicalPath(path: string): string { try { return realpathSync(path); } catch { diff --git a/packages/core/src/scope-move.ts b/packages/core/src/scope-move.ts new file mode 100644 index 0000000..8a4b978 --- /dev/null +++ b/packages/core/src/scope-move.ts @@ -0,0 +1,280 @@ +// `mozak scope move` (owner route): move a scope's files into a vault folder and point its inventory entry there. +// Copies mozak.json, mozak.md (or their pre-0.4 names), README.md, AGENTS.md and the annotations sidecar, verifies +// every copy byte for byte, then rewrites only that inventory entry to { id, root } under the inventory lock with the +// same validated atomic write as `focus`. Every other key and entry stays as it was. The old files stay in place. +// A failure before the inventory rename removes what was copied, so both places and the old inventory stay valid. +// `--drop` removes a 0-plan entry from the inventory instead (its files stay). No git and no network here. + +import { createHash, randomUUID } from "node:crypto"; +import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, statSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { DomainError } from "./errors.ts"; +import { executeOperation, type OperationOutput } from "./api.ts"; +import { fsyncDir, writeFileDurable } from "./durable.ts"; +import { inventoryText, withInventoryLock, writeInventoryValidated } from "./inventory-file.ts"; +import { canonicalPath, loadInventory, type ScopeEntry, type ScopeInventory } from "./scope-index.ts"; +import { SCOPE_FILE_NAMES } from "./scope-files.ts"; +import { readScope, withScopeLocks } from "./scope-store.ts"; +import { ANNOTATIONS_FILE } from "./annotations.ts"; +import { isUtcTimestamp } from "./understanding.ts"; +import { nonEmptyString } from "./validate.ts"; +import { vaultOf } from "./vault-config.ts"; + +/** Files a move carries, in copy order. The plan file comes first so a reader never sees a projection without it. */ +export const MOVED_FILES = [...SCOPE_FILE_NAMES, ANNOTATIONS_FILE, "README.md", "AGENTS.md"] as const; +/** Entry keys that name where the plans are. A move replaces them with one `root`. */ +const LOCATION_KEYS = new Set(["root", "remote", "ref", "plans"]); + +export interface MoveArgs { + scope: unknown; to?: unknown; drop?: unknown; dryRun?: unknown; + ownerRef: unknown; ownerMessageAt: unknown; reason: unknown; +} +export interface MovedFile { name: string; bytes: number; sha256: string } +export interface MoveResult { + status: "ok" | "dry-run"; + scope: string; + action: "move" | "drop"; + from: string; + to: string | null; + inPlace: boolean; + changed: boolean; + plans: number; + files: MovedFile[]; + /** The rewritten inventory entry, or null for a drop. */ + entry: Record | null; + warnings: { code: string; message: string }[]; + owner: { ownerRef: string; ownerMessageAt: string; reason: string }; +} +export interface MoveOptions { onPhase?: (phase: string) => void; lockTimeoutMs?: number } + +type RawEntry = Record & { id: string }; +type SourceFile = { name: string; bytes: Buffer; mode: number }; +interface Request { scope: string; to: string | null; dryRun: boolean; owner: MoveResult["owner"] } + +const sha256 = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex"); +const invalid = (message: string) => new DomainError("invalid-input", message, 2); + +/** Boundary: check every argument once. Owner provenance is required and never synthesized. */ +export function parseMoveArgs(a: MoveArgs): Request { + const scope = nonEmptyString(a.scope, "scope"); + const drop = a.drop === true; + if (a.drop !== undefined && typeof a.drop !== "boolean") throw invalid("drop must be a boolean"); + if (drop === (a.to !== undefined)) throw invalid("scope move needs exactly one of --to PATH or --drop"); + const to = drop ? null : nonEmptyString(a.to, "to"); + const ownerRef = nonEmptyString(a.ownerRef, "ownerRef"); + if (!isUtcTimestamp(a.ownerMessageAt)) throw invalid("ownerMessageAt must be the UTC time of the owner's message, for example 2026-11-01T17:25:00.000Z"); + const reason = nonEmptyString(a.reason, "reason"); + return { scope, to, dryRun: a.dryRun === true, owner: { ownerRef, ownerMessageAt: a.ownerMessageAt, reason } }; +} + +/** Run `check` on the source folder as a plain local scope: no settings, no remote refresh, no network. */ +function assertSourceChecks(entry: ScopeEntry): void { + const local: ScopeInventory = { format: "mozak.local/v3", scopes: [{ id: entry.id, root: entry.root }], digest: "" }; + const out = executeOperation(local, "check", { scope: entry.id }); + if (out.exitCode === 0) return; + const codes = (out.data.issues as { code: string }[]).map((i) => i.code).join(", "); + throw new DomainError("move-source-fails-check", `scope "${entry.id}" at ${entry.root} fails check (${codes}); fix that first, the move copies only a clean scope`, 3); +} + +/** + * The regular files of MOVED_FILES present in `root`, with their bytes. Names come from listing the folder, so on a + * case-insensitive disk mozak.json is never also read as MOZAK.json. A symlink or other file type is refused. + */ +function sourceFiles(root: string): SourceFile[] { + const present = new Set(readdirSync(root)); + const out: SourceFile[] = []; + for (const name of MOVED_FILES) { + if (!present.has(name)) continue; + const path = join(root, name); + const st = lstatSync(path); + if (!st.isFile()) throw new DomainError("scope-file-not-regular", `${name} in ${root} must be a regular file, not a link or folder`, 2); + out.push({ name, bytes: readFileSync(path), mode: st.mode & 0o777 }); + } + return out; +} + +/** Refuse a target that already holds a scope or any file the move would write. Only called when the folder changes. */ +function assertTargetFree(target: string, names: string[], inv: ScopeInventory): void { + const other = inv.scopes.find((s) => s.root === target); + if (other) throw new DomainError("move-target-has-scope", `${target} is already the folder of scope "${other.id}"`, 2); + if (!existsSync(target)) return; + if (!statSync(target).isDirectory()) throw new DomainError("move-target-not-directory", `${target} exists and is not a folder`, 2); + const plan = SCOPE_FILE_NAMES.find((n) => existsSync(join(target, n))); + if (plan) throw new DomainError("move-target-has-scope", `${target} already holds ${plan}; pick an empty folder`, 2); + const taken = names.filter((n) => existsSync(join(target, n))); + if (taken.length) throw new DomainError("move-target-file-exists", `${target} already holds ${taken.join(", ")}; the move never overwrites a file`, 2); +} + +/** Pinned specification paths of every plan that do not exist under `target`. The move does not carry them. */ +function specsLeftBehind(source: ScopeEntry, target: string): { code: string; message: string }[] { + const paths = new Set(readScope(source).state.plans.flatMap((p) => p.specifications.map((s) => s.path))); + return [...paths].sort().filter((p) => !existsSync(join(target, p))).map((p) => ({ + code: "spec-not-moved", + message: `specification ${p} is not copied; copy it to ${join(target, p)} by hand if the plan still needs it`, + })); +} + +/** The entry after the move: id, the new root, then every other key of the old entry in its order (focus, x). */ +function movedEntry(old: RawEntry, to: string): Record { + const out: Record = { id: old.id, root: to }; + for (const [k, v] of Object.entries(old)) if (k !== "id" && !LOCATION_KEYS.has(k)) out[k] = v; + return out; +} + +/** + * Copy every file through a flushed temp file, verify the bytes, rename into place, then run the inventory step. + * Any failure before the inventory points at `target` removes what was copied and the folders it made. + */ +function copyVerified(files: SourceFile[], target: string, onPhase: (p: string) => void, inventoryStep: () => void, inventoryPointsHere: () => boolean): void { + const createdDirs = missingDirs(target); + const placed: string[] = []; + try { + for (const d of [...createdDirs].reverse()) mkdirSync(d); + for (const f of files) { + placed.push(placeVerified(f, target)); + onPhase(`after-copy:${f.name}`); + } + fsyncDir(target); + for (const f of files) assertSameBytes(join(target, f.name), f.bytes); + inventoryStep(); + } catch (e) { + if (!inventoryPointsHere()) rollBack(placed, createdDirs); + throw e; + } +} + +/** Folders from `target` up to the first one that exists, deepest first. */ +function missingDirs(target: string): string[] { + const out: string[] = []; + for (let d = target; !existsSync(d); d = dirname(d)) out.push(d); + return out; +} + +function assertSameBytes(path: string, bytes: Buffer): void { + if (!readFileSync(path).equals(bytes)) throw new DomainError("move-verify-failed", `${path} differs from the source after the copy`, 4); +} + +/** One file: flushed temp file, same mode, bytes checked, renamed into place. Returns the final path. */ +function placeVerified(f: SourceFile, target: string): string { + const temp = join(target, `.${f.name}.${randomUUID()}.move-tmp`); + try { + writeFileDurable(temp, f.bytes); + chmodSync(temp, f.mode); + assertSameBytes(temp, f.bytes); + renameSync(temp, join(target, f.name)); + } catch (e) { + rmSync(temp, { force: true }); + throw e; + } + return join(target, f.name); +} + +function rollBack(placed: string[], createdDirs: string[]): void { + for (const p of placed) rmSync(p); + for (const d of createdDirs) { try { rmdirSync(d); } catch { /* not empty or gone: leave it */ } } +} + +/** Under the scope lock: the files must still be the ones the plan read, else a write slipped in between. */ +function assertUnchanged(fresh: SourceFile[], planned: SourceFile[]): void { + const same = fresh.length === planned.length && fresh.every((f, i) => f.name === planned[i]!.name && f.bytes.equals(planned[i]!.bytes)); + if (!same) throw new DomainError("stale-input", "the scope changed while the move started; run it again", 3); +} + +/** + * Move or drop one scope. Dry run reports the files and the new entry without writing anything. Running the same + * move twice is a no-op the second time (the entry already points at the target). + */ +export function moveScope(inventoryPath: string, args: MoveArgs, options: MoveOptions = {}): MoveResult { + const req = parseMoveArgs(args); + const onPhase = (phase: string) => options.onPhase?.(phase); + if (req.dryRun) return { ...planMove(inventoryPath, req).result, status: "dry-run" }; + return withInventoryLock(inventoryPath, () => { + const p = planMove(inventoryPath, req); + if (!p.result.changed) return p.result; + const writeInventory = () => { onPhase("before-inventory-write"); writeInventoryValidated(inventoryPath, p.text); }; + const written = () => readFileSync(inventoryPath, "utf8") === p.text; + withScopeLocks([p.source.root], () => { + // Reread under the scope lock: a plan write between the plan and the lock would change the bytes. + if (p.files.length === 0) return writeInventory(); + const fresh = sourceFiles(p.source.root); + assertUnchanged(fresh, p.files); + copyVerified(fresh, p.result.to!, onPhase, writeInventory, written); + }, options); + return p.result; + }, options); +} + +interface Planned { result: MoveResult; source: ScopeEntry; files: SourceFile[]; text: string } + +/** Everything the move will do, checked against the current inventory and files. Writes nothing. */ +function planMove(inventoryPath: string, req: Request): Planned { + const text = readFileSync(inventoryPath, "utf8"); + const inv = loadInventory(inventoryPath); + const loaded = inv.scopes.find((s) => s.id === req.scope); + if (!loaded) throw new DomainError("scope-not-found", `no scope "${req.scope}" in the inventory; run mozak scopes to list the scope ids`, 2); + const source: ScopeEntry = { id: loaded.id, root: loaded.root }; + const doc = JSON.parse(text) as { scopes: RawEntry[] }; + const index = doc.scopes.findIndex((e) => e.id === req.scope); + const old = doc.scopes[index]!; + const base = { scope: req.scope, from: source.root, owner: req.owner, warnings: [] as MoveResult["warnings"] }; + + if (req.to === null) { + const plans = readScope(source).state.plans.length; + if (plans > 0) throw new DomainError("drop-refused-has-plans", `scope "${req.scope}" has ${plans} plan(s); only a scope with 0 plans can be dropped. Move it instead`, 2); + doc.scopes.splice(index, 1); + return { source, files: [], text: inventoryText(doc, text), result: { ...base, status: "ok", action: "drop", to: null, inPlace: false, changed: true, plans, files: [], entry: null } }; + } + + const target = canonicalPath(resolve(dirname(inventoryPath), req.to)); + if (vaultOf(target) === null) { + throw new DomainError("move-target-outside-vault", `${target} is not inside an Obsidian vault: no folder at or above it has a .obsidian folder`, 2); + } + const inPlace = target === source.root; + const files = inPlace ? [] : sourceFiles(source.root); + if (!inPlace) assertTargetFree(target, files.map((f) => f.name), inv); + assertSourceChecks(source); + const entry = movedEntry(old, req.to); + const changed = JSON.stringify(entry) !== JSON.stringify(old); + doc.scopes[index] = entry as RawEntry; + const plans = readScope(source).state.plans.length; + const warnings = inPlace ? [] : specsLeftBehind(source, target); + return { + source, files, text: inventoryText(doc, text), + result: { ...base, status: "ok", action: "move", to: target, inPlace, changed, plans, warnings, entry, files: files.map((f) => ({ name: f.name, bytes: f.bytes.length, sha256: sha256(f.bytes) })) }, + }; +} + +/** Route shared by the CLI: moveScope with its errors as an envelope. Owner only; MCP never exposes it. */ +export function scopeMoveOutput(inventoryPath: string, args: MoveArgs, options: MoveOptions = {}): OperationOutput { + try { + return { exitCode: 0, data: { ...moveScope(inventoryPath, args, options) } }; + } catch (err) { + if (!(err instanceof DomainError)) throw err; + return { exitCode: err.exitCode, data: { status: err.code, issues: [{ code: err.code, message: err.message }] } }; + } +} + +/** One-screen text form for the CLI. Errors print as their JSON envelope. */ +export function renderMove(d: Record): string { + if (d.status !== "ok" && d.status !== "dry-run") return `${JSON.stringify(d, null, 2)}\n`; + const lines = [`status: ${d.status}${statusNote(d)}`, ...(d.action === "drop" ? dropLines(d) : moveLines(d))]; + for (const w of d.warnings) lines.push(`warning ${w.code}: ${w.message}`); + return `${lines.join("\n")}\n`; +} + +function statusNote(d: Record): string { + if (d.status === "dry-run") return " (nothing written)"; + return d.changed ? "" : " (already done, nothing changed)"; +} + +function dropLines(d: Record): string[] { + return [`drop ${d.scope}: remove its inventory entry (0 plans); files stay in ${d.from}`]; +} + +function moveLines(d: Record): string[] { + const lines = [`move ${d.scope}: ${d.plans} plan(s)`, ` from ${d.from}`, ` to ${d.to}${d.inPlace ? " (same folder, entry only)" : ""}`]; + for (const f of d.files) lines.push(` copy ${f.name} (${f.bytes} bytes, sha256 ${String(f.sha256).slice(0, 12)})`); + lines.push(` new entry: ${JSON.stringify(d.entry)}`); + if (d.status === "ok" && d.changed && !d.inPlace) lines.push(`the old files stay in ${d.from}; delete them only after checking the new folder`); + return lines; +} diff --git a/packages/core/src/vault-config.ts b/packages/core/src/vault-config.ts index b0fc023..2434d5a 100644 --- a/packages/core/src/vault-config.ts +++ b/packages/core/src/vault-config.ts @@ -2,7 +2,7 @@ // Inside the plugin, Vault#configDir is the answer. Outside it there is no API, and users can rename the folder, // so this looks for the default name first and then for any dot folder that has Obsidian's own config files. import { existsSync, readdirSync, statSync } from "node:fs"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; /** The default config folder name. Kept in one place; everything else asks vaultConfigDir. */ export const DEFAULT_CONFIG_DIR = [".", "obsidian"].join(""); @@ -29,6 +29,18 @@ export function vaultConfigDir(vault: string): string | null { return null; } +/** + * The vault folder that holds `path`: the nearest folder at or above it with a `.obsidian` folder, or null. `path` + * need not exist yet. Only the default config folder name counts, so a scope root is in a vault on every machine or + * on none. This is the vault rule every scope root must meet. + */ +export function vaultOf(path: string): string | null { + for (let dir = path; ; dir = dirname(dir)) { + if (isDir(join(dir, DEFAULT_CONFIG_DIR))) return dir; + if (dirname(dir) === dir) return null; + } +} + /** Where the mozak plugin lives in a vault, or null when the vault has no config folder. */ export function vaultPluginDir(vault: string): string | null { const config = vaultConfigDir(vault); diff --git a/packages/core/test/scope-move.test.ts b/packages/core/test/scope-move.test.ts new file mode 100644 index 0000000..218de30 --- /dev/null +++ b/packages/core/test/scope-move.test.ts @@ -0,0 +1,260 @@ +// mozak scope move (owner route): copy a scope's files into a vault folder, verify them byte for byte, then point the +// inventory entry at the new folder. Synthetic temp folders only. Never a real inventory or vault. +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { content, NOW } from "./annotations-fixture.ts"; +import { executeOperation } from "../src/api.ts"; +import { loadInventory } from "../src/scope-index.ts"; +import { initScopeState, mutateScope, readScope } from "../src/scope-store.ts"; +import { reviewShow } from "../src/review.ts"; +import { moveScope, renderMove, scopeMoveOutput } from "../src/scope-move.ts"; + +const made: string[] = []; +after(() => { for (const d of made.splice(0)) rmSync(d, { recursive: true, force: true }); }); + +const OWNER = { ownerRef: "synthetic:owner-move", ownerMessageAt: NOW, reason: "Synthetic move into the vault" }; +const sha = (path: string) => createHash("sha256").update(readFileSync(path)).digest("hex"); + +/** Make a scope at `root` with one accepted plan (so it has receipts) and the usual entry files. */ +function makeScope(id: string, root: string, plans = 1): void { + mkdirSync(root, { recursive: true }); + writeFileSync(join(root, "README.md"), `# ${id}\n`); + writeFileSync(join(root, "AGENTS.md"), `Agents for ${id}\n`); + const entry = { id, root: realpathSync(root) }; + initScopeState(entry, { operationId: `init-${id}`, scopeId: id, kind: "project", title: `Synthetic ${id}`, expectedAbsent: { graph: true, bridge: true }, ownerRef: "synthetic:init", ownerMessageAt: NOW }); + for (let i = 1; i <= plans; i++) { + const planId = `${id}-p${i}`; + mutateScope(entry, { operationId: `prop-${planId}`, scopeId: id, expected: readScope(entry).snapshot, action: "propose", payload: { planId, content: content(planId), distinctFromPlanIds: readScope(entry).state.plans.map((p) => p.id) } }, "agent"); + const shown = reviewShow(readScope(entry).state, planId, "approve-direction"); + mutateScope(entry, { operationId: `appr-${planId}`, scopeId: id, expected: readScope(entry).snapshot, action: "approve-direction", payload: { planId, revisionId: shown.revisionId, reviewDigest: shown.reviewDigest, ownerRef: "synthetic:approve", ownerMessageAt: NOW, reason: "Synthetic approval" } }, "owner"); + } +} + +/** + * base/inventory.json, a vault at base/vault (it has a .obsidian folder), a local scope outside the vault at + * base/code/proj, a scope already in the vault at base/vault/home, and a 0-plan scope outside it at base/code/empty. + */ +function setup(extraEntries: unknown[] = []) { + const base = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "mozak-move-")); + made.push(base); + const vault = join(base, "vault"); + mkdirSync(join(vault, ".obsidian"), { recursive: true }); + makeScope("proj", join(base, "code", "proj"), 2); + makeScope("home", join(vault, "home")); + makeScope("empty", join(base, "code", "empty"), 0); + const config = join(base, "inventory.json"); + const text = `{\n "format": "mozak.local/v3",\n "x": { "note": "kept" },\n "scopes": [\n { "id": "home", "root": "vault/home", "focus": [] },\n { "id": "proj", "root": "code/proj", "focus": ["proj-p1"], "x": { "colour": "red" } },\n { "id": "empty", "root": "code/empty" }${extraEntries.map((e) => `,\n ${JSON.stringify(e)}`).join("")}\n ]\n}\n`; + writeFileSync(config, text); + return { base, vault, config, text }; +} +const raw = (config: string) => JSON.parse(readFileSync(config, "utf8")); +const plansOf = (config: string, scope: string) => JSON.stringify(executeOperation(loadInventory(config), "plans", { scope, includeRejected: true, limit: 100 }).data.groups); +/** check after the move: no findings except the x-key notice this fixture's inventory causes on purpose. */ +function assertClean(config: string, scope: string): void { + const out = executeOperation(loadInventory(config), "check", { scope }); + const issues = (out.data.issues as { code: string }[]).filter((i) => i.code !== "inventory-x-ignored"); + assert.deepEqual(issues, [], `${scope}: ${JSON.stringify(out.data.issues)}`); +} + +test("move: a local scope outside the vault is copied, verified and the entry rewritten; plans and receipts unchanged", () => { + const f = setup(); + const src = join(f.base, "code", "proj"); + const before = { json: sha(join(src, "mozak.json")), md: sha(join(src, "mozak.md")), plans: plansOf(f.config, "proj"), receipts: readScope({ id: "proj", root: realpathSync(src) }).state.receipts }; + const out = moveScope(f.config, { scope: "proj", to: "vault/projects/proj", ...OWNER }); + assert.equal(out.status, "ok"); + assert.equal(out.changed, true); + const target = join(f.vault, "projects", "proj"); + assert.deepEqual(out.files.map((x) => x.name).sort(), ["AGENTS.md", "README.md", "mozak.json", "mozak.md"]); + for (const x of out.files) assert.equal(x.sha256, sha(join(target, x.name))); + assert.equal(sha(join(target, "mozak.json")), before.json, "mozak.json byte-identical"); + assert.equal(sha(join(target, "mozak.md")), before.md, "mozak.md byte-identical"); + // The old files stay where they were. + assert.equal(sha(join(src, "mozak.json")), before.json); + // Only that entry changed: root replaced, focus and x kept; every other key and entry untouched. + const doc = raw(f.config); + assert.deepEqual(doc.x, { note: "kept" }); + assert.deepEqual(doc.scopes[0], { id: "home", root: "vault/home", focus: [] }); + assert.deepEqual(doc.scopes[1], { id: "proj", root: "vault/projects/proj", focus: ["proj-p1"], x: { colour: "red" } }); + assert.deepEqual(doc.scopes[2], { id: "empty", root: "code/empty" }); + assert.match(readFileSync(f.config, "utf8"), /^\{\n "format"/, "indent kept"); + assert.equal(plansOf(f.config, "proj"), before.plans, "plans read the same through the new entry"); + assert.deepEqual(readScope({ id: "proj", root: realpathSync(target) }).state.receipts, before.receipts); + assertClean(f.config, "proj"); + // No lock or temp file left behind in either place. + assert.deepEqual(readdirSync(target).sort(), ["AGENTS.md", "README.md", "mozak.json", "mozak.md"]); + assert.ok(!existsSync(join(src, ".mozak-write-lock"))); + assert.ok(!existsSync(join(f.base, ".mozak-inventory-lock"))); +}); + +test("move --dry-run prints the files and the new entry and writes nothing", () => { + const f = setup(); + const out = moveScope(f.config, { scope: "proj", to: "vault/projects/proj", dryRun: true, ...OWNER }); + assert.equal(out.status, "dry-run"); + assert.deepEqual(out.entry, { id: "proj", root: "vault/projects/proj", focus: ["proj-p1"], x: { colour: "red" } }); + assert.equal(out.files.length, 4); + assert.ok(out.files.every((x) => x.bytes > 0 && /^[0-9a-f]{64}$/.test(x.sha256))); + assert.equal(readFileSync(f.config, "utf8"), f.text); + assert.ok(!existsSync(join(f.vault, "projects"))); +}); + +test("move of a legacy vault-plans entry to its own plans folder rewrites the entry in place without copying", () => { + const f = setup([{ id: "tool", remote: "github:synthetic/tool", plans: "vault/tool" }]); + makeScope("tool", join(f.vault, "tool")); + const bytes = sha(join(f.vault, "tool", "mozak.json")); + const out = moveScope(f.config, { scope: "tool", to: "vault/tool", ...OWNER }); + assert.equal(out.status, "ok"); + assert.equal(out.inPlace, true); + assert.deepEqual(out.files, []); + assert.deepEqual(raw(f.config).scopes[3], { id: "tool", root: "vault/tool" }); + assert.equal(sha(join(f.vault, "tool", "mozak.json")), bytes); + assertClean(f.config, "tool"); +}); + +test("move of a legacy repo-cache entry copies the cached plan files into the vault", () => { + const f = setup([{ id: "web", remote: "github:synthetic/web", ref: "main" }]); + const cache = join(f.base, ".mozak-cache", "web"); + makeScope("web", cache); + writeFileSync(join(cache, "mozak.annotations.json"), "{}\n"); + const json = sha(join(cache, "mozak.json")); + const out = moveScope(f.config, { scope: "web", to: "vault/projects/web", ...OWNER }); + assert.equal(out.status, "ok"); + assert.deepEqual(out.files.map((x) => x.name).sort(), ["AGENTS.md", "README.md", "mozak.annotations.json", "mozak.json", "mozak.md"]); + assert.equal(sha(join(f.vault, "projects", "web", "mozak.json")), json); + assert.deepEqual(raw(f.config).scopes[3], { id: "web", root: "vault/projects/web" }); + assert.ok(existsSync(join(cache, "mozak.json")), "the cache copy stays"); + assertClean(f.config, "web"); +}); + +test("move refuses a target outside a vault, a target that holds mozak files, another scope's root and a bad source", () => { + const f = setup(); + const same = () => assert.equal(readFileSync(f.config, "utf8"), f.text); + assert.throws(() => moveScope(f.config, { scope: "proj", to: "elsewhere/proj", ...OWNER }), { code: "move-target-outside-vault", message: /\.obsidian/ }); + mkdirSync(join(f.vault, "taken"), { recursive: true }); + writeFileSync(join(f.vault, "taken", "mozak.json"), "{}"); + assert.throws(() => moveScope(f.config, { scope: "proj", to: "vault/taken", ...OWNER }), { code: "move-target-has-scope" }); + assert.throws(() => moveScope(f.config, { scope: "proj", to: "vault/home", ...OWNER }), { code: "move-target-has-scope" }); + mkdirSync(join(f.vault, "readme"), { recursive: true }); + writeFileSync(join(f.vault, "readme", "README.md"), "someone else's notes\n"); + assert.throws(() => moveScope(f.config, { scope: "proj", to: "vault/readme", ...OWNER }), { code: "move-target-file-exists" }); + assert.equal(readFileSync(join(f.vault, "readme", "README.md"), "utf8"), "someone else's notes\n"); + assert.throws(() => moveScope(f.config, { scope: "nope", to: "vault/nope", ...OWNER }), { code: "scope-not-found" }); + // A source that fails check: mozak.md edited by hand. + writeFileSync(join(f.base, "code", "proj", "mozak.md"), "hand edit\n"); + assert.throws(() => moveScope(f.config, { scope: "proj", to: "vault/projects/proj", ...OWNER }), { code: "move-source-fails-check" }); + assert.ok(!existsSync(join(f.vault, "projects"))); + same(); +}); + +test("move refuses missing owner provenance and bad arguments before touching anything", () => { + const f = setup(); + assert.throws(() => moveScope(f.config, { scope: "proj", to: "vault/p", ...OWNER, ownerRef: "" }), { code: "invalid-input" }); + assert.throws(() => moveScope(f.config, { scope: "proj", to: "vault/p", ...OWNER, ownerMessageAt: "yesterday" }), { code: "invalid-input" }); + assert.throws(() => moveScope(f.config, { scope: "proj", to: "vault/p", ...OWNER, reason: " " }), { code: "invalid-input" }); + assert.throws(() => moveScope(f.config, { scope: "proj", ...OWNER }), { code: "invalid-input", message: /--to PATH or --drop/ }); + assert.throws(() => moveScope(f.config, { scope: "proj", to: "vault/p", drop: true, ...OWNER }), { code: "invalid-input" }); + assert.equal(readFileSync(f.config, "utf8"), f.text); +}); + +test("a failure halfway through leaves the source, the target folder and the old inventory as they were", () => { + for (const phase of ["after-copy:mozak.json", "before-inventory-write"]) { + const f = setup(); + const src = join(f.base, "code", "proj"); + const json = sha(join(src, "mozak.json")); + assert.throws(() => moveScope(f.config, { scope: "proj", to: "vault/projects/proj", ...OWNER }, { onPhase: (p) => { if (p === phase) throw new Error(`injected at ${p}`); } }), /injected/); + assert.equal(readFileSync(f.config, "utf8"), f.text, `${phase}: inventory unchanged`); + assert.equal(sha(join(src, "mozak.json")), json); + assert.ok(!existsSync(join(f.vault, "projects", "proj", "mozak.json")), `${phase}: no partial copy left`); + assert.ok(!existsSync(join(src, ".mozak-write-lock")), `${phase}: scope lock released`); + assert.ok(!existsSync(join(f.base, ".mozak-inventory-lock")), `${phase}: inventory lock released`); + // The route still works afterwards. + assert.equal(moveScope(f.config, { scope: "proj", to: "vault/projects/proj", ...OWNER }).status, "ok"); + } +}); + +test("a scope file that changes between the plan and the scope lock stops the move with stale-input", () => { + const changes: [string, (src: string) => void][] = [ + ["same size", (src) => writeFileSync(join(src, "README.md"), readFileSync(join(src, "README.md"), "utf8").toUpperCase())], + ["file removed", (src) => rmSync(join(src, "AGENTS.md"))], + ]; + for (const [label, change] of changes) { + const f = setup(); + const src = join(f.base, "code", "proj"); + assert.throws(() => moveScope(f.config, { scope: "proj", to: "vault/projects/proj", ...OWNER }, { onPhase: (p) => { if (p === "all-locked") change(src); } }), { code: "stale-input" }, label); + assert.equal(readFileSync(f.config, "utf8"), f.text, label); + assert.ok(!existsSync(join(f.vault, "projects", "proj")), label); + } +}); + +test("move is idempotent: a second run of the same move changes nothing", () => { + const f = setup(); + moveScope(f.config, { scope: "proj", to: "vault/projects/proj", ...OWNER }); + const text = readFileSync(f.config, "utf8"); + const again = moveScope(f.config, { scope: "proj", to: "vault/projects/proj", ...OWNER }); + assert.equal(again.changed, false); + assert.equal(readFileSync(f.config, "utf8"), text); +}); + +test("drop removes a 0-plan entry only, leaves its files, and refuses a scope that has plans", () => { + const f = setup(); + assert.throws(() => moveScope(f.config, { scope: "proj", drop: true, ...OWNER }), { code: "drop-refused-has-plans" }); + assert.throws(() => moveScope(f.config, { scope: "home", drop: true, ...OWNER }), { code: "drop-refused-has-plans", message: /has 1 plan/ }); + const dry = moveScope(f.config, { scope: "empty", drop: true, dryRun: true, ...OWNER }); + assert.equal(dry.status, "dry-run"); + assert.equal(readFileSync(f.config, "utf8"), f.text); + const out = moveScope(f.config, { scope: "empty", drop: true, ...OWNER }); + assert.equal(out.status, "ok"); + assert.equal(out.entry, null); + assert.equal(out.inPlace, false); + assert.equal(out.to, null); + assert.deepEqual(raw(f.config).scopes.map((s: { id: string }) => s.id), ["home", "proj"]); + assert.ok(existsSync(join(f.base, "code", "empty", "mozak.json")), "files stay"); +}); + +test("a pinned specification that stays behind is reported as a warning", () => { + const f = setup(); + const src = join(f.base, "code", "proj"); + mkdirSync(join(src, "docs")); + writeFileSync(join(src, "docs", "spec.md"), "# spec\n"); + const entry = { id: "proj", root: realpathSync(src) }; + const st = readScope(entry).state; + const plan = st.plans[0]!; + const bounds = { summary: "fixture", allowedPaths: [], excludedActions: [], outcomeChecks: plan.accepted!.content.outcomes.map((o) => ({ outcomeId: o.id, criterion: "passes" })), limitations: [] }; + const r = mutateScope(entry, { operationId: "spec-1", scopeId: "proj", expected: readScope(entry).snapshot, action: "attach-spec", payload: { planId: plan.id, acceptedRevisionId: plan.accepted!.id, path: "docs/spec.md", bounds, discussionDigest: null } }, "agent"); + assert.equal(r.committed, true, JSON.stringify(r)); + const out = moveScope(f.config, { scope: "proj", to: "vault/projects/proj", dryRun: true, ...OWNER }); + assert.deepEqual(out.warnings.map((w) => w.code), ["spec-not-moved"]); + assert.match(out.warnings[0]!.message, /docs\/spec\.md/); +}); + +test("renderMove: dry run, done, already done, in place, drop, warnings and errors", () => { + const f = setup([{ id: "tool", remote: "github:synthetic/tool", plans: "vault/tool" }]); + makeScope("tool", join(f.vault, "tool")); + const dry = renderMove(moveScope(f.config, { scope: "proj", to: "vault/projects/proj", dryRun: true, ...OWNER })); + assert.match(dry, /^status: dry-run \(nothing written\)\nmove proj: 2 plan\(s\)\n from .*code\/proj\n to .*vault\/projects\/proj\n copy mozak\.json \(\d+ bytes, sha256 [0-9a-f]{12}\)/); + assert.match(dry, /new entry: \{"id":"proj","root":"vault\/projects\/proj","focus":\["proj-p1"\],"x":\{"colour":"red"\}\}\n$/); + assert.doesNotMatch(dry, /old files stay/); + const done = renderMove(moveScope(f.config, { scope: "proj", to: "vault/projects/proj", ...OWNER })); + assert.match(done, /^status: ok\n/); + assert.match(done, /the old files stay in .*code\/proj; delete them only after checking the new folder\n$/); + assert.match(renderMove(moveScope(f.config, { scope: "proj", to: "vault/projects/proj", ...OWNER })), /^status: ok \(already done, nothing changed\)\n/); + const inPlace = renderMove(moveScope(f.config, { scope: "tool", to: "vault/tool", ...OWNER })); + assert.match(inPlace, /\(same folder, entry only\)/); + assert.doesNotMatch(inPlace, /copy |old files stay/); + assert.match(renderMove(moveScope(f.config, { scope: "empty", drop: true, ...OWNER })), /^status: ok\ndrop empty: remove its inventory entry \(0 plans\); files stay in .*code\/empty\n$/); + assert.match(renderMove({ status: "ok", action: "move", scope: "s", plans: 1, from: "/a", to: "/b", files: [], entry: {}, changed: true, inPlace: false, warnings: [{ code: "spec-not-moved", message: "m" }] }), /warning spec-not-moved: m\n$/); + assert.equal(renderMove({ status: "scope-not-found", issues: [] }), `${JSON.stringify({ status: "scope-not-found", issues: [] }, null, 2)}\n`); +}); + +test("scopeMoveOutput: errors become an envelope with the domain exit code", () => { + const f = setup(); + const bad = scopeMoveOutput(f.config, { scope: "proj", to: "elsewhere", ...OWNER }); + assert.equal(bad.exitCode, 2); + assert.equal(bad.data.status, "move-target-outside-vault"); + const ok = scopeMoveOutput(f.config, { scope: "proj", to: "vault/projects/proj", dryRun: true, ...OWNER }); + assert.equal(ok.exitCode, 0); + assert.equal(ok.data.status, "dry-run"); +}); From f37192c0b67ee0918c1c0fe7449212bef61a6eef Mon Sep 17 00:00:00 2001 From: pitfa19 <166558275+pitfa19@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:11:09 +0100 Subject: [PATCH 02/10] Enforce the vault rule: a scope root must sit inside an Obsidian vault Why: spec step 3, owner answer of 2026-11-01 ("enforce, do not only warn"). mozak keeps plans in vaults only. What: - loadInventory marks an entry whose root has no folder with .obsidian at or above it as refused (scope-outside-vault, naming mozak scope move). It is never a whole-inventory error: the entry stays listed, other scopes keep working, and scope move still reads it. resolveScope throws the refusal, so every read and write route refuses the scope. All-scope loops (render, rename-files, similar, locators, plans-md) now resolve each entry; local sync and default locator roots skip refused entries. - doctor (source and npm installs) reports the scope with its code and the scope move fix (inventoryFix, one place for the next step). - Test fixtures create their temp base as a vault (test/vault-temp.ts), so existing tests run on vault fixtures as the spec asks. The demo vault script, the README example and the installer test make the .obsidian folder first. Proof: vault-rule.test.ts (vaultOf, loader keeps and refuses, every route refuses, all-scope reads report failed coverage, scope move reads the refused entry) and the doctor tests failed first, pass now. Before the fixture change 216 existing tests failed on the new rule, after it none. npm test 652 of 652 under default TMPDIR, /tmp and a realpath folder, test:install 73 + 1 skipped. ub-mode: CRAP resolveScope 7.0 (was 10, entry selection split into selectEntry 4.0), inventoryFix 5.0, vaultOf 4.1, vaultRule 2.0. loadInventory stays at CC 46 (pre-existing; step 4 restructures it). dryer: no candidates. mutator on the changed lines: scope-index 5 of 5, vaultOf 1 of 1, inventoryFix 8 of 8 killed. --- packages/cli/src/doctor.ts | 23 +++-- packages/cli/test/acceptance.test.ts | 5 +- packages/cli/test/agent-ergonomics.test.ts | 5 +- packages/cli/test/cli.test.ts | 5 +- packages/cli/test/commit-flag.test.ts | 5 +- packages/cli/test/context-modes.test.ts | 8 +- packages/cli/test/cwd-scope.test.ts | 5 +- packages/cli/test/doctor.test.ts | 27 +++++- packages/cli/test/package2-history.test.ts | 5 +- packages/cli/test/package2-mixed-rows.test.ts | 5 +- packages/cli/test/package2-parity.test.ts | 5 +- packages/cli/test/package2-protected.test.ts | 5 +- packages/cli/test/package2-rows.test.ts | 5 +- packages/cli/test/render.test.ts | 5 +- packages/cli/test/scope-move-cli.test.ts | 2 +- packages/cli/test/scopes.test.ts | 5 +- packages/core/src/api.ts | 6 +- packages/core/src/local-sync.ts | 4 +- packages/core/src/locators.ts | 2 +- packages/core/src/plans-index.ts | 4 +- packages/core/src/scope-index.ts | 39 +++++++-- packages/core/test/annotations-fixture.ts | 5 +- packages/core/test/delete.test.ts | 5 +- packages/core/test/durable-write.test.ts | 3 +- packages/core/test/error-messages.test.ts | 5 +- packages/core/test/file-names.test.ts | 5 +- packages/core/test/handoff-store.test.ts | 5 +- packages/core/test/remote.test.ts | 9 +- packages/core/test/s2-offline.test.ts | 5 +- packages/core/test/s2-sync.test.ts | 7 +- packages/core/test/s6-fixture.ts | 5 +- packages/core/test/scope-index.test.ts | 4 +- packages/core/test/scope-move.test.ts | 11 ++- packages/core/test/storage-hygiene.test.ts | 5 +- packages/core/test/vault-plans.test.ts | 7 +- packages/core/test/vault-rule.test.ts | 87 +++++++++++++++++++ packages/core/test/vault-temp.ts | 15 ++++ packages/core/test/vdup-fixture.ts | 5 +- packages/core/test/visibility.test.ts | 5 +- packages/core/test/vref.test.ts | 5 +- packages/mcp/test/mcp.test.ts | 7 +- packages/mcp/test/package2-protected.test.ts | 5 +- packages/obsidian/test/model.test.ts | 13 +-- packages/obsidian/test/sync.test.ts | 5 +- scripts/readme-example.mjs | 2 + scripts/setup-demo-vault.mjs | 4 +- scripts/test-install.mjs | 3 +- 47 files changed, 306 insertions(+), 106 deletions(-) create mode 100644 packages/core/test/vault-rule.test.ts create mode 100644 packages/core/test/vault-temp.ts diff --git a/packages/cli/src/doctor.ts b/packages/cli/src/doctor.ts index 8680fa8..49b0a5e 100644 --- a/packages/cli/src/doctor.ts +++ b/packages/cli/src/doctor.ts @@ -147,6 +147,20 @@ function vaultsUnder(root: string): string[] { return out.sort(); } +/** + * The one next step for an inventory whose scopes do not read. Scopes outside a vault come first: they need + * `mozak scope move`. Then folders without mozak.json. Anything else: check the first failed scope. + */ +export function inventoryFix(inventoryPath: string, failed: { id: string; code?: string | undefined }[]): string { + const outside = failed.filter((r) => r.code === "scope-outside-vault" || r.code === "legacy-repo-scope"); + if (outside.length) return `Move each into a vault folder: mozak scope move --scope ${outside[0]!.id} --to --owner-ref REF --owner-message-at ISO --reason TEXT --config ${inventoryPath} (see docs/installation.md, Moving to 0.6.0)`; + if (failed.length === 0) return `mozak check --config ${inventoryPath} --scope `; + if (failed.every((r) => r.code === "scope-uninitialized")) { + return `These folders have no mozak.json. If your notes repo should have them, pull it; otherwise start each with mozak scope init (see the skill's references/bootstrap.md).`; + } + return `mozak check --config ${inventoryPath} --scope ${failed[0]!.id}`; +} + /** * Doctor for an npm install: npm owns the files and the `mozak` / `mozak-mcp` commands, so there is no manifest, * no wrapper and no source checkout to check. npm runs no install scripts, so the skill ships as a template and @@ -205,11 +219,11 @@ function doctorNpm( try { const inv = loadInventory(resolve(args.config)); const out = executeOperation(inv, "scopes", {}, "agent"); - const rows = (out.data.scopes ?? []) as Array<{ id: string; status?: string; error?: unknown }>; + const rows = (out.data.scopes ?? []) as Array<{ id: string; status?: string; code?: string; error?: unknown }>; const failed = rows.filter((r) => r.status === "failed" || r.error); add(failed.length === 0 ? { id: "inventory", state: "ok", message: `${args.config}: ${rows.length} scope(s), all readable` } - : { id: "inventory", state: "fail", message: `${args.config}: ${failed.length} scope(s) do not read: ${failed.map((r) => r.id).join(", ")}`, fix: `mozak check --config ${args.config} --scope ${failed[0].id}` }); + : { id: "inventory", state: "fail", message: `${args.config}: ${failed.length} scope(s) do not read: ${failed.map((r) => `${r.id}${r.code ? ` (${r.code})` : ""}`).join(", ")}`, fix: inventoryFix(args.config, failed) }); } catch (err) { add({ id: "inventory", state: "fail", message: `${args.config} does not load: ${err instanceof Error ? err.message : String(err)}`, fix: "Fix the JSON, or see docs/installation.md (Inventory)" }); } @@ -345,14 +359,11 @@ export function doctor(args: DoctorArgs): { exitCode: number; data: Record r.code ?? r.error?.code; if (cov?.complete && failed.length === 0) add({ id: "inventory", state: "ok", message: `${inventoryPath}: ${rows.length} scope(s), all readable` }); else { - const uninit = failed.filter((r) => codeOf(r) === "scope-uninitialized"); add({ id: "inventory", state: "fail", message: `${inventoryPath}: ${failed.length || "some"} scope(s) do not read: ${failed.map((r) => `${r.id}${codeOf(r) ? ` (${codeOf(r)})` : ""}`).join(", ")}`, - fix: uninit.length === failed.length && uninit.length > 0 - ? `These folders have no mozak.json. If your notes repo should have them, pull it; otherwise start each with mozak scope init (see the skill's references/bootstrap.md).` - : `mozak check --config ${inventoryPath} --scope ${failed[0]?.id ?? ""}`, + fix: inventoryFix(inventoryPath, failed.map((r) => ({ id: r.id, code: codeOf(r) }))), }); } } catch (err) { diff --git a/packages/cli/test/acceptance.test.ts b/packages/cli/test/acceptance.test.ts index 7252691..89c27c3 100644 --- a/packages/cli/test/acceptance.test.ts +++ b/packages/cli/test/acceptance.test.ts @@ -1,10 +1,11 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { spawn, spawnSync } from "node:child_process"; -import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, symlinkSync } from "node:fs"; +import { mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, symlinkSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { readScope } from "../../core/src/scope-store.ts"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR; if (!scratch) throw new Error("scratch directory required"); @@ -15,7 +16,7 @@ const ownerAt = "2026-10-12T08:00:00.000Z"; const content = (title = "Recover understanding", acceptance = "objective") => ({ title, purpose: "Preserve agreed meaning", outcomes: [{ id: "o1", statement: "Fresh context is sufficient", acceptance, criterion: "A new process reports the accepted meaning" }], constraints: [], nonGoals: ["Automatic coding authorization"], rationale: "Avoid lost decisions", questions: [], sources: [{ id: "source", locator: "synthetic:source", anchor: null, observedAt: ownerAt, version: "fixture-v1", limitations: ["Synthetic transport fixture, not a real pilot"] }] }); function fixture(initialize = true) { - const root = mkdtempSync(join(scratch!, "mozak-acceptance-")); roots.push(root); + const root = vaultTemp(join(scratch!, "mozak-acceptance-")); roots.push(root); const entries = ["one", "two"].map(id => { const path = join(root, id); mkdirSync(path); writeFileSync(join(path, "README.md"), "Owner README\n"); diff --git a/packages/cli/test/agent-ergonomics.test.ts b/packages/cli/test/agent-ergonomics.test.ts index d08c1c5..f1df230 100644 --- a/packages/cli/test/agent-ergonomics.test.ts +++ b/packages/cli/test/agent-ergonomics.test.ts @@ -1,12 +1,13 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, writeFileSync, readFileSync, rmSync, readdirSync } from "node:fs"; +import { writeFileSync, readFileSync, rmSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { execFileSync, spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; import { executeOperation } from "../../core/src/api.ts"; import { loadInventory } from "../../core/src/scope-index.ts"; import { handle } from "../../mcp/src/server.ts"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // Flag forms for decide, delete and observe, plan show, and the revise/decide warnings. // Synthetic scopes in isolated temp folders only; the owner provenance is a synthetic fixture value. @@ -20,7 +21,7 @@ const content = (title: string) => ({ }); function fixture() { - const root = mkdtempSync(join(process.env.TMPDIR ?? "/tmp", "mozak-ergonomics-")); roots.push(root); + const root = vaultTemp(join(process.env.TMPDIR ?? "/tmp", "mozak-ergonomics-")); roots.push(root); for (const name of ["README.md", "AGENTS.md"]) writeFileSync(join(root, name), "# Synthetic fixture\n"); const config = join(root, "inventory.json"); writeFileSync(config, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "fx", root }] })); diff --git a/packages/cli/test/cli.test.ts b/packages/cli/test/cli.test.ts index 19b2fcc..8fe0b5c 100644 --- a/packages/cli/test/cli.test.ts +++ b/packages/cli/test/cli.test.ts @@ -1,10 +1,11 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, realpathSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, realpathSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // Basic real-process tests for the built CLI. Each call is a subprocess running packages/cli/dist. // Scratch roots live under JCODE_SCRATCH_DIR (or TMPDIR) and are removed only by this file. @@ -51,7 +52,7 @@ function fixture(id = "sample"): { config: string; scopeRoot: string } { if (!existsSync(cliPath)) { throw new Error(`built CLI missing at ${cliPath}; run "npm run build" before the CLI tests`); } - const base = mkdtempSync(join(scratch, "mozak-cli-")); + const base = vaultTemp(join(scratch, "mozak-cli-")); roots.push(base); const scopeRoot = join(base, id); mkdirSync(scopeRoot, { recursive: true }); diff --git a/packages/cli/test/commit-flag.test.ts b/packages/cli/test/commit-flag.test.ts index 3d9f9a9..78010b1 100644 --- a/packages/cli/test/commit-flag.test.ts +++ b/packages/cli/test/commit-flag.test.ts @@ -1,11 +1,12 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { writeFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { execFileSync, spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; import { executeOperation } from "../../core/src/api.ts"; import { loadInventory } from "../../core/src/scope-index.ts"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // --commit on write routes: a local scope inside a git repo with an upstream gets its // mozak.json and mozak.md committed and pushed. Without --commit the output says "not committed". @@ -17,7 +18,7 @@ const env = { ...process.env, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTE const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, env, encoding: "utf8" }).trim(); function fixture(withUpstream: boolean) { - const base = mkdtempSync(join(process.env.TMPDIR ?? "/tmp", "mozak-commit-")); roots.push(base); + const base = vaultTemp(join(process.env.TMPDIR ?? "/tmp", "mozak-commit-")); roots.push(base); const origin = join(base, "origin.git"); const repo = join(base, "repo"); git(base, "init", "--quiet", "--bare", "-b", "main", origin); diff --git a/packages/cli/test/context-modes.test.ts b/packages/cli/test/context-modes.test.ts index fbbefd4..61ed399 100644 --- a/packages/cli/test/context-modes.test.ts +++ b/packages/cli/test/context-modes.test.ts @@ -1,6 +1,6 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, writeFileSync, readFileSync, rmSync, readdirSync } from "node:fs"; +import { writeFileSync, readFileSync, rmSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; @@ -9,6 +9,7 @@ import { loadInventory } from "../../core/src/scope-index.ts"; import { selectContext } from "../../core/src/context-selection.ts"; import { renderBridge } from "../../core/src/bridge.ts"; import { hashBytes } from "../../core/src/understanding.ts"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // Preapproved seams: executeOperation and built CLI/MCP. Fixtures are synthetic; no live inventory. const roots: string[] = []; @@ -16,7 +17,7 @@ after(() => roots.forEach(root => rmSync(root, { recursive: true, force: true }) const cliPath = fileURLToPath(new URL("../dist/index.js", import.meta.url)); const content = { title: "Synthetic compact context", purpose: "Recover bounded work", outcomes: [{ id: "out", statement: "Synthetic check passes", acceptance: "objective", criterion: "Fixture passes" }], constraints: [], nonGoals: [], rationale: "Fixture only", questions: [], sources: [] }; function fixture(title = content.title) { - const root = mkdtempSync(join(process.env.TMPDIR!, "mozak-context-modes-")); roots.push(root); + const root = vaultTemp(join(process.env.TMPDIR!, "mozak-context-modes-")); roots.push(root); for (const name of ["README.md", "AGENTS.md"]) writeFileSync(join(root, name), "# Synthetic fixture\n"); const config = join(root, "inventory.json"); writeFileSync(config, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "fixture", root }] })); @@ -31,7 +32,8 @@ function fixture(title = content.title) { change("propose", { planId: "alpha", content: { ...content, title } }); return { root, config, inv, run, change }; } -const files = (root: string) => readdirSync(root).sort().map(name => [name, readFileSync(join(root, name))]); +// The scope's own files. The temp root is also the vault, so its .obsidian folder is not part of the snapshot. +const files = (root: string) => readdirSync(root).filter(name => name !== ".obsidian").sort().map(name => [name, readFileSync(join(root, name))]); function decide(w: ReturnType, purpose: string) { const review = w.run("review", { plan: "alpha", purpose }).data.review as any; w.change(purpose, { planId: "alpha", revisionId: review.revisionId, reviewDigest: review.reviewDigest, diff --git a/packages/cli/test/cwd-scope.test.ts b/packages/cli/test/cwd-scope.test.ts index 2a60817..240436e 100644 --- a/packages/cli/test/cwd-scope.test.ts +++ b/packages/cli/test/cwd-scope.test.ts @@ -1,11 +1,12 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { execFileSync, spawn } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { initScopeState, loadInventory, repoKey } from "@mozak/core"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // Real-process tests: the built CLI run from inside a plain git clone finds its scope from the clone's origin, // so an agent working in ~/Downloads/ reads the same vault plans. Writes still need --scope. @@ -32,7 +33,7 @@ function run(args: string[], cwd: string): Promise<{ code: number; out: string; function fixture() { assert.ok(existsSync(cliPath), "run npm run build first"); - const base = mkdtempSync(join(scratch, "mozak-cwd-")); + const base = vaultTemp(join(scratch, "mozak-cwd-")); roots.push(base); const bare = join(base, "tool.git"); const seed = join(base, "seed"); diff --git a/packages/cli/test/doctor.test.ts b/packages/cli/test/doctor.test.ts index 767129b..33f7a7b 100644 --- a/packages/cli/test/doctor.test.ts +++ b/packages/cli/test/doctor.test.ts @@ -5,6 +5,7 @@ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, re import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { inventoryFix } from "../src/doctor.ts"; // `mozak doctor` against an isolated HOME: a real installation, made by the real installer, then broken on purpose. @@ -126,9 +127,9 @@ test("doctor flags a changed installation, an outdated plugin copy (fixed by --f test("doctor on a restore: a correct MCP setting naming a missing wrapper points at --fix, and its inventory is still checked", () => { const f = fixture(); - mkdirSync(join(f.notes, "proj")); - writeFileSync(join(f.notes, "proj", "README.md"), "# p\n"); - writeFileSync(f.inventory, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "proj", root: "./proj" }] })); + mkdirSync(join(f.vault, "proj")); + writeFileSync(join(f.vault, "proj", "README.md"), "# p\n"); + writeFileSync(f.inventory, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "proj", root: "./vault/proj" }] })); const wrapper = join(f.home, ".local/bin/mozak-mcp"); writeFileSync(join(f.home, ".claude.json"), JSON.stringify({ mcpServers: { mozak: { command: wrapper, args: ["--config", f.inventory] } } })); let r = doctor(f); @@ -142,6 +143,26 @@ test("doctor on a restore: a correct MCP setting naming a missing wrapper points assert.equal(r.by("mcp-claude")?.state, "ok", JSON.stringify(r.by("mcp-claude"))); }); +test("doctor reports a scope outside a vault and names mozak scope move", () => { + const f = fixture(); + mkdirSync(join(f.notes, "code")); + writeFileSync(f.inventory, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "code", root: "./code" }] })); + const r = doctor(f, ["--config", f.inventory]); + assert.equal(r.by("inventory")?.state, "fail"); + assert.match(r.by("inventory")!.message, /code \(scope-outside-vault\)/); + assert.match(r.by("inventory")!.fix!, /mozak scope move --scope code --to /); +}); + +test("inventoryFix: scope move for scopes outside a vault or legacy entries first, then scope init, then check", () => { + const inv = "/v/mozak-inventory.json"; + assert.match(inventoryFix(inv, [{ id: "a", code: "scope-uninitialized" }, { id: "b", code: "scope-outside-vault" }]), /^Move each into a vault folder: mozak scope move --scope b --to .* --config \/v\/mozak-inventory\.json \(see docs\/installation\.md, Moving to 0\.6\.0\)$/); + assert.match(inventoryFix(inv, [{ id: "web", code: "legacy-repo-scope" }]), /mozak scope move --scope web /); + assert.match(inventoryFix(inv, [{ id: "a", code: "scope-uninitialized" }, { id: "b", code: "scope-uninitialized" }]), /^These folders have no mozak\.json\./); + assert.equal(inventoryFix(inv, [{ id: "a", code: "scope-uninitialized" }, { id: "b", code: "scope-root-missing" }]), "mozak check --config /v/mozak-inventory.json --scope a"); + assert.equal(inventoryFix(inv, [{ id: "c" }]), "mozak check --config /v/mozak-inventory.json --scope c"); + assert.equal(inventoryFix(inv, []), "mozak check --config /v/mozak-inventory.json --scope "); +}); + test("versions agree across the root, every package, the plugin manifest and the installer", () => { const read = (rel: string) => JSON.parse(readFileSync(join(repo, rel), "utf8")); const version = read("package.json").version as string; diff --git a/packages/cli/test/package2-history.test.ts b/packages/cli/test/package2-history.test.ts index f49b2f1..2bb4811 100644 --- a/packages/cli/test/package2-history.test.ts +++ b/packages/cli/test/package2-history.test.ts @@ -1,11 +1,12 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { mkdirSync, writeFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { readScope } from "../../core/src/scope-store.ts"; import { loadInventory } from "../../core/src/scope-index.ts"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // B03 through the real built CLI. Clarification checkpoint: null-ID questions get core-assigned IDs, answers append // by ID, a settled question reopens only with a reason, and the answer prefix and reopening history are kept. @@ -31,7 +32,7 @@ const content = { }; function fixture() { - const root = mkdtempSync(join(scratch!, "mozak-history-")); + const root = vaultTemp(join(scratch!, "mozak-history-")); roots.push(root); const path = join(root, "one"); mkdirSync(path); diff --git a/packages/cli/test/package2-mixed-rows.test.ts b/packages/cli/test/package2-mixed-rows.test.ts index 07efa7b..e5999a8 100644 --- a/packages/cli/test/package2-mixed-rows.test.ts +++ b/packages/cli/test/package2-mixed-rows.test.ts @@ -1,11 +1,12 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { mkdirSync, writeFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { readScope } from "../../core/src/scope-store.ts"; import { loadInventory } from "../../core/src/scope-index.ts"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // Mixed awaiting rows through the real built CLI. One plan shows direction, outcome, and implementation rows at once. // Each awaiting row carries its explicit purpose label, and titles stay visible. Every owner reference is a synthetic @@ -31,7 +32,7 @@ const content = (title: string) => ({ }); function fixture() { - const root = mkdtempSync(join(scratch!, "mozak-mixed-")); + const root = vaultTemp(join(scratch!, "mozak-mixed-")); roots.push(root); const path = join(root, "one"); mkdirSync(path); diff --git a/packages/cli/test/package2-parity.test.ts b/packages/cli/test/package2-parity.test.ts index b5acbad..819469b 100644 --- a/packages/cli/test/package2-parity.test.ts +++ b/packages/cli/test/package2-parity.test.ts @@ -1,12 +1,13 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { spawn, spawnSync, type ChildProcess } from "node:child_process"; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync, unlinkSync, readFileSync, copyFileSync } from "node:fs"; +import { mkdirSync, writeFileSync, rmSync, unlinkSync, readFileSync, copyFileSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { readScope } from "../../core/src/scope-store.ts"; import { loadInventory } from "../../core/src/scope-index.ts"; import { discussionDigest } from "../../core/src/understanding.ts"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // B11 parity over the full owner path. Owner steps go through the BUILT CLI. Each state is then compared between // the built CLI and a FRESH built MCP child (packages/mcp/dist/index.js, not src). Every owner reference is an @@ -31,7 +32,7 @@ const OWNER = { const OWN_ANSWER = (summary: string) => ({ summary, basis: "owner", ownerRef: "synthetic-owner:fixture-clarification", ownerMessageAt: "2026-10-12T08:02:00.000Z", evidence: [] }); function fixture() { - const root = mkdtempSync(join(scratch!, "mozak-parity-")); + const root = vaultTemp(join(scratch!, "mozak-parity-")); roots.push(root); const path = join(root, "one"); mkdirSync(path); diff --git a/packages/cli/test/package2-protected.test.ts b/packages/cli/test/package2-protected.test.ts index 4c14bef..bbc98a5 100644 --- a/packages/cli/test/package2-protected.test.ts +++ b/packages/cli/test/package2-protected.test.ts @@ -1,9 +1,10 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"; +import { mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // Nested protected-field refusals on the Package 2 routes (discussion save, spec attach). // Each attack puts one protected or unknown field inside an otherwise valid envelope. Each case asserts the exact @@ -30,7 +31,7 @@ const content = { }; function fixture() { - const root = mkdtempSync(join(scratch!, "mozak-protected-")); + const root = vaultTemp(join(scratch!, "mozak-protected-")); roots.push(root); const path = join(root, "one"); mkdirSync(path); diff --git a/packages/cli/test/package2-rows.test.ts b/packages/cli/test/package2-rows.test.ts index abd41da..73e8ce7 100644 --- a/packages/cli/test/package2-rows.test.ts +++ b/packages/cli/test/package2-rows.test.ts @@ -1,9 +1,10 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { mkdirSync, writeFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // Real built-CLI test for human plan rows. One plan can appear as direction, outcome, and implementation // awaiting rows at once. Each row must carry its own explicit purpose label so the rows are not ambiguous. @@ -28,7 +29,7 @@ const content = (title: string) => ({ }); function fixture() { - const root = mkdtempSync(join(scratch!, "mozak-rows-")); + const root = vaultTemp(join(scratch!, "mozak-rows-")); roots.push(root); const path = join(root, "one"); mkdirSync(path); diff --git a/packages/cli/test/render.test.ts b/packages/cli/test/render.test.ts index 8fa45de..981209b 100644 --- a/packages/cli/test/render.test.ts +++ b/packages/cli/test/render.test.ts @@ -1,7 +1,7 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, realpathSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, realpathSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -10,6 +10,7 @@ import { initScopeState, mutateScope, readScope, renderProjection } from "../../ import { renderBridgeLegacy } from "../../core/src/bridge.ts"; import { executeOperation } from "../../core/src/api.ts"; import { loadInventory } from "../../core/src/scope-index.ts"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // Projection-only render route. Synthetic scopes in scratch roots only; never a real inventory. const here = fileURLToPath(new URL(".", import.meta.url)); @@ -90,7 +91,7 @@ test("CLI: pending-order compatibility never repairs hand edits", () => { }); function world(ids = ["alpha", "beta"]) { - const base = mkdtempSync(join(scratch, "mozak-render-")); + const base = vaultTemp(join(scratch, "mozak-render-")); roots.push(base); for (const id of ids) { mkdirSync(join(base, id)); diff --git a/packages/cli/test/scope-move-cli.test.ts b/packages/cli/test/scope-move-cli.test.ts index e4e3fc9..1df9c35 100644 --- a/packages/cli/test/scope-move-cli.test.ts +++ b/packages/cli/test/scope-move-cli.test.ts @@ -49,7 +49,7 @@ test("CLI: scope move needs the owner flags and exactly one of --to or --drop, a const missing = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--to", "vault/alpha"]); assert.equal(missing.code, 2); assert.match(missing.err, /missing --owner-ref/); - const outside = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--to", "elsewhere", ...OWNER]); + const outside = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--to", "../../elsewhere", ...OWNER]); assert.equal(outside.code, 2); assert.equal(JSON.parse(outside.out).status, "move-target-outside-vault"); const both = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--to", "vault/x", "--drop", ...OWNER]); diff --git a/packages/cli/test/scopes.test.ts b/packages/cli/test/scopes.test.ts index e9cd64e..d79dcad 100644 --- a/packages/cli/test/scopes.test.ts +++ b/packages/cli/test/scopes.test.ts @@ -1,10 +1,11 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; -import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, realpathSync } from "node:fs"; +import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, realpathSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // Real-process tests for the read-only `scopes` index. Each call is a subprocess running packages/cli/dist. const here = fileURLToPath(new URL(".", import.meta.url)); @@ -52,7 +53,7 @@ async function mutate(config: string, scope: string, route: string[], action: st /** Inventory with: alpha (initialised, one open plan), beta (initialised, no plan), gamma (not initialised), delta (root missing). */ async function fixture() { if (!existsSync(cliPath)) throw new Error(`built CLI missing at ${cliPath}; run "npm run build" first`); - const base = mkdtempSync(join(scratch, "mozak-scopes-")); + const base = vaultTemp(join(scratch, "mozak-scopes-")); roots.push(base); const entries: { id: string; root: string }[] = []; for (const id of ["alpha", "beta", "gamma"]) { diff --git a/packages/core/src/api.ts b/packages/core/src/api.ts index 2cb1073..e3055ad 100644 --- a/packages/core/src/api.ts +++ b/packages/core/src/api.ts @@ -1065,7 +1065,7 @@ function renderOp(inv: ScopeInventory, a: Record): OperationOut const rows = targets.map((entry) => { if (entry.remote && entry.remote.plansMode === "repo") return { scope: entry.id, result: "remote-skipped", exitCode: 0 }; try { - const { result, outcome } = renderProjection(entry); + const { result, outcome } = renderProjection(resolveScope(inv, entry.id)); return { scope: entry.id, result, exitCode: resultExit(outcome), code: outcome.status, projectionUpdated: outcome.projectionUpdated, projectionStatus: outcome.projectionStatus, ...(outcome.issues.length ? { issues: outcome.issues } : {}) }; } catch (err) { if (!(err instanceof DomainError)) throw err; @@ -1101,7 +1101,7 @@ function renameFilesOp(inv: ScopeInventory, a: Record): Operati const rows = targets.map((entry) => { if (entry.remote && entry.remote.plansMode === "repo") return { scope: entry.id, result: "remote-skipped", exitCode: 0 }; try { - const { result, outcome } = renameScopeFiles(entry); + const { result, outcome } = renameScopeFiles(resolveScope(inv, entry.id)); return { scope: entry.id, result, exitCode: resultExit(outcome), code: outcome.status, ...(outcome.issues.length ? { issues: outcome.issues } : {}) }; } catch (err) { if (!(err instanceof DomainError)) throw err; @@ -1135,7 +1135,7 @@ function reportScopes(inv: ScopeInventory, operation: string, o: Record !s.remote || s.remote.plansMode === "vault"); + return scopes.filter((s) => !s.refused && (!s.remote || s.remote.plansMode === "vault")); } /** diff --git a/packages/core/src/locators.ts b/packages/core/src/locators.ts index bd6f539..a030d65 100644 --- a/packages/core/src/locators.ts +++ b/packages/core/src/locators.ts @@ -62,7 +62,7 @@ const inside = (path: string, dir: string) => path === dir || path.startsWith(di export function defaultIndexRoots(inv: ScopeInventory): LocatorRoot[] { const out = new Map(); for (const entry of inv.scopes) { - if (entry.remote && entry.remote.plansMode === "repo") continue; + if (entry.refused || (entry.remote && entry.remote.plansMode === "repo")) continue; const root = realOrSelf(entry.root); const repo = findRepoRoot(root); if (!repo || repo === root) continue; diff --git a/packages/core/src/plans-index.ts b/packages/core/src/plans-index.ts index 623b554..8c68749 100644 --- a/packages/core/src/plans-index.ts +++ b/packages/core/src/plans-index.ts @@ -10,7 +10,7 @@ import { replaceFileDurable } from "./durable.ts"; import { DomainError } from "./errors.ts"; import { findRepoRoot } from "./notes.ts"; import { realOrSelf } from "./paths.ts"; -import type { ScopeInventory } from "./scope-index.ts"; +import { resolveScope, type ScopeInventory } from "./scope-index.ts"; import { readScopeQuiet } from "./scope-store.ts"; import type { ScopeState } from "./understanding.ts"; @@ -73,7 +73,7 @@ export function plansIndex(inv: ScopeInventory, opts: { write: boolean }): Plans const folder = relative(repo, realOrSelf(entry.root)).split(sep).join("/") || "."; let state: ScopeState | null = null; let code: string | undefined; - try { state = readScopeQuiet(entry).state; } + try { state = readScopeQuiet(resolveScope(inv, entry.id)).state; } catch (err) { if (!(err instanceof DomainError)) throw err; code = err.code; } const list = byRepo.get(repo) ?? []; list.push({ id: entry.id, folder, state, ...(code ? { code } : {}) }); diff --git a/packages/core/src/scope-index.ts b/packages/core/src/scope-index.ts index 1d77cae..e28633e 100644 --- a/packages/core/src/scope-index.ts +++ b/packages/core/src/scope-index.ts @@ -3,6 +3,7 @@ import { existsSync, lstatSync, readFileSync, realpathSync, statSync, type Stats import { basename, dirname, join, resolve } from "node:path"; import { DomainError } from "./errors.ts"; import { cacheRootFor, parseRemoteSpec, readRemoteMeta, CACHE_DIR, DEFAULT_REF, REF_PATTERN, type RemoteInfo } from "./remote-meta.ts"; +import { vaultOf } from "./vault-config.ts"; /** Pilot-local explicit inventory. Never a global registration or a directory scan. */ export const INVENTORY_FORMAT_V2 = "mozak.local/v2" as const; @@ -20,6 +21,11 @@ export interface ScopeEntry { remote?: RemoteInfo; /** Diagnostic only: reserved x settings were ignored at inventory or selected-entry level. */ inventoryExtensionsIgnored?: true; + /** + * Set when the entry is kept in the inventory but every route refuses it (for example a root outside any vault). + * `resolveScope` throws it. `mozak scope move` still reads the entry, so the owner can move it. + */ + refused?: { code: string; message: string }; } export interface ScopeInventory { @@ -229,6 +235,8 @@ export function loadInventory(configPath: string): ScopeInventory { seenRoots.set(canonical, id); const scope: ScopeEntry = remote ? { id, root: canonical, remote } : { id, root: canonical }; if ("x" in raw || "x" in entry) scope.inventoryExtensionsIgnored = true; + const refused = vaultRule(id, canonical); + if (refused) scope.refused = refused; scopes.push(scope); } @@ -240,18 +248,35 @@ export function loadInventory(configPath: string): ScopeInventory { } /** - * Select exactly one inventoried scope and verify its root is still the same directory that was - * recorded at load. Reads only; nothing is created or modified. + * The vault rule: a scope root must sit at or below a folder that has a .obsidian folder. An entry that breaks it is + * kept (so other scopes keep working and `scope move` can read it) and refused by every route. */ -export function resolveScope(inv: ScopeInventory, id: string): ScopeEntry { +function vaultRule(id: string, root: string): ScopeEntry["refused"] | undefined { + if (vaultOf(root) !== null) return undefined; + return { + code: "scope-outside-vault", + message: `scope "${id}" is not inside an Obsidian vault (${root} has no folder with .obsidian above it). mozak keeps plans in vaults only: run mozak scope move --scope ${id} --to --owner-ref REF --owner-message-at ISO --reason TEXT`, + }; +} + +/** The one entry with this id, unless it is missing, listed twice or refused (outside a vault, legacy). */ +function selectEntry(inv: ScopeInventory, id: string): ScopeEntry { const matches = inv.scopes.filter((scope) => scope.id === id); if (matches.length === 0) { throw new DomainError("scope-not-found", `no scope "${id}" in the inventory; run mozak scopes (MCP mozak_scopes) to list the scope ids`); } - const entry = matches[0]; - if (matches.length > 1 || entry === undefined) { - throw new DomainError("scope-ambiguous", `scope "${id}" is listed more than once`); - } + if (matches.length > 1) throw new DomainError("scope-ambiguous", `scope "${id}" is listed more than once`); + const entry = matches[0]!; + if (entry.refused) throw new DomainError(entry.refused.code, entry.refused.message); + return entry; +} + +/** + * Select exactly one inventoried scope and verify its root is still the same directory that was + * recorded at load. Reads only; nothing is created or modified. + */ +export function resolveScope(inv: ScopeInventory, id: string): ScopeEntry { + const entry = selectEntry(inv, id); let real: string; let stats: Stats; diff --git a/packages/core/test/annotations-fixture.ts b/packages/core/test/annotations-fixture.ts index e3fddcf..481691d 100644 --- a/packages/core/test/annotations-fixture.ts +++ b/packages/core/test/annotations-fixture.ts @@ -1,6 +1,6 @@ // Synthetic temp scopes for annotation tests. Never touches a real inventory or vault. import { execFileSync } from "node:child_process"; -import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { initScopeState, mutateScope, readScope } from "../src/scope-store.ts"; @@ -8,6 +8,7 @@ import { reviewShow } from "../src/review.ts"; import { executeOperation } from "../src/api.ts"; import { loadInventory } from "../src/scope-index.ts"; import { readAnnotations } from "../src/annotations.ts"; +import { vaultTemp } from "./vault-temp.ts"; export const NOW = "2026-10-20T09:00:00.000Z"; const roots: string[] = []; @@ -28,7 +29,7 @@ export const content = (id: string, spec: PlanSpec = {}) => ({ }); export function world(scopeIds: string[] = ["alpha"], options: { git?: boolean; settings?: Record; annotations?: boolean } = {}) { - const base = mkdtempSync(join(process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(), "mozak-annot-")); + const base = vaultTemp(join(process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(), "mozak-annot-")); roots.push(base); const entries: Record = {}; for (const id of scopeIds) { diff --git a/packages/core/test/delete.test.ts b/packages/core/test/delete.test.ts index 0562317..70081ff 100644 --- a/packages/core/test/delete.test.ts +++ b/packages/core/test/delete.test.ts @@ -3,15 +3,16 @@ // cannot be proposed again. import test from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, readFileSync, writeFileSync, mkdirSync } from "node:fs"; +import { readFileSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { deletePlans, executeOperation, initScopeState, loadInventory, readScope, resolveScope, withoutPlans, deletedRecord } from "../src/index.ts"; +import { vaultTemp } from "./vault-temp.ts"; const OWNER_AT = "2026-10-22T08:00:00.000Z"; function scope(): { config: string; root: string } { - const base = mkdtempSync(join(tmpdir(), "mozak-delete-")); + const base = vaultTemp(join(tmpdir(), "mozak-delete-")); const root = join(base, "alpha"); mkdirSync(root); writeFileSync(join(root, "README.md"), "# Alpha\n"); diff --git a/packages/core/test/durable-write.test.ts b/packages/core/test/durable-write.test.ts index 911d5ad..c7fbefc 100644 --- a/packages/core/test/durable-write.test.ts +++ b/packages/core/test/durable-write.test.ts @@ -4,13 +4,14 @@ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSyn import { tmpdir } from "node:os"; import { join } from "node:path"; import { durableStats, executeOperation, initScopeState, leftoverTempFiles, loadInventory, replaceFileDurable, writeRemoteMeta } from "../src/index.ts"; +import { vaultTemp } from "./vault-temp.ts"; const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); const made: string[] = []; after(() => { for (const d of made) { if (!d.includes("/mozak-durable-")) throw new Error(d); rmSync(d, { recursive: true, force: true }); } }); function scope() { - const base = mkdtempSync(join(scratch, "mozak-durable-")); made.push(base); + const base = vaultTemp(join(scratch, "mozak-durable-")); made.push(base); const root = join(base, "s"); mkdirSync(root); writeFileSync(join(root, "README.md"), "# r\n"); writeFileSync(join(root, "AGENTS.md"), "# a\n"); const inv = join(base, "inventory.json"); diff --git a/packages/core/test/error-messages.test.ts b/packages/core/test/error-messages.test.ts index ad5e03d..3657da7 100644 --- a/packages/core/test/error-messages.test.ts +++ b/packages/core/test/error-messages.test.ts @@ -2,12 +2,13 @@ // Synthetic scopes in temp dirs only. import { test, after } from "node:test"; import assert from "node:assert/strict"; -import { appendFileSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { executeOperation } from "../src/api.ts"; import { DomainError } from "../src/errors.ts"; import { loadInventory, resolveScope } from "../src/scope-index.ts"; import { initScopeState, mutateScope, readScope } from "../src/scope-store.ts"; +import { vaultTemp } from "./vault-temp.ts"; const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR; if (!scratch) throw new Error("tests require JCODE_SCRATCH_DIR or TMPDIR"); @@ -23,7 +24,7 @@ const content = (title: string) => ({ /** One inventory with the given scope ids, each initialized in its own folder. */ function world(ids = ["alpha"]) { - const base = mkdtempSync(join(scratch!, "mozak-errmsg-")); + const base = vaultTemp(join(scratch!, "mozak-errmsg-")); roots.push(base); const scopes = ids.map((id) => { const root = join(base, id); diff --git a/packages/core/test/file-names.test.ts b/packages/core/test/file-names.test.ts index a026335..b2ae56b 100644 --- a/packages/core/test/file-names.test.ts +++ b/packages/core/test/file-names.test.ts @@ -2,13 +2,14 @@ // and `rename-files` moves an old scope to the new names without changing its plan. import test from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, readFileSync, readdirSync, renameSync, writeFileSync, mkdirSync } from "node:fs"; +import { readFileSync, readdirSync, renameSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { executeOperation, initScopeState, loadInventory, readScope, renameScopeFiles, resolveScope, scopeFileName } from "../src/index.ts"; +import { vaultTemp } from "./vault-temp.ts"; function scope(): { config: string; root: string; id: string } { - const base = mkdtempSync(join(tmpdir(), "mozak-names-")); + const base = vaultTemp(join(tmpdir(), "mozak-names-")); const root = join(base, "alpha"); mkdirSync(root); writeFileSync(join(root, "README.md"), "# Alpha\n"); diff --git a/packages/core/test/handoff-store.test.ts b/packages/core/test/handoff-store.test.ts index 411dc08..8894872 100644 --- a/packages/core/test/handoff-store.test.ts +++ b/packages/core/test/handoff-store.test.ts @@ -1,6 +1,6 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, writeFileSync, readFileSync, mkdirSync, unlinkSync, rmSync, existsSync } from "node:fs"; +import { writeFileSync, readFileSync, mkdirSync, unlinkSync, rmSync, existsSync } from "node:fs"; import { spawnSync } from "node:child_process"; import { join } from "node:path"; import { initScopeState, readScope, readScopeView, mutateScope, repairProjection } from "../src/scope-store.ts"; @@ -8,6 +8,7 @@ import { contextView, reviewShow } from "../src/review.ts"; import { loadInventory } from "../src/scope-index.ts"; import { executeOperation } from "../src/api.ts"; import { discussionDigest } from "../src/understanding.ts"; +import { vaultTemp } from "./vault-temp.ts"; const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR; if (!scratch) throw new Error("tests require JCODE_SCRATCH_DIR or TMPDIR"); @@ -16,7 +17,7 @@ after(() => { for (const root of roots) rmSync(root, { recursive: true, force: t const content = { title: "Bounded formatter", purpose: "Recover exact bounded work", outcomes: [{ id: "out", statement: "String formatter works", acceptance: "objective", criterion: "Local unit tests pass" }], constraints: [], nonGoals: [], rationale: "No repeated interview", questions: [], sources: [] }; const bounds = { summary: "Implement formatter only", allowedPaths: ["src/format.ts", "test/format.test.ts"], excludedActions: ["network", "installation"], outcomeChecks: [{ outcomeId: "out", criterion: "Local formatter test passes" }], limitations: ["Synthetic automated owner references, not live acceptance"] }; function world() { - const root = mkdtempSync(join(scratch!, "mozak-handoff-")); roots.push(root); + const root = vaultTemp(join(scratch!, "mozak-handoff-")); roots.push(root); writeFileSync(join(root, "README.md"), "Fixture README\n"); writeFileSync(join(root, "AGENTS.md"), "Fixture instructions\n"); const entry = { id: "scope", root }; const inventoryPath = join(root, "inventory.json"); diff --git a/packages/core/test/remote.test.ts b/packages/core/test/remote.test.ts index 28d7013..3683913 100644 --- a/packages/core/test/remote.test.ts +++ b/packages/core/test/remote.test.ts @@ -1,10 +1,11 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { executeOperation, initScopeState, loadInventory, parseRemoteSpec, writeRemoteMeta, readRemoteMeta } from "../src/index.ts"; +import { vaultTemp } from "./vault-temp.ts"; const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); const made: string[] = []; @@ -21,7 +22,7 @@ const content = (title: string) => ({ /** Bare origin with an initialised scope plus a decoy file that must never be checked out. */ function fixture() { - const base = mkdtempSync(join(scratch, "mozak-remote-")); + const base = vaultTemp(join(scratch, "mozak-remote-")); made.push(base); const bare = join(base, "origin.git"); const seed = join(base, "seed"); @@ -40,7 +41,7 @@ function fixture() { const exec = (inv: string, op: string, args: unknown, actor: "agent" | "owner" = "agent") => executeOperation(loadInventory(inv), op, args, actor); test("inventory: remote entry validation stays strict, v2 still accepted", () => { - const base = mkdtempSync(join(scratch, "mozak-remote-")); made.push(base); + const base = vaultTemp(join(scratch, "mozak-remote-")); made.push(base); const inv = join(base, "i.json"); const bad = (scopes: unknown[], format = "mozak.local/v3") => { writeFileSync(inv, JSON.stringify({ format, scopes })); return () => loadInventory(inv); }; assert.throws(bad([{ id: "a", remote: "github:o/r", root: "x" }]), /exactly one/); @@ -177,7 +178,7 @@ test("pull makes a full clone, reads prefer it, and an existing foreign destinat }); test("not a scope: remote without mozak.json fails clearly", () => { - const base = mkdtempSync(join(scratch, "mozak-remote-")); made.push(base); + const base = vaultTemp(join(scratch, "mozak-remote-")); made.push(base); const bare = join(base, "o.git"), seed = join(base, "s"); g(base, "init", "--bare", "-b", "main", bare); mkdirSync(seed); g(seed, "init", "-b", "main"); writeFileSync(join(seed, "README.md"), "x"); diff --git a/packages/core/test/s2-offline.test.ts b/packages/core/test/s2-offline.test.ts index f23bf66..75d8895 100644 --- a/packages/core/test/s2-offline.test.ts +++ b/packages/core/test/s2-offline.test.ts @@ -3,10 +3,11 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { executeOperation, initScopeState, loadInventory, readRemoteMeta, writeRemoteMeta } from "../src/index.ts"; +import { vaultTemp } from "./vault-temp.ts"; const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); const made: string[] = []; @@ -16,7 +17,7 @@ const g = (cwd: string, ...args: string[]) => const init = (id: string, root: string) => initScopeState({ id, root }, { operationId: `init-${id}`, scopeId: id, kind: "project", title: id, expectedAbsent: { graph: true, bridge: true }, ownerRef: "host:t", ownerMessageAt: "2026-10-12T08:50:00.000Z" }); function fixture() { - const base = mkdtempSync(join(scratch, "mozak-s2off-")); + const base = vaultTemp(join(scratch, "mozak-s2off-")); made.push(base); const bare = join(base, "origin.git"); const seed = join(base, "seed"); diff --git a/packages/core/test/s2-sync.test.ts b/packages/core/test/s2-sync.test.ts index 5d70997..6e906c5 100644 --- a/packages/core/test/s2-sync.test.ts +++ b/packages/core/test/s2-sync.test.ts @@ -3,11 +3,12 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { executeOperation, initScopeState, loadInventory, readScope } from "../src/index.ts"; import { syncLocal } from "../src/local-sync.ts"; +import { vaultTemp } from "./vault-temp.ts"; const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); const made: string[] = []; @@ -17,7 +18,7 @@ const g = (cwd: string, ...args: string[]) => const content = (title: string) => ({ constraints: [], nonGoals: [], outcomes: [{ acceptance: "objective", criterion: "c", id: "o", statement: "s" }], purpose: "p", questions: [], rationale: "r", sources: [], title }); function fixture() { - const base = mkdtempSync(join(scratch, "mozak-s2sync-")); + const base = vaultTemp(join(scratch, "mozak-s2sync-")); made.push(base); const bare = join(base, "vault.git"); const seed = join(base, "seed"); @@ -121,7 +122,7 @@ test("sync refuses while any scope lock in the repo is held, releases what it to }); test("sync of a local scope outside git reports not-in-git", () => { - const base = mkdtempSync(join(scratch, "mozak-s2sync-")); + const base = vaultTemp(join(scratch, "mozak-s2sync-")); made.push(base); const root = join(base, "plain"); mkdirSync(root); diff --git a/packages/core/test/s6-fixture.ts b/packages/core/test/s6-fixture.ts index b35c2f6..db47056 100644 --- a/packages/core/test/s6-fixture.ts +++ b/packages/core/test/s6-fixture.ts @@ -2,13 +2,14 @@ // Layout: /vault is one git repo with scopes under personal/ and research/; /company is a second git // repo whose scope sits at the repo root, like a shared company vault. import { execFileSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { initScopeState, mutateScope, readScope } from "../src/scope-store.ts"; import { reviewShow } from "../src/review.ts"; import { executeOperation } from "../src/api.ts"; import { loadInventory } from "../src/scope-index.ts"; +import { vaultTemp } from "./vault-temp.ts"; export const NOW = "2026-10-20T09:00:00.000Z"; const roots: string[] = []; @@ -35,7 +36,7 @@ export const s6content = (id: string, spec: S6PlanSpec = {}) => ({ /** scopes: id -> folder relative to base (for example "vault/personal/p"). */ export function s6world(scopes: Record, options: { repos?: string[]; settings?: unknown } = {}) { - const base = mkdtempSync(join(process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(), "mozak-s6-")); + const base = vaultTemp(join(process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(), "mozak-s6-")); roots.push(base); for (const repo of options.repos ?? []) { mkdirSync(join(base, repo), { recursive: true }); diff --git a/packages/core/test/scope-index.test.ts b/packages/core/test/scope-index.test.ts index d1eddfd..2c747d6 100644 --- a/packages/core/test/scope-index.test.ts +++ b/packages/core/test/scope-index.test.ts @@ -3,7 +3,6 @@ import assert from "node:assert/strict"; import { existsSync, mkdirSync, - mkdtempSync, readdirSync, realpathSync, rmSync, @@ -14,6 +13,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { DomainError } from "../src/errors.ts"; import { assertScopeFiles, loadInventory, resolveScope } from "../src/scope-index.ts"; +import { vaultTemp } from "./vault-temp.ts"; const workspaces: string[] = []; @@ -23,7 +23,7 @@ after(() => { function workspace(): string { const base = process.env.JCODE_SCRATCH_DIR ?? tmpdir(); - const root = mkdtempSync(join(base, "mozak-scope-index-")); + const root = vaultTemp(join(base, "mozak-scope-index-")); workspaces.push(root); return root; } diff --git a/packages/core/test/scope-move.test.ts b/packages/core/test/scope-move.test.ts index 218de30..b241f85 100644 --- a/packages/core/test/scope-move.test.ts +++ b/packages/core/test/scope-move.test.ts @@ -10,7 +10,7 @@ import { content, NOW } from "./annotations-fixture.ts"; import { executeOperation } from "../src/api.ts"; import { loadInventory } from "../src/scope-index.ts"; import { initScopeState, mutateScope, readScope } from "../src/scope-store.ts"; -import { reviewShow } from "../src/review.ts"; +import { reviewRows, reviewShow } from "../src/review.ts"; import { moveScope, renderMove, scopeMoveOutput } from "../src/scope-move.ts"; const made: string[] = []; @@ -52,7 +52,8 @@ function setup(extraEntries: unknown[] = []) { return { base, vault, config, text }; } const raw = (config: string) => JSON.parse(readFileSync(config, "utf8")); -const plansOf = (config: string, scope: string) => JSON.stringify(executeOperation(loadInventory(config), "plans", { scope, includeRejected: true, limit: 100 }).data.groups); +/** Plan rows of the scope as `plans` groups them, read straight from a folder (the source is outside the vault). */ +const plansAt = (id: string, root: string) => JSON.stringify(reviewRows(readScope({ id, root: realpathSync(root) }).state, true)); /** check after the move: no findings except the x-key notice this fixture's inventory causes on purpose. */ function assertClean(config: string, scope: string): void { const out = executeOperation(loadInventory(config), "check", { scope }); @@ -63,7 +64,7 @@ function assertClean(config: string, scope: string): void { test("move: a local scope outside the vault is copied, verified and the entry rewritten; plans and receipts unchanged", () => { const f = setup(); const src = join(f.base, "code", "proj"); - const before = { json: sha(join(src, "mozak.json")), md: sha(join(src, "mozak.md")), plans: plansOf(f.config, "proj"), receipts: readScope({ id: "proj", root: realpathSync(src) }).state.receipts }; + const before = { json: sha(join(src, "mozak.json")), md: sha(join(src, "mozak.md")), plans: plansAt("proj", src), receipts: readScope({ id: "proj", root: realpathSync(src) }).state.receipts }; const out = moveScope(f.config, { scope: "proj", to: "vault/projects/proj", ...OWNER }); assert.equal(out.status, "ok"); assert.equal(out.changed, true); @@ -81,7 +82,9 @@ test("move: a local scope outside the vault is copied, verified and the entry re assert.deepEqual(doc.scopes[1], { id: "proj", root: "vault/projects/proj", focus: ["proj-p1"], x: { colour: "red" } }); assert.deepEqual(doc.scopes[2], { id: "empty", root: "code/empty" }); assert.match(readFileSync(f.config, "utf8"), /^\{\n "format"/, "indent kept"); - assert.equal(plansOf(f.config, "proj"), before.plans, "plans read the same through the new entry"); + assert.equal(plansAt("proj", target), before.plans, "plans read the same in the new folder"); + const listed = executeOperation(loadInventory(f.config), "plans", { scope: "proj", limit: 100 }); + assert.deepEqual((listed.data.groups as { open: { rows: { planId: string }[] } }).open.rows.map((r) => r.planId).sort(), ["proj-p1", "proj-p2"], "plans reads them through the new entry"); assert.deepEqual(readScope({ id: "proj", root: realpathSync(target) }).state.receipts, before.receipts); assertClean(f.config, "proj"); // No lock or temp file left behind in either place. diff --git a/packages/core/test/storage-hygiene.test.ts b/packages/core/test/storage-hygiene.test.ts index 761beba..f6e0bee 100644 --- a/packages/core/test/storage-hygiene.test.ts +++ b/packages/core/test/storage-hygiene.test.ts @@ -1,17 +1,18 @@ import { after, test } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, symlinkSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, writeFileSync, symlinkSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { initScopeState, readScope, repairProjection } from "../src/scope-store.ts"; import { executeOperation } from "../src/api.ts"; import { loadInventory } from "../src/scope-index.ts"; +import { vaultTemp } from "./vault-temp.ts"; const roots: string[] = []; after(() => roots.forEach(root => rmSync(root, { recursive: true, force: true }))); function world(nested = false) { - const repo = mkdtempSync(join(tmpdir(), "mozak-hygiene-")); roots.push(repo); + const repo = vaultTemp(join(tmpdir(), "mozak-hygiene-")); roots.push(repo); execFileSync("git", ["init", "-q", repo], { timeout: 5000 }); const root = nested ? join(repo, "topic") : repo; mkdirSync(root, { recursive: true }); diff --git a/packages/core/test/vault-plans.test.ts b/packages/core/test/vault-plans.test.ts index 117c7be..3e8146f 100644 --- a/packages/core/test/vault-plans.test.ts +++ b/packages/core/test/vault-plans.test.ts @@ -1,10 +1,11 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { executeOperation, initScopeState, loadInventory, readRemoteMeta, setVisibilityChecker } from "../src/index.ts"; +import { vaultTemp } from "./vault-temp.ts"; const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); const made: string[] = []; @@ -26,7 +27,7 @@ function repoState(bare: string): string { /** A public-style code repo (no plan files) plus a vault folder holding the scope. */ function fixture() { - const base = mkdtempSync(join(scratch, "mozak-vault-")); + const base = vaultTemp(join(scratch, "mozak-vault-")); made.push(base); const bare = join(base, "code.git"); const seed = join(base, "seed"); @@ -50,7 +51,7 @@ function fixture() { const exec = (inv: string, op: string, args: unknown, actor: "agent" | "owner" = "agent") => executeOperation(loadInventory(inv), op, args, actor); test("inventory: plans makes a vault scope; shape stays strict; old digests unchanged", () => { - const base = mkdtempSync(join(scratch, "mozak-vault-")); made.push(base); + const base = vaultTemp(join(scratch, "mozak-vault-")); made.push(base); const inv = join(base, "i.json"); const load = (scopes: unknown[]) => { writeFileSync(inv, JSON.stringify({ format: "mozak.local/v3", scopes })); return loadInventory(inv); }; const before = load([{ id: "a", remote: "github:o/r" }, { id: "b", root: "b" }]).digest; diff --git a/packages/core/test/vault-rule.test.ts b/packages/core/test/vault-rule.test.ts new file mode 100644 index 0000000..10c4714 --- /dev/null +++ b/packages/core/test/vault-rule.test.ts @@ -0,0 +1,87 @@ +// The vault rule (0.6.0): every scope root must sit at or below a folder with a .obsidian folder. The loader keeps an +// entry outside a vault but marks it refused (code scope-outside-vault, naming mozak scope move): it never fails the +// whole inventory, every route that reads or writes the scope refuses it, and scopes and doctor list it as failed. +// Synthetic temp folders only. +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { content, NOW } from "./annotations-fixture.ts"; +import { executeOperation } from "../src/api.ts"; +import { loadInventory, resolveScope } from "../src/scope-index.ts"; +import { initScopeState, readScope } from "../src/scope-store.ts"; +import { vaultOf } from "../src/vault-config.ts"; +import { moveScope } from "../src/scope-move.ts"; + +const made: string[] = []; +after(() => { for (const d of made.splice(0)) rmSync(d, { recursive: true, force: true }); }); + +function scope(id: string, root: string): void { + mkdirSync(root, { recursive: true }); + writeFileSync(join(root, "README.md"), `# ${id}\n`); + writeFileSync(join(root, "AGENTS.md"), `Agents for ${id}\n`); + initScopeState({ id, root }, { operationId: `init-${id}`, scopeId: id, kind: "project", title: `Synthetic ${id}`, expectedAbsent: { graph: true, bridge: true }, ownerRef: "synthetic:init", ownerMessageAt: NOW }); +} + +/** base/vault (a vault) holds "inside"; base/code/outside is outside any vault. */ +function setup() { + const base = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "mozak-vaultrule-")); + made.push(base); + mkdirSync(join(base, "vault", ".obsidian"), { recursive: true }); + scope("inside", join(base, "vault", "notes", "inside")); + scope("outside", join(base, "code", "outside")); + const config = join(base, "inventory.json"); + writeFileSync(config, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "inside", root: "vault/notes/inside" }, { id: "outside", root: "code/outside" }] })); + return { base, config }; +} + +test("vaultOf finds the nearest folder with .obsidian at or above a path, even one that does not exist yet", () => { + const { base } = setup(); + assert.equal(vaultOf(join(base, "vault", "notes", "inside")), join(base, "vault")); + assert.equal(vaultOf(join(base, "vault")), join(base, "vault")); + assert.equal(vaultOf(join(base, "vault", "not", "yet")), join(base, "vault")); + assert.equal(vaultOf(join(base, "code", "outside")), null); + // A file named .obsidian is not a vault. + writeFileSync(join(base, "code", ".obsidian"), ""); + assert.equal(vaultOf(join(base, "code", "outside")), null); +}); + +test("the loader keeps an entry outside a vault but refuses it with scope-outside-vault naming scope move", () => { + const { config } = setup(); + const inv = loadInventory(config); + assert.deepEqual(inv.scopes.map((s) => s.id), ["inside", "outside"], "never a whole-inventory error"); + assert.equal(resolveScope(inv, "inside").id, "inside"); + assert.throws(() => resolveScope(inv, "outside"), (e: { code: string; message: string }) => + e.code === "scope-outside-vault" && /not inside an Obsidian vault/.test(e.message) && /mozak scope move --scope outside --to /.test(e.message)); +}); + +test("every route refuses a scope outside a vault; all-scope reads report it as failed coverage", () => { + const { config } = setup(); + const inv = loadInventory(config); + for (const [op, args] of [["context", { scope: "outside" }], ["plans", { scope: "outside" }], ["check", { scope: "outside" }], ["review", { scope: "outside", plan: "p" }], ["render", { scope: "outside" }]] as const) { + const out = executeOperation(inv, op, args); + assert.notEqual(out.exitCode, 0, op); + assert.equal((out.data.issues as { code: string }[])[0]!.code, "scope-outside-vault", op); + } + const ctx = executeOperation(inv, "context", { scope: "inside" }); + const req = { operationId: "op-1", scopeId: "outside", expected: ctx.data.snapshot, action: "propose", payload: { planId: "p1", content: content("p1") } }; + assert.equal((executeOperation(inv, "propose", { scope: "outside", request: req }).data.issues as { code: string }[])[0]!.code, "scope-outside-vault"); + const idx = executeOperation(inv, "scopes", {}); + assert.equal(idx.exitCode, 6); + const rows = idx.data.scopes as { id: string; status: string; code?: string }[]; + assert.deepEqual(rows.map((r) => [r.id, r.status, r.code ?? null]), [["inside", "ok", null], ["outside", "failed", "scope-outside-vault"]]); + const all = executeOperation(inv, "plans", { all: true }); + assert.equal(all.exitCode, 6); + assert.equal(executeOperation(inv, "render", { all: true }).exitCode, 6); +}); + +test("scope move reads a refused entry and the moved scope then works", () => { + const { config, base } = setup(); + const out = moveScope(config, { scope: "outside", to: "vault/notes/outside", ownerRef: "synthetic:owner", ownerMessageAt: NOW, reason: "into the vault" }); + assert.equal(out.status, "ok"); + const inv = loadInventory(config); + assert.equal(resolveScope(inv, "outside").root.endsWith(join("vault", "notes", "outside")), true); + assert.equal(executeOperation(inv, "check", { scope: "outside" }).exitCode, 0); + assert.equal(readScope({ id: "outside", root: join(base, "code", "outside") }).state.scope.id, "outside", "old files stay"); +}); diff --git a/packages/core/test/vault-temp.ts b/packages/core/test/vault-temp.ts new file mode 100644 index 0000000..a99331b --- /dev/null +++ b/packages/core/test/vault-temp.ts @@ -0,0 +1,15 @@ +// Test temp folders as Obsidian vaults. Since 0.6.0 every scope root must sit inside a vault (a folder with a +// .obsidian folder at or above it), so fixtures create their temp base as a vault. Synthetic folders only. +import { mkdirSync, mkdtempSync } from "node:fs"; +import { join } from "node:path"; + +/** Give `dir` a .obsidian folder, so it and everything below it is inside a vault. Returns `dir`. */ +export function makeVault(dir: string): string { + mkdirSync(join(dir, ".obsidian"), { recursive: true }); + return dir; +} + +/** mkdtempSync(prefix), made a vault. */ +export function vaultTemp(prefix: string): string { + return makeVault(mkdtempSync(prefix)); +} diff --git a/packages/core/test/vdup-fixture.ts b/packages/core/test/vdup-fixture.ts index 58f9685..fb71d26 100644 --- a/packages/core/test/vdup-fixture.ts +++ b/packages/core/test/vdup-fixture.ts @@ -2,7 +2,7 @@ // set: exact copies under neutral ids, 60 mutations (12 bases x 5 kinds, a third of them Croatian), templated // siblings that must never be called duplicates, one supersession pair, and one reject moved to another scope. // Used by packages/core/test/vdup.test.ts (every commit) and scripts/verify-dup.ts (on demand). -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { initScopeState, mutateScope, readScope } from "../src/scope-store.ts"; @@ -10,6 +10,7 @@ import { reviewShow } from "../src/review.ts"; import { executeOperation } from "../src/api.ts"; import { loadInventory } from "../src/scope-index.ts"; import type { SimilarPair, SimilarReport } from "../src/similar.ts"; +import { vaultTemp } from "./vault-temp.ts"; const NOW = "2026-10-20T09:00:00.000Z"; @@ -74,7 +75,7 @@ export interface Mirror { } export function buildMirror(): Mirror { - const base = mkdtempSync(join(process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(), "mozak-vdup-")); + const base = vaultTemp(join(process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(), "mozak-vdup-")); const scopes = ["mirror-a", "copies", "mut-1", "mut-2", "mut-3", "mut-4", "mut-5", "tmpl-1", "tmpl-2", "tmpl-3", "relay-old", "relay-bridge"]; const entries: Record = {}; for (const id of scopes) { diff --git a/packages/core/test/visibility.test.ts b/packages/core/test/visibility.test.ts index ce242e4..c02f084 100644 --- a/packages/core/test/visibility.test.ts +++ b/packages/core/test/visibility.test.ts @@ -1,10 +1,11 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { executeOperation, githubSlug, initScopeState, loadInventory, readRemoteMeta, setVisibilityChecker, writeRemoteMeta, type Visibility } from "../src/index.ts"; +import { vaultTemp } from "./vault-temp.ts"; const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); const made: string[] = []; @@ -21,7 +22,7 @@ const content = (title: string) => ({ /** A repo-mode remote scope: plans inside the repo. */ function fixture() { - const base = mkdtempSync(join(scratch, "mozak-vis-")); + const base = vaultTemp(join(scratch, "mozak-vis-")); made.push(base); const bare = join(base, "origin.git"); const seed = join(base, "seed"); diff --git a/packages/core/test/vref.test.ts b/packages/core/test/vref.test.ts index de8f635..41a1682 100644 --- a/packages/core/test/vref.test.ts +++ b/packages/core/test/vref.test.ts @@ -4,12 +4,13 @@ import { after, test } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; +import { readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { cleanup, world } from "./annotations-fixture.ts"; import { readScope, renderBridge } from "../src/scope-store.ts"; import { canonical } from "../src/understanding.ts"; import { ANNOTATIONS_FILE, readAnnotations } from "../src/annotations.ts"; +import { vaultTemp } from "./vault-temp.ts"; after(cleanup); type Issue = { code: string; message: string }; @@ -121,7 +122,7 @@ test("V-ref: the unchanged 0.4.0 core (main) reads and writes a scope that has a try { execFileSync("git", ["rev-parse", "--verify", "-q", "main^{commit}"], { stdio: "ignore", timeout: 5000 }); } catch { hasMain = false; } if (!hasMain) { t.skip("branch main is not available in this checkout"); return; } const version = JSON.parse(execFileSync("git", ["show", "main:package.json"], { encoding: "utf8", timeout: 5000 })).version; - const dir = mkdtempSync(join(process.env.TMPDIR!, "mozak-main-core-")); + const dir = vaultTemp(join(process.env.TMPDIR!, "mozak-main-core-")); try { execFileSync("sh", ["-c", `git archive main packages/core/src | tar -x -C "${dir}"`], { timeout: 20000 }); const old = await import(join(dir, "packages/core/src/index.ts")); diff --git a/packages/mcp/test/mcp.test.ts b/packages/mcp/test/mcp.test.ts index 27eccd8..0ba0495 100644 --- a/packages/mcp/test/mcp.test.ts +++ b/packages/mcp/test/mcp.test.ts @@ -1,12 +1,13 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { spawn, spawnSync, type ChildProcess } from "node:child_process"; -import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { errorText, handle, TOOLS } from "../src/server.ts"; import { initScopeState, loadInventory } from "@mozak/core"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // Package 1 contract (docs/implementation-package-1-plan-state-review.md, sections 5 and 8). // Read tools map to API operations; mutation tools map to API operations; every call is actor "agent". @@ -60,7 +61,7 @@ after(() => { /** A real scratch inventory with one scope created through core's public initScopeState. */ function fixture(): { dir: string; configPath: string; scopeDir: string } { - const dir = realpathSync(mkdtempSync(join(tmpdir(), "mozak-mcp-"))); + const dir = realpathSync(vaultTemp(join(tmpdir(), "mozak-mcp-"))); scratchDirs.push(dir); const scopeDir = join(dir, "alpha"); mkdirSync(scopeDir); @@ -768,7 +769,7 @@ function normalizeContext(d: any) { test("A08/A09: a real built CLI scenario, then a fresh MCP process returns equivalent context and review DTOs", async () => { const f = fixture(); // The fixture already initialised the scope through core. This scenario drives the real CLI from a clean scope instead. - const dir = realpathSync(mkdtempSync(join(tmpdir(), "mozak-parity-"))); + const dir = realpathSync(vaultTemp(join(tmpdir(), "mozak-parity-"))); scratchDirs.push(dir); const scopeDir = join(dir, "beta"); mkdirSync(scopeDir); diff --git a/packages/mcp/test/package2-protected.test.ts b/packages/mcp/test/package2-protected.test.ts index 5879474..f17f5da 100644 --- a/packages/mcp/test/package2-protected.test.ts +++ b/packages/mcp/test/package2-protected.test.ts @@ -1,11 +1,12 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { spawn, spawnSync, type ChildProcess } from "node:child_process"; -import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"; +import { mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { readScope } from "../../core/src/scope-store.ts"; import { loadInventory } from "../../core/src/scope-index.ts"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; // Package 2 nested protected-field attacks through a FRESH BUILT MCP child (packages/mcp/dist/index.js). // Each attack is a valid-looking new-route call with one protected or forged field inside it. Every case asserts @@ -42,7 +43,7 @@ const content = { /** Owner setup through the built CLI, ending with an accepted plan and no discussion, specification or grant. */ function fixture() { - const root = mkdtempSync(join(scratch!, "mozak-mcp-protected-")); + const root = vaultTemp(join(scratch!, "mozak-mcp-protected-")); roots.push(root); const path = join(root, "one"); mkdirSync(path); diff --git a/packages/obsidian/test/model.test.ts b/packages/obsidian/test/model.test.ts index 945f0ee..a0e448b 100644 --- a/packages/obsidian/test/model.test.ts +++ b/packages/obsidian/test/model.test.ts @@ -1,7 +1,7 @@ import { test } from "node:test"; import { execFileSync } from "node:child_process"; import assert from "node:assert/strict"; -import { mkdtempSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -11,6 +11,7 @@ import { countRemote, countsSummary, defaultFilter, FILTERS, headingLine, planMa import { loadScopesModel, realOrSelf, renderStaleProjections } from "../src/load.ts"; import { cleanup as cleanupWorlds, world } from "../../core/test/annotations-fixture.ts"; import { after } from "node:test"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; after(cleanupWorlds); @@ -58,7 +59,7 @@ test("resolveOpenTarget separates vault files from outside files", () => { }); test("resolveOpenTarget treats a vault opened through a symlink as the same vault", () => { - const base = realpathSync(mkdtempSync(join(process.env.JCODE_SCRATCH_DIR ?? tmpdir(), "mozak-obs-link-"))); + const base = realpathSync(vaultTemp(join(process.env.JCODE_SCRATCH_DIR ?? tmpdir(), "mozak-obs-link-"))); const real = join(base, "real-vault"); mkdirSync(join(real, "plans"), { recursive: true }); writeFileSync(join(real, "plans", "mozak.md"), "# m\n"); @@ -82,7 +83,7 @@ test("failed scope becomes an error row and counts as failed", () => { }); test("discoverInventory walks up from the vault and chooseInventory prefers the setting", () => { - const top = mkdtempSync(join(tmpdir(), "mozak-obs-")); + const top = vaultTemp(join(tmpdir(), "mozak-obs-")); const vault = join(top, "repo", "vault"); mkdirSync(vault, { recursive: true }); assert.equal(discoverInventory(vault), null); @@ -94,7 +95,7 @@ test("discoverInventory walks up from the vault and chooseInventory prefers the }); test("loadScopesModel reads a real core inventory, one scope failing without hiding the rest", () => { - const top = mkdtempSync(join(tmpdir(), "mozak-obs-")); + const top = vaultTemp(join(tmpdir(), "mozak-obs-")); mkdirSync(join(top, "empty")); writeFileSync( join(top, "mozak-inventory.json"), @@ -126,7 +127,7 @@ test("remote scopes carry their badge data through the view model and are counte }); test("vault-plans scopes keep the repo badge, are never stale, open plans inside the vault, and need no sync", () => { - const base = mkdtempSync(join(process.env.JCODE_SCRATCH_DIR ?? tmpdir(), "mozak-obs-vault-")); + const base = vaultTemp(join(process.env.JCODE_SCRATCH_DIR ?? tmpdir(), "mozak-obs-vault-")); const vault = join(base, "vault"); const plans = join(vault, "creations", "tool"); mkdirSync(plans, { recursive: true }); @@ -163,7 +164,7 @@ const roadContent = { }; /** A synthetic inventory with one accepted plan whose first outcome has passing evidence. */ function roadWorld() { - const top = mkdtempSync(join(scratchBase, "mozak-obs-road-")); + const top = vaultTemp(join(scratchBase, "mozak-obs-road-")); mkdirSync(join(top, "road")); writeFileSync(join(top, "road", "README.md"), "# r\n"); writeFileSync(join(top, "road", "AGENTS.md"), "# a\n"); diff --git a/packages/obsidian/test/sync.test.ts b/packages/obsidian/test/sync.test.ts index b4d6b34..d77424c 100644 --- a/packages/obsidian/test/sync.test.ts +++ b/packages/obsidian/test/sync.test.ts @@ -3,11 +3,12 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { initScopeState } from "@mozak/core"; import { syncAll, syncSummary } from "../src/load.ts"; +import { vaultTemp } from "../../core/test/vault-temp.ts"; const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); const made: string[] = []; @@ -26,7 +27,7 @@ test("syncSummary names pulled, ahead and diverged vaults and stale remotes", () }); test("syncAll fast-forwards a vault repo that holds a local scope", () => { - const base = mkdtempSync(join(scratch, "mozak-obs-sync-")); + const base = vaultTemp(join(scratch, "mozak-obs-sync-")); made.push(base); const bare = join(base, "vault.git"); const seed = join(base, "seed"); diff --git a/scripts/readme-example.mjs b/scripts/readme-example.mjs index 52f889f..eb3146c 100644 --- a/scripts/readme-example.mjs +++ b/scripts/readme-example.mjs @@ -10,6 +10,8 @@ import { fileURLToPath } from "node:url"; const cli = fileURLToPath(new URL("../packages/cli/dist/index.js", import.meta.url)); const root = mkdtempSync(join(tmpdir(), "mozak-readme-example-")); +// The example folder is an Obsidian vault: mozak keeps plans only inside a vault. +mkdirSync(join(root, ".obsidian")); const at = new Date(Date.now() - 60_000).toISOString(); let seq = 0; diff --git a/scripts/setup-demo-vault.mjs b/scripts/setup-demo-vault.mjs index 14b570f..594a191 100644 --- a/scripts/setup-demo-vault.mjs +++ b/scripts/setup-demo-vault.mjs @@ -62,7 +62,9 @@ for (const s of scopes) { writeFileSync(join(dir, "AGENTS.md"), s.agents); } -// 2. Write mozak-inventory.json at the vault root so the Obsidian plugin auto-discovers it +// 2. Write mozak-inventory.json at the vault root so the Obsidian plugin auto-discovers it. The .obsidian folder +// comes first: mozak reads scopes only inside a vault. +mkdirSync(join(target, ".obsidian"), { recursive: true }); const inventoryPath = join(target, "mozak-inventory.json"); writeFileSync( inventoryPath, diff --git a/scripts/test-install.mjs b/scripts/test-install.mjs index 92ea6e4..e924884 100644 --- a/scripts/test-install.mjs +++ b/scripts/test-install.mjs @@ -220,7 +220,8 @@ test('relocated real product installs at two canonical Unicode/quoted prefixes a assert.equal(direct.status, 0, direct.stderr); cli(f, ['context', '--scope', 'one', '--json'], 2); // explicit config remains required cli(f, ['not-a-command'], 2); // wrapper preserves failure status - const scope = join(f.root, 'synthetic scope'); mkdirSync(scope); + const scope = join(f.root, 'synthetic vault', 'synthetic scope'); mkdirSync(scope, { recursive: true }); + mkdirSync(join(f.root, 'synthetic vault', '.obsidian')); writeFileSync(join(scope, 'README.md'), '# Synthetic scope\n'); writeFileSync(join(scope, 'AGENTS.md'), '# Synthetic instructions\n'); const config = join(f.root, 'inventory.json'); From 8efd769adc03df6f0d9c7746993dced38aca1f7a Mon Sep 17 00:00:00 2001 From: pitfa19 <166558275+pitfa19@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:38:01 +0100 Subject: [PATCH 03/10] Retire repo-scope entries: list them as legacy-repo-scope with the move command Why: spec step 4. 0.6.0 no longer accepts remote, ref or plans entries as working scopes. Such an entry must not break the inventory: other scopes keep working and mozak scope move can read it. What: - core legacy-entry.ts: an entry with any of remote, ref, plans is kept as a refused entry (legacy-repo-scope). Its root is where its plan files are on this machine: the plans folder for a vault-plans entry, a 0.5.0 full clone named (absolute path) in the cache metadata while it still holds mozak.json, else the sparse cache copy. The message names the remote and the exact command, with --to set to the plans folder when it is already in a vault and --config set to the inventory. No URL parsing, no git, no network. - loadInventory split into readInventoryJson, localEntry, legacyEntry, entryId and assertUnique. Legacy keys stay closed and strict (no root beside them, no unknown keys, safe id). The digest is the v2 shape for every entry, so local-entry digests are unchanged. ScopeEntry no longer gets a remote from the loader, so every remote code path is now unreachable (step 6 deletes it). - sync --scope and pull resolve through resolveScope, so they refuse a legacy entry like every other route. - Tests: legacy-entries.test.ts (new). remote.test.ts, vault-plans.test.ts, visibility.test.ts and s2-offline.test.ts are deleted: every test in them exercised repo-scope behaviour that no longer exists. Their still-valid parts moved: entry strictness, digest stability and "local reads never fetch" into legacy-entries.test.ts. cwd-scope, render and the plugin model test now assert the refusal. Proof: legacy-entries.test.ts failed first (no refusal, plugin row without error) and passes (9 tests). npm test 638 of 638 under default TMPDIR, /tmp and a realpath folder, test:install 73 + 1 skipped. ub-mode: CRAP loadInventory 8.0 (was CC 46, CRAP 46.6), legacyEntry 8.0, readInventoryJson 8.0, legacyLocation 7.0, repoModeRoot 4.0, assertUnique under 5. dryer: no candidates. mutator legacy-entry.ts and the loader lines: 38 killed, 2 equivalent survivors in the id sort comparator (ids are unique, so < and <= and the tie value never differ). --- packages/cli/test/cwd-scope.test.ts | 23 +-- packages/cli/test/render.test.ts | 13 +- packages/core/src/api.ts | 7 +- packages/core/src/legacy-entry.ts | 55 ++++++ packages/core/src/scope-index.ts | 174 ++++++++----------- packages/core/test/legacy-entries.test.ts | 167 ++++++++++++++++++ packages/core/test/remote.test.ts | 203 ---------------------- packages/core/test/s2-offline.test.ts | 89 ---------- packages/core/test/vault-plans.test.ts | 169 ------------------ packages/core/test/visibility.test.ts | 121 ------------- packages/obsidian/test/model.test.ts | 20 +-- 11 files changed, 313 insertions(+), 728 deletions(-) create mode 100644 packages/core/src/legacy-entry.ts create mode 100644 packages/core/test/legacy-entries.test.ts delete mode 100644 packages/core/test/remote.test.ts delete mode 100644 packages/core/test/s2-offline.test.ts delete mode 100644 packages/core/test/vault-plans.test.ts delete mode 100644 packages/core/test/visibility.test.ts diff --git a/packages/cli/test/cwd-scope.test.ts b/packages/cli/test/cwd-scope.test.ts index 240436e..9243120 100644 --- a/packages/cli/test/cwd-scope.test.ts +++ b/packages/cli/test/cwd-scope.test.ts @@ -63,19 +63,12 @@ test("repoKey normalizes https, ssh, scp-like, github: and file forms", () => { assert.equal(repoKey("not a url"), null); }); -test("context, plans, check and review show without --scope inside a clone resolve the vault scope", async () => { +test("context, plans, check and review show without --scope inside a clone no longer resolve a legacy repo scope", async () => { const { inv, clone } = fixture(); + // 0.6.0: a remote entry is legacy-repo-scope, so a clone's origin matches no working scope. const ctx = await run(["context", "--config", inv], clone); - assert.equal(ctx.code, 0, ctx.out + ctx.err); - assert.equal(JSON.parse(ctx.out).context.scope.id, "tool"); - // Also from a subfolder of the clone. - mkdirSync(join(clone, "src")); - assert.equal((await run(["context", "--config", inv], join(clone, "src"))).code, 0); - const plans = await run(["plans", "--config", inv, "--json"], clone); - assert.equal(plans.code, 0, plans.out); - assert.equal((await run(["check", "--config", inv], clone)).code, 0); - const show = await run(["review", "show", "--config", inv, "--plan", "nope"], clone); - assert.notEqual(JSON.parse(show.out).status, "scope-not-found"); + assert.equal(ctx.code, 2, ctx.out + ctx.err); + assert.equal(JSON.parse(ctx.out).status, "scope-not-found"); // The clone never receives plan files. assert.ok(!existsSync(join(clone, "mozak.json"))); assert.equal(g(clone, "status", "--porcelain"), ""); @@ -105,13 +98,13 @@ test("explicit --scope still wins inside a clone", async () => { assert.notEqual(JSON.parse(r.out).context?.scope?.id, "tool"); }); -test("pull --into a Downloads folder clones code only", async () => { +test("pull refuses a legacy repo scope and clones nothing", async () => { const { inv, base, plans } = fixture(); const before = readFileSync(join(plans, "mozak.json")); const dest = join(base, "Downloads", "fresh"); const r = await run(["pull", "--config", inv, "--scope", "tool", "--into", dest, "--json"], base); - assert.equal(r.code, 0, r.out + r.err); - assert.ok(existsSync(join(dest, "index.js"))); - assert.ok(!existsSync(join(dest, "mozak.json"))); + assert.equal(r.code, 2, r.out + r.err); + assert.equal(JSON.parse(r.out).status, "legacy-repo-scope"); + assert.ok(!existsSync(dest)); assert.deepEqual(readFileSync(join(plans, "mozak.json")), before); }); diff --git a/packages/cli/test/render.test.ts b/packages/cli/test/render.test.ts index 981209b..d6b8165 100644 --- a/packages/cli/test/render.test.ts +++ b/packages/cli/test/render.test.ts @@ -149,18 +149,15 @@ test("render reports a failed cleanup even if the projection was already publish assert.equal(sha(join(entry.root, "mozak.json")), json); }); -test("direct render refuses remote scopes before touching their cache", () => { +test("render --all reports a legacy repo entry as failed and never touches its cache", () => { const { config, entries } = world(["alpha"]); writeFileSync(config, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "alpha", remote: "github:example/sample", ref: "main" }] })); - const remote = loadInventory(config).scopes[0]!; - const entry = { ...entries[0]!, remote: remote.remote }; makeLegacy(entries[0]!); - const before = sha(join(entry.root, "mozak.md")); - assert.throws(() => renderProjection(entry), { code: "remote-render-refused" }); - assert.equal(sha(join(entry.root, "mozak.md")), before); + const before = sha(join(entries[0]!.root, "mozak.md")); const out = executeOperation(loadInventory(config), "render", { all: true }, "agent"); - assert.equal(out.exitCode, 0); - assert.equal((out.data.scopes as { result: string }[])[0]!.result, "remote-skipped"); + assert.equal(out.exitCode, 6); + assert.deepEqual((out.data.scopes as { result: string; code?: string }[]).map((r) => [r.result, r.code]), [["failed", "legacy-repo-scope"]]); + assert.equal(sha(join(entries[0]!.root, "mozak.md")), before); }); test("a hand-edited bridge stays a conflict and render refuses to overwrite it", () => { diff --git a/packages/core/src/api.ts b/packages/core/src/api.ts index e3055ad..29bda88 100644 --- a/packages/core/src/api.ts +++ b/packages/core/src/api.ts @@ -988,8 +988,8 @@ function remoteOp(inv: ScopeInventory, operation: string, a: Record s.id === nonEmpty(o.scope, "scope")); + // A local scope syncs the git repo that holds it. A refused scope (outside a vault, legacy repo scope) is refused. + const named = o.scope === undefined ? undefined : resolveScope(inv, nonEmpty(o.scope, "scope")); if (named && !named.remote) return localSyncOutput(inv, [named], base); const targets = o.scope === undefined ? remoteEntries(inv) : [resolveRemoteTarget(inv, nonEmpty(o.scope, "scope"))]; const remote = targets.map((e) => syncRemote(e, { force: true })); @@ -1030,8 +1030,7 @@ function localSyncOutput(inv: ScopeInventory, targets: ScopeEntry[], base: Recor } function resolveRemoteTarget(inv: ScopeInventory, id: string): ScopeEntry { - const entry = inv.scopes.find((s) => s.id === id); - if (!entry) throw new DomainError("scope-not-found", `no scope "${id}" in the inventory; run mozak scopes (MCP mozak_scopes) to list the scope ids`); + const entry = resolveScope(inv, id); if (!entry.remote) throw new DomainError("scope-not-remote", `scope "${id}" is a local scope, there is nothing to sync`); return entry; } diff --git a/packages/core/src/legacy-entry.ts b/packages/core/src/legacy-entry.ts new file mode 100644 index 0000000..c61b508 --- /dev/null +++ b/packages/core/src/legacy-entry.ts @@ -0,0 +1,55 @@ +// Legacy repo-scope entries. Before 0.6.0 an inventory entry could name a git repo instead of a folder: +// { id, remote, ref?, plans? }. mozak 0.6.0 keeps plans in vault folders only, so such an entry is no longer a working +// scope. The loader keeps it (never a whole-inventory error) as a refused entry whose root is where its plan files are +// on this machine, so `mozak scope move` can copy them into a vault. Every other route refuses it with +// legacy-repo-scope and the exact move command. Nothing here runs git or touches the network. + +import { readFileSync } from "node:fs"; +import { isAbsolute, join, resolve } from "node:path"; +import { vaultOf } from "./vault-config.ts"; + +export const LEGACY_KEYS = ["remote", "ref", "plans"] as const; +/** The cache folder 0.5.0 kept next to the inventory for repo scopes. */ +export const LEGACY_CACHE_DIR = ".mozak-cache"; + +export interface LegacyLocation { root: string; refused: { code: string; message: string } } + +/** True when the entry carries any key of the retired repo-scope form. */ +export const isLegacyEntry = (entry: Record): boolean => LEGACY_KEYS.some((k) => k in entry); + +/** + * Where a repo-mode entry's plan files are on this machine: a full clone made by 0.5.0 `mozak pull` (named in the + * cache metadata, used only while it still holds mozak.json), else the sparse cache copy. Reads one small JSON file. + */ +function repoModeRoot(base: string, id: string): string { + const cache = join(base, LEGACY_CACHE_DIR, id); + try { + const meta = JSON.parse(readFileSync(join(base, LEGACY_CACHE_DIR, `${id}.meta.json`), "utf8")) as { fullClone?: unknown }; + const clone = meta.fullClone; + // 0.5.0 wrote an absolute path. Anything else would resolve against the current folder, so it is ignored. + if (typeof clone === "string" && isAbsolute(clone)) { + readFileSync(join(clone, "mozak.json")); + return clone; + } + } catch { /* no metadata, or the clone is gone: the cache copy it is */ } + return cache; +} + +/** + * The refused location of a legacy entry. `plans` (a vault-plans entry) names the folder that already holds the plans; + * otherwise they are in the repo cache. The command suggests the plans folder itself when it is inside a vault (the + * move then only rewrites the entry), else a vault folder the owner picks. + */ +export function legacyLocation(base: string, inventoryFile: string, id: string, entry: Record, canonical: (p: string) => string): LegacyLocation { + const plans = typeof entry.plans === "string" && entry.plans.trim() !== "" ? entry.plans : null; + const root = canonical(plans !== null ? resolve(base, plans) : repoModeRoot(base, id)); + const target = plans !== null && vaultOf(root) !== null ? plans : ""; + const from = typeof entry.remote === "string" ? ` (remote ${entry.remote})` : ""; + return { + root, + refused: { + code: "legacy-repo-scope", + message: `scope "${id}" is a repo scope${from}, which mozak 0.6.0 no longer reads; its plans are in ${root}. Move them into a vault folder: mozak scope move --scope ${id} --to ${target} --owner-ref REF --owner-message-at ISO --reason TEXT --config ${inventoryFile}`, + }, + }; +} diff --git a/packages/core/src/scope-index.ts b/packages/core/src/scope-index.ts index e28633e..d0b64ce 100644 --- a/packages/core/src/scope-index.ts +++ b/packages/core/src/scope-index.ts @@ -1,8 +1,9 @@ import { createHash } from "node:crypto"; -import { existsSync, lstatSync, readFileSync, realpathSync, statSync, type Stats } from "node:fs"; +import { lstatSync, readFileSync, realpathSync, statSync, type Stats } from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; import { DomainError } from "./errors.ts"; -import { cacheRootFor, parseRemoteSpec, readRemoteMeta, CACHE_DIR, DEFAULT_REF, REF_PATTERN, type RemoteInfo } from "./remote-meta.ts"; +import type { RemoteInfo } from "./remote-meta.ts"; +import { isLegacyEntry, LEGACY_KEYS, legacyLocation } from "./legacy-entry.ts"; import { vaultOf } from "./vault-config.ts"; /** Pilot-local explicit inventory. Never a global registration or a directory scan. */ @@ -11,7 +12,7 @@ export const INVENTORY_FORMAT_V2 = "mozak.local/v2" as const; export const INVENTORY_FORMAT = "mozak.local/v3" as const; export type InventoryFormat = typeof INVENTORY_FORMAT_V2 | typeof INVENTORY_FORMAT; export const WRITE_LOCK_DIR = ".mozak-write-lock"; -import { SCOPE_FILE_NAMES, scopeFile } from "./scope-files.ts"; +import { SCOPE_FILE_NAMES } from "./scope-files.ts"; export interface ScopeEntry { id: string; @@ -39,10 +40,10 @@ export interface ScopeInventory { const INVENTORY_KEYS = ["format", "scopes"] as const; const ENTRY_KEYS = ["id", "root"] as const; -const REMOTE_ENTRY_KEYS = ["id", "remote", "ref", "plans"] as const; /** Optional on every scope entry. `focus`: the owner's starred plan ids, read by the plugin and `mozak focus` only. */ const OPTIONAL_ENTRY_KEYS = ["focus"] as const; -const REMOTE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; +/** A legacy entry's id named a cache folder, so it never held path characters. */ +const LEGACY_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; function isPlainObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); @@ -110,137 +111,100 @@ export function canonicalPath(path: string): string { } function digestOf(format: string, scopes: ScopeEntry[]): string { - const canonical = JSON.stringify({ - format, - // Local entries keep the exact v2 shape, so existing digests do not change. Vault entries add their plans folder. - scopes: scopes.map((scope) => - scope.remote - ? scope.remote.plansMode === "vault" - ? { id: scope.id, root: scope.root, remote: scope.remote.spec, ref: scope.remote.ref, plans: "vault" } - : { id: scope.id, root: scope.root, remote: scope.remote.spec, ref: scope.remote.ref } - : { id: scope.id, root: scope.root }, - ), - }); + // Format plus sorted id and canonical root: the exact v2 shape, so existing digests do not change. + const canonical = JSON.stringify({ format, scopes: scopes.map((scope) => ({ id: scope.id, root: scope.root })) }); return createHash("sha256").update(canonical, "utf8").digest("hex"); } -/** - * Read and validate an explicit local inventory. Relative roots resolve against the config - * directory. Missing or unreadable roots are retained so that only the selected scope fails later. - */ -export function loadInventory(configPath: string): ScopeInventory { - const file = resolve(configPath); - +function readInventoryJson(file: string): Record { let text: string; try { text = readFileSync(file, "utf8"); } catch (err) { throw new DomainError("inventory-unreadable", `${file}: cannot read inventory (${errorCode(err) ?? "unknown"})`); } - let raw: unknown; try { raw = JSON.parse(text); } catch { throw invalidInventory(file, "inventory is not valid JSON"); } - if (!isPlainObject(raw)) throw invalidInventory(file, "inventory must be a JSON object"); assertClosedObject(raw, INVENTORY_KEYS, "inventory", file); if (raw.format !== INVENTORY_FORMAT && raw.format !== INVENTORY_FORMAT_V2) { throw invalidInventory(file, `format must be "${INVENTORY_FORMAT}" or "${INVENTORY_FORMAT_V2}"`); } - const format: InventoryFormat = raw.format; if (!Array.isArray(raw.scopes)) throw invalidInventory(file, `"scopes" must be an array`); + return raw; +} + +/** A retired repo-scope entry (v3 only): closed keys, no root, an id that named a cache folder. */ +function legacyEntry(entry: Record, file: string, base: string): ScopeEntry { + for (const key of Object.keys(entry)) { + if (key === "root") throw invalidInventory(file, `scope entry must have exactly one of "root" or "remote"`); + if (key !== "x" && key !== "id" && !(LEGACY_KEYS as readonly string[]).includes(key) && !(OPTIONAL_ENTRY_KEYS as readonly string[]).includes(key)) { + throw invalidInventory(file, `unknown key "${key}" in scope entry`); + } + } + assertExtensionObject(entry, "scope entry", file); + const id = entryId(entry, file); + if (!LEGACY_ID_PATTERN.test(id)) throw invalidInventory(file, `scope id "${id}" must use letters, digits, ".", "_" or "-"`); + const { root, refused } = legacyLocation(base, file, id, entry, canonicalPath); + return { id, root, refused }; +} + +function entryId(entry: Record, file: string): string { + const id = entry.id; + if (typeof id !== "string" || id.trim() === "") throw invalidInventory(file, "scope id must be a nonempty string"); + return id; +} + +/** A working scope entry: { id, root } plus optional keys. The vault rule marks a root outside a vault as refused. */ +function localEntry(entry: Record, file: string, base: string): ScopeEntry { + assertClosedObject(entry, ENTRY_KEYS, "scope entry", file, OPTIONAL_ENTRY_KEYS); + const id = entryId(entry, file); + const rawRoot = entry.root; + if (typeof rawRoot !== "string" || rawRoot.trim() === "") throw invalidInventory(file, `scope "${id}" root must be a nonempty string`); + const root = canonicalPath(resolve(base, rawRoot)); + const refused = vaultRule(id, root); + return refused ? { id, root, refused } : { id, root }; +} +/** Each id and each canonical root appears once. */ +function assertUnique(scope: ScopeEntry, seen: { ids: Set; roots: Map }, file: string): void { + if (seen.ids.has(scope.id)) throw new DomainError("inventory-duplicate-id", `${file}: duplicate scope id "${scope.id}"`); + seen.ids.add(scope.id); + const prior = seen.roots.get(scope.root); + if (prior !== undefined) { + throw new DomainError("inventory-duplicate-root", `${file}: scopes "${prior}" and "${scope.id}" resolve to the same root ${scope.root}`); + } + seen.roots.set(scope.root, scope.id); +} + +/** + * Read and validate an explicit local inventory. Relative roots resolve against the config + * directory. Missing or unreadable roots are retained so that only the selected scope fails later. + * Entries outside a vault and retired repo-scope entries are kept but refused (see `refused`). + */ +export function loadInventory(configPath: string): ScopeInventory { + const file = resolve(configPath); + const raw = readInventoryJson(file); + const format = raw.format as InventoryFormat; const base = dirname(file); - const seenIds = new Set(); - const seenRoots = new Map(); + const seen = { ids: new Set(), roots: new Map() }; const scopes: ScopeEntry[] = []; - for (const entry of raw.scopes) { + for (const entry of raw.scopes as unknown[]) { if (!isPlainObject(entry)) throw invalidInventory(file, "each scope must be an object"); - const isRemote = format === INVENTORY_FORMAT && "remote" in entry; - if (isRemote) { - // Exactly one of root or remote. The ref is optional and defaults to main. The object stays closed. - for (const key of Object.keys(entry)) { - if (key !== "x" && !(REMOTE_ENTRY_KEYS as readonly string[]).includes(key) && !(OPTIONAL_ENTRY_KEYS as readonly string[]).includes(key)) { - throw invalidInventory(file, key === "root" ? `scope entry must have exactly one of "root" or "remote"` : `unknown key "${key}" in scope entry`); - } - } - assertExtensionObject(entry, "scope entry", file); - if (!("id" in entry)) throw invalidInventory(file, `missing "id" in scope entry`); - } else { - assertClosedObject(entry, ENTRY_KEYS, "scope entry", file, OPTIONAL_ENTRY_KEYS); - } + const scope = format === INVENTORY_FORMAT && isLegacyEntry(entry) ? legacyEntry(entry, file, base) : localEntry(entry, file, base); assertFocus(entry, file); - - const id = entry.id; - if (typeof id !== "string" || id.trim() === "") { - throw invalidInventory(file, "scope id must be a nonempty string"); - } - let root: string; - let remote: RemoteInfo | undefined; - if (isRemote) { - if (!REMOTE_ID_PATTERN.test(id)) { - throw invalidInventory(file, `remote scope id "${id}" must use letters, digits, ".", "_" or "-" (it names a cache folder)`); - } - if (typeof entry.remote !== "string") throw invalidInventory(file, `scope "${id}" remote must be a string`); - const ref = entry.ref === undefined ? DEFAULT_REF : entry.ref; - if (typeof ref !== "string" || !REF_PATTERN.test(ref)) { - throw invalidInventory(file, `scope "${id}" ref must be a plain branch name`); - } - const parsed = parseRemoteSpec(entry.remote); - if (!parsed) { - throw invalidInventory(file, `scope "${id}" remote must look like "github:owner/repo", an https:// URL or an absolute file:// URL`); - } - const cacheRoot = canonicalPath(cacheRootFor(base, id)); - if (entry.plans !== undefined) { - // Vault plans: the scope root is a local folder. The repo is never cloned, committed to or pushed for plans. - if (typeof entry.plans !== "string" || entry.plans.trim() === "") throw invalidInventory(file, `scope "${id}" plans must be a nonempty path`); - const plansRoot = canonicalPath(resolve(base, entry.plans)); - const cacheDir = canonicalPath(join(base, CACHE_DIR)); - if (plansRoot === cacheDir || plansRoot.startsWith(cacheDir + "/")) { - throw invalidInventory(file, `scope "${id}" plans folder must not be inside ${CACHE_DIR}/`); - } - root = plansRoot; - remote = { spec: entry.remote, url: parsed.url, ref, repoName: parsed.repoName, baseDir: base, cacheRoot, fullClone: null, plansMode: "vault" }; - } else { - const meta = readRemoteMeta(base, id); - const fullClone = meta.fullClone !== null && existsSync(join(meta.fullClone, ".git")) && existsSync(scopeFile(meta.fullClone, "graph")) ? canonicalPath(meta.fullClone) : null; - root = fullClone ?? cacheRoot; - remote = { spec: entry.remote, url: parsed.url, ref, repoName: parsed.repoName, baseDir: base, cacheRoot, fullClone, plansMode: "repo" }; - } - } else { - const rawRoot = entry.root; - if (typeof rawRoot !== "string" || rawRoot.trim() === "") { - throw invalidInventory(file, `scope "${id}" root must be a nonempty string`); - } - root = canonicalPath(resolve(base, rawRoot)); - } - - if (seenIds.has(id)) { - throw new DomainError("inventory-duplicate-id", `${file}: duplicate scope id "${id}"`); - } - seenIds.add(id); - - const canonical = root; - const prior = seenRoots.get(canonical); - if (prior !== undefined) { - throw new DomainError( - "inventory-duplicate-root", - `${file}: scopes "${prior}" and "${id}" resolve to the same root ${canonical}`, - ); - } - seenRoots.set(canonical, id); - const scope: ScopeEntry = remote ? { id, root: canonical, remote } : { id, root: canonical }; + assertUnique(scope, seen, file); if ("x" in raw || "x" in entry) scope.inventoryExtensionsIgnored = true; - const refused = vaultRule(id, canonical); - if (refused) scope.refused = refused; scopes.push(scope); } - scopes.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); + // Ids are unique (assertUnique), so ordering by "is a before b" is total. Code-point order, not locale order. + scopes.sort((a, b) => (a.id < b.id ? -1 : 1)); const inventory: ScopeInventory = { format, scopes, digest: digestOf(format, scopes) }; // Not enumerable: the loaded inventory compares and serializes exactly as before. Used to find mozak-settings.json. Object.defineProperty(inventory, "path", { value: file, enumerable: false }); diff --git a/packages/core/test/legacy-entries.test.ts b/packages/core/test/legacy-entries.test.ts new file mode 100644 index 0000000..521c819 --- /dev/null +++ b/packages/core/test/legacy-entries.test.ts @@ -0,0 +1,167 @@ +// Legacy repo-scope entries (0.6.0): an inventory entry with remote, ref or plans is no longer a working scope. It is +// listed as a failed scope with code legacy-repo-scope and the exact mozak scope move command, never a whole-inventory +// error, so other scopes keep working, scope move can read it, and every other route refuses it. Nothing touches git +// or the network for it. Synthetic temp folders only. +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { NOW } from "./annotations-fixture.ts"; +import { executeOperation } from "../src/api.ts"; +import { loadInventory, resolveScope } from "../src/scope-index.ts"; +import { initScopeState } from "../src/scope-store.ts"; +import { moveScope } from "../src/scope-move.ts"; +import { loadScopesModel } from "../../obsidian/src/load.ts"; + +const made: string[] = []; +after(() => { for (const d of made.splice(0)) rmSync(d, { recursive: true, force: true }); }); + +function scope(id: string, root: string): void { + mkdirSync(root, { recursive: true }); + writeFileSync(join(root, "README.md"), `# ${id}\n`); + writeFileSync(join(root, "AGENTS.md"), `Agents for ${id}\n`); + initScopeState({ id, root }, { operationId: `init-${id}`, scopeId: id, kind: "project", title: `Synthetic ${id}`, expectedAbsent: { graph: true, bridge: true }, ownerRef: "synthetic:init", ownerMessageAt: NOW }); +} + +/** + * A vault inventory as the owner had it with 0.5.0: a local scope, a vault-plans entry (plans in the vault), and a + * repo-mode entry whose plans sit in the sparse cache .mozak-cache/web. The remotes point at a file:// path that does + * not exist, so any git call would fail loudly. + */ +function legacyWorld() { + const base = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "mozak-legacy-")); + made.push(base); + mkdirSync(join(base, ".obsidian")); + scope("home", join(base, "home")); + scope("tool", join(base, "creations", "tool")); + scope("web", join(base, ".mozak-cache", "web")); + const config = join(base, "mozak-inventory.json"); + writeFileSync(config, JSON.stringify({ format: "mozak.local/v3", scopes: [ + { id: "home", root: "home" }, + { id: "tool", remote: `file://${base}/missing/tool.git`, plans: "creations/tool" }, + { id: "web", remote: `file://${base}/missing/web.git`, ref: "main", focus: [] }, + ] }, null, 2)); + return { base, config }; +} + +test("the loader lists legacy entries as refused with legacy-repo-scope and the exact scope move command", () => { + const { config } = legacyWorld(); + const inv = loadInventory(config); + assert.deepEqual(inv.scopes.map((s) => s.id), ["home", "tool", "web"]); + assert.equal(resolveScope(inv, "home").id, "home"); + assert.throws(() => resolveScope(inv, "tool"), (e: { code: string; message: string }) => + e.code === "legacy-repo-scope" && e.message.includes(`mozak scope move --scope tool --to creations/tool --owner-ref REF --owner-message-at ISO --reason TEXT --config ${config}`)); + assert.throws(() => resolveScope(inv, "web"), (e: { code: string; message: string }) => + e.code === "legacy-repo-scope" && e.message.includes(`mozak scope move --scope web --to --owner-ref REF --owner-message-at ISO --reason TEXT --config ${config}`) && /plans are in .*\.mozak-cache\/web/.test(e.message)); +}); + +test("scopes lists them as failed, other scopes work, and no route fetches, clones or writes cache metadata", () => { + const { base, config } = legacyWorld(); + const inv = loadInventory(config); + const cacheBefore = readdirSync(join(base, ".mozak-cache")).sort(); + const idx = executeOperation(inv, "scopes", {}); + assert.equal(idx.exitCode, 6); + const rows = idx.data.scopes as { id: string; status: string; code?: string; message?: string }[]; + assert.deepEqual(rows.map((r) => [r.id, r.status, r.code ?? null]), [["home", "ok", null], ["tool", "failed", "legacy-repo-scope"], ["web", "failed", "legacy-repo-scope"]]); + assert.match(rows[1]!.message!, /mozak scope move --scope tool --to creations\/tool/); + assert.equal(executeOperation(inv, "context", { scope: "home" }).exitCode, 0); + for (const id of ["tool", "web"]) { + for (const [op, args, actor] of [["context", {}, "agent"], ["plans", {}, "agent"], ["check", {}, "agent"], ["render", {}, "agent"], ["sync", {}, "agent"], ["pull", {}, "owner"]] as const) { + const out = executeOperation(inv, op, { scope: id, ...args }, actor); + assert.equal((out.data.issues as { code: string }[])[0]?.code, "legacy-repo-scope", `${op} ${id}: ${JSON.stringify(out.data)}`); + assert.notEqual(out.exitCode, 0); + } + } + // sync without a scope and the all-scope reads touch no remote at all. + const sync = executeOperation(inv, "sync", {}); + assert.deepEqual(sync.data.remote, []); + assert.equal(executeOperation(inv, "plans", { all: true }).exitCode, 6); + assert.deepEqual(readdirSync(join(base, ".mozak-cache")).sort(), cacheBefore, "no meta file, no clone"); + assert.ok(!existsSync(join(base, ".mozak-cache", "web.meta.json"))); +}); + +test("the plugin model shows a legacy entry as a failed row with the move command", () => { + const { config } = legacyWorld(); + const model = loadScopesModel(config); + const web = model.scopes.find((s) => s.id === "web")!; + assert.equal(web.errorCode, "legacy-repo-scope"); + assert.match(web.errorMessage!, /mozak scope move --scope web/); + assert.equal(model.scopes.find((s) => s.id === "home")!.errorCode, null); +}); + +test("local reads never fetch: a legacy entry whose origin is gone costs no network and writes no cache metadata", () => { + const { base, config } = legacyWorld(); + const inv = loadInventory(config); + for (const op of ["context", "check"]) assert.equal(executeOperation(inv, op, { scope: "home" }).exitCode, 0, op); + assert.equal(executeOperation(inv, "plans", { all: true }).exitCode, 6); + assert.equal(executeOperation(inv, "sync", { local: true }).data.remote instanceof Array, true); + for (const id of ["home", "tool", "web"]) assert.ok(!existsSync(join(base, ".mozak-cache", `${id}.meta.json`)), id); +}); + +test("legacy entry shape stays strict, v2 has no legacy keys, and local-entry digests are unchanged", () => { + const { base } = legacyWorld(); + const inv = join(base, "i.json"); + const load = (scopes: unknown[], format = "mozak.local/v3") => { writeFileSync(inv, JSON.stringify({ format, scopes })); return loadInventory(inv); }; + assert.throws(() => load([{ id: "a", remote: "github:o/r", root: "x" }]), /exactly one of "root" or "remote"/); + assert.throws(() => load([{ id: "a", root: "y", plans: "x" }]), /exactly one of "root" or "remote"/); + assert.throws(() => load([{ id: "a", remote: "github:o/r", extra: 1 }]), /unknown key "extra"/); + assert.throws(() => load([{ id: "../a", remote: "github:o/r" }]), /must use letters, digits/); + assert.throws(() => load([{ remote: "github:o/r" }]), /scope id must be a nonempty string/); + assert.throws(() => load([{ id: "a", remote: "github:o/r", x: 1 }]), /"x" in scope entry must be an object/); + assert.throws(() => load([{ id: "a", remote: "github:o/r" }], "mozak.local/v2"), /unknown key "remote"/); + // Old remote values that 0.5.0 refused are now only a refused entry: no URL parsing, no network. + assert.equal(load([{ id: "a", remote: "ftp://x/y", ref: "--upload-pack=x" }]).scopes[0]!.refused?.code, "legacy-repo-scope"); + // A local entry's digest is the v2 shape (format, id, canonical root), so it is the same before and after 0.6.0. + const local = load([{ id: "home", root: "home" }]); + const expected = createHash("sha256").update(JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "home", root: join(realpathSync(base), "home") }] }), "utf8").digest("hex"); + assert.equal(local.digest, expected); + assert.equal(load([{ id: "home", root: "home", focus: [] }]).digest, expected, "focus never changes the digest"); + writeFileSync(inv, JSON.stringify({ format: "mozak.local/v2", scopes: [] })); + assert.equal(loadInventory(inv).format, "mozak.local/v2"); +}); + +test("loaded inventory: entries sorted by id, x flagged per entry, the file path kept but not serialized, remote named in the message", () => { + const { base } = legacyWorld(); + const inv = join(base, "i.json"); + writeFileSync(inv, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "web", ref: "main" }, { id: "home", root: "home", x: {} }, { id: "tool", remote: "github:o/tool", plans: "creations/tool" }] })); + const loaded = loadInventory(inv); + assert.deepEqual(loaded.scopes.map((s) => s.id), ["home", "tool", "web"]); + assert.deepEqual(loaded.scopes.map((s) => s.inventoryExtensionsIgnored === true), [true, false, false]); + assert.equal(loaded.path, inv); + assert.equal(JSON.stringify(loaded).includes("\"path\""), false); + assert.match(loaded.scopes[1]!.refused!.message, /is a repo scope \(remote github:o\/tool\)/); + assert.match(loaded.scopes[2]!.refused!.message, /^scope "web" is a repo scope, which mozak/); + // A metadata file naming an empty or relative clone path falls back to the cache, even when that path holds plans. + writeFileSync(join(base, ".mozak-cache", "web.meta.json"), JSON.stringify({ fullClone: "" })); + assert.equal(loadInventory(inv).scopes[2]!.root, join(realpathSync(base), ".mozak-cache", "web")); + const cwd = process.cwd(); + try { + process.chdir(base); + writeFileSync(join(base, ".mozak-cache", "web.meta.json"), JSON.stringify({ fullClone: "home" })); + assert.equal(loadInventory(inv).scopes[2]!.root, join(realpathSync(base), ".mozak-cache", "web")); + } finally { process.chdir(cwd); } +}); + +test("a repo-mode entry reads the plans from a 0.5.0 full clone while it still holds them, else from the cache", () => { + const { base, config } = legacyWorld(); + const clone = join(base, "Downloads", "web"); + scope("web", clone); + writeFileSync(join(base, ".mozak-cache", "web.meta.json"), JSON.stringify({ lastFetchAt: null, lastError: null, fullClone: clone })); + assert.equal(loadInventory(config).scopes.find((s) => s.id === "web")!.root, realpathSync(clone)); + rmSync(join(clone, "mozak.json")); + assert.equal(loadInventory(config).scopes.find((s) => s.id === "web")!.root, join(realpathSync(base), ".mozak-cache", "web")); + writeFileSync(join(base, ".mozak-cache", "web.meta.json"), "{ broken"); + assert.equal(loadInventory(config).scopes.find((s) => s.id === "web")!.root, join(realpathSync(base), ".mozak-cache", "web")); +}); + +test("scope move reads both legacy kinds and the moved scopes then work", () => { + const { config } = legacyWorld(); + const owner = { ownerRef: "synthetic:owner", ownerMessageAt: NOW, reason: "vault-only" }; + assert.equal(moveScope(config, { scope: "tool", to: "creations/tool", ...owner }).inPlace, true); + assert.equal(moveScope(config, { scope: "web", to: "projects/web", ...owner }).files.length, 4); + const inv = loadInventory(config); + assert.equal(executeOperation(inv, "scopes", {}).exitCode, 0); + for (const id of ["home", "tool", "web"]) assert.equal(executeOperation(inv, "check", { scope: id }).exitCode, 0, id); +}); diff --git a/packages/core/test/remote.test.ts b/packages/core/test/remote.test.ts deleted file mode 100644 index 3683913..0000000 --- a/packages/core/test/remote.test.ts +++ /dev/null @@ -1,203 +0,0 @@ -import { test, after } from "node:test"; -import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { executeOperation, initScopeState, loadInventory, parseRemoteSpec, writeRemoteMeta, readRemoteMeta } from "../src/index.ts"; -import { vaultTemp } from "./vault-temp.ts"; - -const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); -const made: string[] = []; -after(() => { for (const d of made) { if (!d.includes("/mozak-remote-")) throw new Error(d); rmSync(d, { recursive: true, force: true }); } }); - -const g = (cwd: string, ...args: string[]) => - execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", "-c", "protocol.file.allow=always", ...args], { cwd, encoding: "utf8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } }); - -const content = (title: string) => ({ - title, purpose: "Keep agreed direction", - outcomes: [{ id: "o1", statement: "Context can be recovered", acceptance: "objective", criterion: "A new process reads the same direction" }], - constraints: [], nonGoals: [], rationale: "r", questions: [], sources: [], -}); - -/** Bare origin with an initialised scope plus a decoy file that must never be checked out. */ -function fixture() { - const base = vaultTemp(join(scratch, "mozak-remote-")); - made.push(base); - const bare = join(base, "origin.git"); - const seed = join(base, "seed"); - g(base, "init", "--bare", "-b", "main", bare); - mkdirSync(seed); - g(seed, "init", "-b", "main"); - writeFileSync(join(seed, "README.md"), "# r\n"); - writeFileSync(join(seed, "AGENTS.md"), "# a\n"); - writeFileSync(join(seed, "big.bin"), "decoy"); - initScopeState({ id: "genome-mcp", root: seed }, { operationId: "init-1", scopeId: "genome-mcp", kind: "project", title: "Genome", expectedAbsent: { graph: true, bridge: true }, ownerRef: "host:t", ownerMessageAt: "2026-10-12T08:50:00.000Z" }); - g(seed, "add", "."); g(seed, "commit", "-m", "seed"); g(seed, "remote", "add", "origin", bare); g(seed, "push", "origin", "main"); - const inv = join(base, "inventory.json"); - writeFileSync(inv, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "genome-mcp", remote: `file://${bare}`, ref: "main" }] })); - return { base, bare, inv }; -} -const exec = (inv: string, op: string, args: unknown, actor: "agent" | "owner" = "agent") => executeOperation(loadInventory(inv), op, args, actor); - -test("inventory: remote entry validation stays strict, v2 still accepted", () => { - const base = vaultTemp(join(scratch, "mozak-remote-")); made.push(base); - const inv = join(base, "i.json"); - const bad = (scopes: unknown[], format = "mozak.local/v3") => { writeFileSync(inv, JSON.stringify({ format, scopes })); return () => loadInventory(inv); }; - assert.throws(bad([{ id: "a", remote: "github:o/r", root: "x" }]), /exactly one/); - assert.throws(bad([{ id: "a", remote: "github:o/r", extra: 1 }]), /unknown key/); - assert.throws(bad([{ id: "a", remote: "ftp://x/y" }]), /remote must look like/); - assert.throws(bad([{ id: "a", remote: "github:o/r", ref: "--upload-pack=x" }]), /ref/); - assert.throws(bad([{ id: "../a", remote: "github:o/r" }]), /cache folder/); - assert.throws(bad([{ id: "a", remote: "github:o/r" }], "mozak.local/v2"), /unknown key "remote"/); - const ok = bad([{ id: "a", remote: "github:pitfa19/genome-mcp" }])(); - assert.equal(ok.scopes[0]?.remote?.ref, "main"); - assert.equal(ok.scopes[0]?.remote?.url, "https://github.com/pitfa19/genome-mcp.git"); - assert.equal(ok.scopes[0]?.root, join(realpathOf(base), ".mozak-cache", "a")); - writeFileSync(inv, JSON.stringify({ format: "mozak.local/v2", scopes: [] })); - assert.equal(loadInventory(inv).format, "mozak.local/v2"); - assert.equal(parseRemoteSpec("github:a/b/c"), null); -}); -function realpathOf(p: string) { return execFileSync("realpath", [p], { encoding: "utf8" }).trim(); } - -test("check warns about a sidecar file in a repo-mode remote scope even though it is never read", () => { - const { inv, base } = fixture(); - assert.equal(exec(inv, "context", { scope: "genome-mcp" }).exitCode, 0); - const codes = () => (exec(inv, "check", { scope: "genome-mcp" }).data.issues as { code: string }[]).map((i) => i.code); - assert.equal(codes().includes("annotations-on-remote"), false); - writeFileSync(join(base, ".mozak-cache", "genome-mcp", "mozak.annotations.json"), "{ not json"); - assert.equal(codes().includes("annotations-on-remote"), true); - assert.equal(codes().includes("annotations-invalid"), false); -}); - -test("first read fetches a sparse copy with only the four files", () => { - const { inv, base } = fixture(); - const out = exec(inv, "context", { scope: "genome-mcp" }); - assert.equal(out.exitCode, 0, JSON.stringify(out.data)); - const remote = (out.data.remote as any[])[0]; - assert.equal(remote.stale, false); - const cache = join(base, ".mozak-cache", "genome-mcp"); - assert.ok(existsSync(join(cache, "mozak.json"))); - assert.ok(existsSync(join(cache, "AGENTS.md"))); - assert.ok(!existsSync(join(cache, "big.bin"))); - assert.ok(existsSync(join(cache, ".git"))); - const idx = exec(inv, "scopes", {}); - const row = (idx.data.scopes as any[])[0]; - assert.equal(row.remote.startsWith("file://"), true); - assert.equal(row.stale, false); -}); - -test("offline: cached copy is used and marked stale; fresh copy skips fetch", () => { - const { inv, base, bare } = fixture(); - assert.equal(exec(inv, "context", { scope: "genome-mcp" }).exitCode, 0); - // Within ten minutes nothing is fetched, even with the origin gone. - rmSync(bare, { recursive: true }); - const fresh = exec(inv, "context", { scope: "genome-mcp" }); - assert.equal((fresh.data.remote as any[])[0].stale, false); - // Age the last fetch beyond the window. - const meta = readRemoteMeta(base, "genome-mcp"); - writeRemoteMeta(base, "genome-mcp", { ...meta, lastFetchAt: new Date(Date.now() - 11 * 60_000).toISOString() }); - const stale = exec(inv, "context", { scope: "genome-mcp" }); - assert.equal(stale.exitCode, 0); - assert.equal((stale.data.remote as any[])[0].stale, true); - assert.ok((stale.data.issues as any[]).some((i) => i.code === "remote-stale")); - const sync = exec(inv, "sync", {}); - assert.equal(sync.exitCode, 6); - // A write is refused while stale. - const w = exec(inv, "propose", { scope: "genome-mcp", request: {} }); - assert.equal((w.data as any).status, "remote-stale"); -}); - -test("write commits only mozak.json and mozak.md and pushes; sync pulls it elsewhere", () => { - const { inv, base, bare } = fixture(); - const ctx = exec(inv, "context", { scope: "genome-mcp" }); - const req = { operationId: "op-1", scopeId: "genome-mcp", expected: ctx.data.snapshot, action: "propose", payload: { planId: "p1", content: content("Remote plan") } }; - // An unrelated dirty file in the cache must not be committed. - writeFileSync(join(base, ".mozak-cache", "genome-mcp", "README.md"), "# edited\n"); - const out = exec(inv, "propose", { scope: "genome-mcp", request: req }); - assert.equal(out.exitCode, 0, JSON.stringify(out.data)); - assert.deepEqual((out.data as any).remotePush, { committed: true, pushed: true }); - const verify = join(base, "verify"); - g(base, "clone", bare, verify); - assert.match(readFileSync(join(verify, "mozak.json"), "utf8"), /Remote plan/); - assert.equal(readFileSync(join(verify, "README.md"), "utf8"), "# r\n"); - assert.equal(g(verify, "show", "--name-only", "--format=", "HEAD").trim().split("\n").sort().join(","), "mozak.json,mozak.md"); - const plans = exec(inv, "plans", { scope: "genome-mcp" }); - assert.equal((plans.data as any).groups.awaiting.count, 1); - // Owner rules unchanged: an agent cannot decide. - assert.equal((exec(inv, "decide", { scope: "genome-mcp", request: {} }).data as any).status, "not-permitted"); -}); - -test("push failure keeps the local commit and reports it; sync recovers", () => { - const { inv, base, bare } = fixture(); - const ctx = exec(inv, "context", { scope: "genome-mcp" }); - g(bare, "config", "receive.denyCurrentBranch", "refuse"); - writeFileSync(join(bare, "hooks-pre-receive-marker"), ""); - mkdirSync(join(bare, "hooks"), { recursive: true }); - writeFileSync(join(bare, "hooks", "pre-receive"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); - const req = { operationId: "op-2", scopeId: "genome-mcp", expected: ctx.data.snapshot, action: "propose", payload: { planId: "p2", content: content("Queued plan") } }; - const out = exec(inv, "propose", { scope: "genome-mcp", request: req }); - assert.equal(out.exitCode, 5); - assert.ok((out.data.issues as any[]).some((i) => i.code === "remote-push-failed")); - rmSync(join(bare, "hooks", "pre-receive")); - const sync = exec(inv, "sync", { scope: "genome-mcp" }); - assert.equal(sync.exitCode, 0, JSON.stringify(sync.data)); - const verify = join(base, "verify"); - g(base, "clone", bare, verify); - assert.match(readFileSync(join(verify, "mozak.json"), "utf8"), /Queued plan/); -}); - -test("pull makes a full clone, reads prefer it, and an existing foreign destination is refused", () => { - const { inv, base, bare } = fixture(); - const dest = join(base, "full"); - const out = exec(inv, "pull", { scope: "genome-mcp", into: dest }, "owner"); - assert.equal(out.exitCode, 0, JSON.stringify(out.data)); - assert.ok(existsSync(join(dest, "big.bin"))); - assert.equal(readRemoteMeta(base, "genome-mcp").fullClone, dest); - // Agents cannot pull. - assert.equal((exec(inv, "pull", { scope: "genome-mcp" }, "agent").data as any).status, "not-permitted"); - // Re-pull into the same repo is fine. - assert.equal(exec(inv, "pull", { scope: "genome-mcp", into: dest }, "owner").exitCode, 0); - // Reads now use the full clone. - const scopes = exec(inv, "scopes", {}); - const row = (scopes.data.scopes as any[])[0]; - assert.equal(row.source, "full-clone"); - assert.equal(realpathOf(row.root), realpathOf(dest)); - // Writes go through the full clone and push. - const ctx = exec(inv, "context", { scope: "genome-mcp" }); - const req = { operationId: "op-3", scopeId: "genome-mcp", expected: ctx.data.snapshot, action: "propose", payload: { planId: "p3", content: content("Full plan") } }; - assert.equal(exec(inv, "propose", { scope: "genome-mcp", request: req }).exitCode, 0); - const verify = join(base, "verify"); - g(base, "clone", bare, verify); - assert.match(readFileSync(join(verify, "mozak.json"), "utf8"), /Full plan/); - // A different directory is refused. - const other = join(base, "other"); - mkdirSync(other); - writeFileSync(join(other, "x"), "x"); - assert.equal((exec(inv, "pull", { scope: "genome-mcp", into: other }, "owner").data as any).status, "pull-destination-exists"); -}); - -test("not a scope: remote without mozak.json fails clearly", () => { - const base = vaultTemp(join(scratch, "mozak-remote-")); made.push(base); - const bare = join(base, "o.git"), seed = join(base, "s"); - g(base, "init", "--bare", "-b", "main", bare); - mkdirSync(seed); g(seed, "init", "-b", "main"); writeFileSync(join(seed, "README.md"), "x"); - g(seed, "add", "."); g(seed, "commit", "-m", "x"); g(seed, "remote", "add", "origin", bare); g(seed, "push", "origin", "main"); - const inv = join(base, "inventory.json"); - writeFileSync(inv, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "plain", remote: `file://${bare}` }] })); - const out = exec(inv, "context", { scope: "plain" }); - assert.equal((out.data as any).status, "scope-uninitialized"); -}); - -test("sync warns when the inventory dir is a git repo that does not ignore .mozak-cache", () => { - const { inv, base } = fixture(); - g(base, "init", "-b", "main", "work"); - // Put the inventory inside a fresh git repo. - const repo = join(base, "work"); - writeFileSync(join(repo, "inventory.json"), readFileSync(inv, "utf8")); - const out = exec(join(repo, "inventory.json"), "sync", {}); - assert.ok((out.data.issues as any[]).some((i) => i.code === "cache-not-ignored"), JSON.stringify(out.data)); - writeFileSync(join(repo, ".gitignore"), ".mozak-cache/\n"); - const again = exec(join(repo, "inventory.json"), "sync", {}); - assert.ok(!(again.data.issues as any[]).some((i) => i.code === "cache-not-ignored")); -}); diff --git a/packages/core/test/s2-offline.test.ts b/packages/core/test/s2-offline.test.ts deleted file mode 100644 index 75d8895..0000000 --- a/packages/core/test/s2-offline.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -// S2 offline reads: local and vault-plans reads never fetch; remote reads keep the 10-minute fetch, mark -// remoteFreshness, and after a failed fetch do not retry the network on every read. Local bare repos only. -import { test, after } from "node:test"; -import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { executeOperation, initScopeState, loadInventory, readRemoteMeta, writeRemoteMeta } from "../src/index.ts"; -import { vaultTemp } from "./vault-temp.ts"; - -const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); -const made: string[] = []; -after(() => { for (const d of made) { if (!d.includes("/mozak-s2off-")) throw new Error(d); rmSync(d, { recursive: true, force: true }); } }); -const g = (cwd: string, ...args: string[]) => - execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", "-c", "protocol.file.allow=always", ...args], { cwd, encoding: "utf8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } }); -const init = (id: string, root: string) => initScopeState({ id, root }, { operationId: `init-${id}`, scopeId: id, kind: "project", title: id, expectedAbsent: { graph: true, bridge: true }, ownerRef: "host:t", ownerMessageAt: "2026-10-12T08:50:00.000Z" }); - -function fixture() { - const base = vaultTemp(join(scratch, "mozak-s2off-")); - made.push(base); - const bare = join(base, "origin.git"); - const seed = join(base, "seed"); - g(base, "init", "--bare", "-b", "main", bare); - mkdirSync(seed); - g(seed, "init", "-b", "main"); - writeFileSync(join(seed, "README.md"), "# r\n"); - writeFileSync(join(seed, "AGENTS.md"), "# a\n"); - init("repo", seed); - g(seed, "add", "."); g(seed, "commit", "-m", "seed"); g(seed, "remote", "add", "origin", bare); g(seed, "push", "origin", "main"); - // A local scope and a vault-plans scope whose repo URL does not exist: reads must not need it. - const local = join(base, "local"); - const plans = join(base, "notes", "tool"); - for (const dir of [local, plans]) { mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, "README.md"), "# r\n"); writeFileSync(join(dir, "AGENTS.md"), "# a\n"); } - init("local", local); - const inv = join(base, "inventory.json"); - writeFileSync(inv, JSON.stringify({ format: "mozak.local/v3", scopes: [ - { id: "repo", remote: `file://${bare}`, ref: "main" }, - { id: "local", root: "local" }, - { id: "tool", remote: `file://${join(base, "missing.git")}`, plans: "notes/tool" }, - ] })); - init("tool", loadInventory(inv).scopes[2]!.root); - return { base, bare, inv }; -} -const exec = (inv: string, op: string, args: unknown) => executeOperation(loadInventory(inv), op, args, "agent"); -type Row = { scope: string; stale: boolean; remoteFreshness: string }; -const row = (out: ReturnType, scope: string) => (out.data.remote as Row[]).find((r) => r.scope === scope)!; -const metaFile = (base: string, id: string) => join(base, ".mozak-cache", `${id}.meta.json`); - -test("local and vault-plans reads never fetch or write cache metadata", () => { - const { inv, base } = fixture(); - assert.equal(exec(inv, "context", { scope: "local" }).exitCode, 0); - assert.equal(exec(inv, "check", { scope: "local" }).exitCode, 0); - const vault = exec(inv, "context", { scope: "tool" }); - assert.equal(vault.exitCode, 0, JSON.stringify(vault.data.issues)); - assert.deepEqual(row(vault, "tool"), { scope: "tool", remote: `file://${join(base, "missing.git")}`, ref: "main", stale: false, lastFetchAt: null, source: "vault", remoteFreshness: "local" } as unknown as Row); - assert.equal(existsSync(metaFile(base, "tool")), false); - assert.equal(existsSync(metaFile(base, "local")), false); - assert.equal(existsSync(metaFile(base, "repo")), false, "no read touched the repo-mode scope"); -}); - -test("remote reads: fetched, then cached for ten minutes, then offline without retrying on every read", () => { - const { inv, base, bare } = fixture(); - assert.equal(row(exec(inv, "context", { scope: "repo" }), "repo").remoteFreshness, "fetched"); - assert.equal(row(exec(inv, "context", { scope: "repo" }), "repo").remoteFreshness, "cached"); - // Go offline and age the last fetch past the window. - rmSync(bare, { recursive: true }); - const meta = readRemoteMeta(base, "repo"); - writeRemoteMeta(base, "repo", { ...meta, lastFetchAt: new Date(Date.now() - 11 * 60_000).toISOString() }); - const first = exec(inv, "context", { scope: "repo" }); - assert.equal(first.exitCode, 0); - assert.deepEqual([row(first, "repo").stale, row(first, "repo").remoteFreshness], [true, "offline"]); - const afterFailure = readFileSync(metaFile(base, "repo"), "utf8"); - assert.ok(JSON.parse(afterFailure).lastAttemptAt); - // The next reads use the cached copy and do not try the network again: the metadata is untouched. - for (const op of ["context", "check", "plans"]) { - const out = exec(inv, op, op === "plans" ? { all: true } : { scope: "repo" }); - assert.equal(row(out, "repo").remoteFreshness, "offline", op); - assert.equal(readFileSync(metaFile(base, "repo"), "utf8"), afterFailure, `${op} did not retry the fetch`); - } - // sync always tries. - assert.equal(exec(inv, "sync", { scope: "repo" }).exitCode, 6); - assert.notEqual(readFileSync(metaFile(base, "repo"), "utf8"), afterFailure); - // Once the failed attempt is ten minutes old, a read tries again. - const m2 = readRemoteMeta(base, "repo"); - writeRemoteMeta(base, "repo", { ...m2, lastAttemptAt: new Date(Date.now() - 11 * 60_000).toISOString() }); - exec(inv, "context", { scope: "repo" }); - assert.ok(Date.parse(readRemoteMeta(base, "repo").lastAttemptAt!) > Date.now() - 60_000); -}); diff --git a/packages/core/test/vault-plans.test.ts b/packages/core/test/vault-plans.test.ts deleted file mode 100644 index 3e8146f..0000000 --- a/packages/core/test/vault-plans.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { test, after } from "node:test"; -import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { executeOperation, initScopeState, loadInventory, readRemoteMeta, setVisibilityChecker } from "../src/index.ts"; -import { vaultTemp } from "./vault-temp.ts"; - -const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); -const made: string[] = []; -after(() => { for (const d of made) { if (!d.includes("/mozak-vault-")) throw new Error(d); rmSync(d, { recursive: true, force: true }); } }); - -const g = (cwd: string, ...args: string[]) => - execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", "-c", "protocol.file.allow=always", ...args], { cwd, encoding: "utf8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } }); - -const content = (title: string) => ({ - title, purpose: "Keep agreed direction", - outcomes: [{ id: "first-step", statement: "Context can be recovered", acceptance: "objective", criterion: "A new process reads the same direction" }], - constraints: [], nonGoals: [], rationale: "r", questions: [], sources: [], -}); - -/** Snapshot of everything git knows about a bare repo: every ref and every object. */ -function repoState(bare: string): string { - return [g(bare, "for-each-ref", "--format=%(refname) %(objectname)"), g(bare, "count-objects", "-v"), readdirSync(join(bare, "refs", "heads")).sort().join(",")].join("\n"); -} - -/** A public-style code repo (no plan files) plus a vault folder holding the scope. */ -function fixture() { - const base = vaultTemp(join(scratch, "mozak-vault-")); - made.push(base); - const bare = join(base, "code.git"); - const seed = join(base, "seed"); - g(base, "init", "--bare", "-b", "main", bare); - mkdirSync(seed); - g(seed, "init", "-b", "main"); - writeFileSync(join(seed, "README.md"), "# code\n"); - writeFileSync(join(seed, "index.js"), "console.log(1)\n"); - g(seed, "add", "."); g(seed, "commit", "-m", "code"); g(seed, "remote", "add", "origin", bare); g(seed, "push", "origin", "main"); - const vault = join(base, "vault"); - const plans = join(vault, "creations", "tool"); - mkdirSync(plans, { recursive: true }); - writeFileSync(join(plans, "README.md"), "# tool plans\n"); - writeFileSync(join(plans, "AGENTS.md"), "# agents\n"); - const inv = join(vault, "mozak-inventory.json"); - writeFileSync(inv, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "tool", remote: `file://${bare}`, plans: "creations/tool" }] })); - const entry = loadInventory(inv).scopes[0]!; - initScopeState(entry, { operationId: "init-1", scopeId: "tool", kind: "project", title: "Tool", expectedAbsent: { graph: true, bridge: true }, ownerRef: "host:t", ownerMessageAt: "2026-10-18T08:50:00.000Z" }); - return { base, bare, vault, plans, inv }; -} -const exec = (inv: string, op: string, args: unknown, actor: "agent" | "owner" = "agent") => executeOperation(loadInventory(inv), op, args, actor); - -test("inventory: plans makes a vault scope; shape stays strict; old digests unchanged", () => { - const base = vaultTemp(join(scratch, "mozak-vault-")); made.push(base); - const inv = join(base, "i.json"); - const load = (scopes: unknown[]) => { writeFileSync(inv, JSON.stringify({ format: "mozak.local/v3", scopes })); return loadInventory(inv); }; - const before = load([{ id: "a", remote: "github:o/r" }, { id: "b", root: "b" }]).digest; - // Adding a vault entry elsewhere does not change how existing entries hash. - const plain = load([{ id: "a", remote: "github:o/r" }, { id: "b", root: "b" }]); - assert.equal(plain.digest, before); - const v = load([{ id: "a", remote: "github:o/r", plans: "notes/a" }]).scopes[0]!; - assert.equal(v.remote?.plansMode, "vault"); - assert.equal(v.root, join(execFileSync("realpath", [base], { encoding: "utf8" }).trim(), "notes", "a")); - assert.equal(load([{ id: "a", remote: "github:o/r" }]).scopes[0]!.remote?.plansMode, "repo"); - assert.notEqual(load([{ id: "a", remote: "github:o/r", plans: "notes/a" }]).digest, load([{ id: "a", remote: "github:o/r" }]).digest); - assert.throws(() => load([{ id: "a", remote: "github:o/r", plans: "" }]), /plans must be a nonempty path/); - assert.throws(() => load([{ id: "a", remote: "github:o/r", plans: 3 }]), /plans must be a nonempty path/); - assert.throws(() => load([{ id: "a", remote: "github:o/r", plans: ".mozak-cache/a" }]), /must not be inside \.mozak-cache/); - assert.throws(() => load([{ id: "a", remote: "github:o/r", plans: "x", root: "y" }]), /exactly one/); - assert.throws(() => load([{ id: "a", root: "y", plans: "x" }]), /unknown key "plans"/); - assert.throws(() => load([{ id: "a", remote: "github:o/r", plans: "x" }, { id: "b", root: "x" }]), /same root/); -}); - -test("vault scope: reads, writes, sync and render never touch the repo", () => { - const { inv, bare, base, plans } = fixture(); - const repoBefore = repoState(bare); - const ctx = exec(inv, "context", { scope: "tool" }); - assert.equal(ctx.exitCode, 0, JSON.stringify(ctx.data)); - const status = (ctx.data.remote as any[])[0]; - assert.equal(status.source, "vault"); - assert.equal(status.stale, false); - const req = { operationId: "op-1", scopeId: "tool", expected: ctx.data.snapshot, action: "propose", payload: { planId: "p1", content: content("Vault plan") } }; - const out = exec(inv, "propose", { scope: "tool", request: req }); - assert.equal(out.exitCode, 0, JSON.stringify(out.data)); - assert.equal((out.data as any).remotePush, undefined); - assert.match(readFileSync(join(plans, "mozak.json"), "utf8"), /Vault plan/); - assert.match(readFileSync(join(plans, "mozak.md"), "utf8"), /Vault plan/); - const sync = exec(inv, "sync", {}); - assert.equal(sync.exitCode, 0); - assert.equal((sync.data.remote as any[])[0].source, "vault"); - const render = exec(inv, "render", { all: true }); - assert.notEqual((render.data.scopes as any[])[0].result, "remote-skipped"); - assert.equal(exec(inv, "check", { scope: "tool" }).exitCode, 0); - // No cache, no clone, no git work anywhere for this scope. - assert.ok(!existsSync(join(base, "vault", ".mozak-cache", "tool"))); - assert.ok(!existsSync(join(plans, ".git"))); - assert.equal(repoState(bare), repoBefore); -}); - -test("vault scope works with no network and with the origin gone", () => { - const { inv, bare } = fixture(); - rmSync(bare, { recursive: true }); - const ctx = exec(inv, "context", { scope: "tool" }); - assert.equal(ctx.exitCode, 0); - const req = { operationId: "op-off", scopeId: "tool", expected: ctx.data.snapshot, action: "propose", payload: { planId: "p1", content: content("Offline") } }; - assert.equal(exec(inv, "propose", { scope: "tool", request: req }).exitCode, 0); - const idx = exec(inv, "scopes", {}); - const row = (idx.data.scopes as any[])[0]; - assert.equal(row.source, "vault"); - assert.equal(row.remote.startsWith("file://"), true); - assert.equal(row.stale, false); -}); - -test("pull of a vault scope clones code only and leaves the plans untouched", () => { - const { inv, base, plans } = fixture(); - const plansBefore = readFileSync(join(plans, "mozak.json")); - const dest = join(base, "Downloads", "tool"); - const out = exec(inv, "pull", { scope: "tool", into: dest }, "owner"); - assert.equal(out.exitCode, 0, JSON.stringify(out.data)); - assert.ok(existsSync(join(dest, "index.js"))); - assert.ok(!existsSync(join(dest, "mozak.json"))); - assert.ok(!existsSync(join(dest, "mozak.md"))); - assert.deepEqual(readFileSync(join(plans, "mozak.json")), plansBefore); - // The scope root is still the vault folder, not the clone. - assert.equal(loadInventory(inv).scopes[0]!.root, execFileSync("realpath", [plans], { encoding: "utf8" }).trim()); - assert.equal(readRemoteMeta(join(base, "vault"), "tool").fullClone, null); - // Deleting the clone loses nothing. - rmSync(dest, { recursive: true }); - assert.equal(exec(inv, "context", { scope: "tool" }).exitCode, 0); -}); - -test("vault scopes are never blocked or warned for being public; visibility is only a label", () => { - const { inv } = fixture(); - let calls = 0; - const restore = setVisibilityChecker(() => { calls++; return "public"; }); - try { - const ctx = exec(inv, "context", { scope: "tool" }); - const req = { operationId: "op-v", scopeId: "tool", expected: ctx.data.snapshot, action: "propose", payload: { planId: "p1", content: content("Public code, private plans") } }; - assert.equal(exec(inv, "propose", { scope: "tool", request: req }).exitCode, 0); - assert.equal(calls, 0, "writes and reads never ask about visibility"); - const sync = exec(inv, "sync", {}); - assert.equal(sync.exitCode, 0); - assert.ok(!(sync.data.issues as any[]).some((i) => i.code === "public-repo-plans")); - assert.equal(calls, 1, "sync caches the answer once for the sidebar label"); - exec(inv, "sync", {}); - assert.equal(calls, 1); - } finally { restore(); } -}); - -test("spec files resolve inside the plans folder", () => { - const { inv, plans } = fixture(); - assert.ok(statSync(plans).isDirectory()); - mkdirSync(join(plans, "docs")); - writeFileSync(join(plans, "docs", "spec.md"), "# spec\n"); - let ctx = exec(inv, "context", { scope: "tool" }); - const p = { operationId: "op-p", scopeId: "tool", expected: ctx.data.snapshot, action: "propose", payload: { planId: "p1", content: content("Spec plan") } }; - assert.equal(exec(inv, "propose", { scope: "tool", request: p }).exitCode, 0); - const show = exec(inv, "review", { scope: "tool", plan: "p1" }); - ctx = exec(inv, "context", { scope: "tool" }); - const d = { operationId: "op-d", scopeId: "tool", expected: ctx.data.snapshot, action: "approve-direction", payload: { planId: "p1", revisionId: (show.data as any).review.revisionId, reviewDigest: (show.data as any).review.reviewDigest, ownerRef: "host:t", ownerMessageAt: "2026-10-18T09:00:00.000Z", reason: "ok" } }; - assert.equal(exec(inv, "decide", { scope: "tool", request: d }, "owner").exitCode, 0); - const graph = JSON.parse(readFileSync(join(plans, "mozak.json"), "utf8")); - const accepted = graph.plans[0].accepted.id; - ctx = exec(inv, "context", { scope: "tool" }); - const bounds = { summary: "s", allowedPaths: ["src"], excludedActions: [], outcomeChecks: [{ outcomeId: "first-step", criterion: "c" }], limitations: [] }; - const a = { operationId: "op-a", scopeId: "tool", expected: ctx.data.snapshot, action: "attach-spec", payload: { planId: "p1", acceptedRevisionId: accepted, path: "docs/spec.md", bounds, discussionDigest: null } }; - const attached = exec(inv, "attach-spec", { scope: "tool", request: a }); - assert.equal(attached.exitCode, 0, JSON.stringify(attached.data)); -}); diff --git a/packages/core/test/visibility.test.ts b/packages/core/test/visibility.test.ts deleted file mode 100644 index c02f084..0000000 --- a/packages/core/test/visibility.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { test, after } from "node:test"; -import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { executeOperation, githubSlug, initScopeState, loadInventory, readRemoteMeta, setVisibilityChecker, writeRemoteMeta, type Visibility } from "../src/index.ts"; -import { vaultTemp } from "./vault-temp.ts"; - -const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); -const made: string[] = []; -after(() => { for (const d of made) { if (!d.includes("/mozak-vis-")) throw new Error(d); rmSync(d, { recursive: true, force: true }); } }); - -const g = (cwd: string, ...args: string[]) => - execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", "-c", "protocol.file.allow=always", ...args], { cwd, encoding: "utf8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } }); - -const content = (title: string) => ({ - title, purpose: "p", - outcomes: [{ id: "first-step", statement: "s", acceptance: "objective", criterion: "c" }], - constraints: [], nonGoals: [], rationale: "r", questions: [], sources: [], -}); - -/** A repo-mode remote scope: plans inside the repo. */ -function fixture() { - const base = vaultTemp(join(scratch, "mozak-vis-")); - made.push(base); - const bare = join(base, "origin.git"); - const seed = join(base, "seed"); - g(base, "init", "--bare", "-b", "main", bare); - mkdirSync(seed); - g(seed, "init", "-b", "main"); - writeFileSync(join(seed, "README.md"), "# r\n"); - writeFileSync(join(seed, "AGENTS.md"), "# a\n"); - initScopeState({ id: "team", root: seed }, { operationId: "init-1", scopeId: "team", kind: "project", title: "Team", expectedAbsent: { graph: true, bridge: true }, ownerRef: "host:t", ownerMessageAt: "2026-10-18T08:50:00.000Z" }); - g(seed, "add", "."); g(seed, "commit", "-m", "seed"); g(seed, "remote", "add", "origin", bare); g(seed, "push", "origin", "main"); - const inv = join(base, "inventory.json"); - writeFileSync(inv, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "team", remote: `file://${bare}`, ref: "main" }] })); - return { base, bare, inv }; -} -const exec = (inv: string, op: string, args: unknown, actor: "agent" | "owner" = "agent") => executeOperation(loadInventory(inv), op, args, actor); -function propose(inv: string, id: string) { - const ctx = exec(inv, "context", { scope: "team" }); - return exec(inv, "propose", { scope: "team", request: { operationId: id, scopeId: "team", expected: ctx.data.snapshot, action: "propose", payload: { planId: id, content: content(id) } } }); -} -function withChecker(answer: Visibility, fn: (calls: () => number) => void) { - let calls = 0; - const restore = setVisibilityChecker(() => { calls++; return answer; }); - try { fn(() => calls); } finally { restore(); } -} - -test("githubSlug accepts github forms and nothing else", () => { - assert.equal(githubSlug("github:Pitfa19/Mozak"), "pitfa19/mozak"); - assert.equal(githubSlug("https://github.com/o/r.git"), "o/r"); - assert.equal(githubSlug("git@github.com:o/r.git"), "o/r"); - assert.equal(githubSlug("https://gitlab.com/o/r"), null); - assert.equal(githubSlug("file:///tmp/x.git"), null); -}); - -test("public repo with plans inside: writes refused, sync and scopes warn, reads still work", () => { - const { inv, bare } = fixture(); - withChecker("public", () => { - const before = g(bare, "rev-parse", "main"); - const w = propose(inv, "p1"); - assert.equal(w.exitCode, 3); - assert.equal((w.data as any).status, "public-repo-plans"); - assert.match(String((w.data as any).issues[0].message), /"plans"/); - assert.equal(g(bare, "rev-parse", "main"), before); - const sync = exec(inv, "sync", {}); - assert.ok((sync.data.issues as any[]).some((i) => i.code === "public-repo-plans" && i.scope === "team")); - const idx = exec(inv, "scopes", {}); - assert.ok((idx.data.issues as any[]).some((i) => i.code === "public-repo-plans")); - assert.equal(exec(inv, "context", { scope: "team" }).exitCode, 0); - assert.equal(exec(inv, "plans", { scope: "team" }).exitCode, 0); - }); -}); - -test("private and unknown never block", () => { - for (const answer of ["private-or-missing", "unknown"] as const) { - const { inv } = fixture(); - withChecker(answer, () => { - assert.equal(propose(inv, "p1").exitCode, 0); - assert.ok(!(exec(inv, "sync", {}).data.issues as any[]).some((i) => i.code === "public-repo-plans")); - }); - } -}); - -test("visibility answer is cached; reads never call the checker", () => { - const { inv, base } = fixture(); - withChecker("private-or-missing", (calls) => { - exec(inv, "context", { scope: "team" }); - exec(inv, "scopes", {}); - assert.equal(calls(), 0); - assert.equal(propose(inv, "p1").exitCode, 0); - assert.equal(calls(), 1); - assert.equal(propose(inv, "p2").exitCode, 0); - assert.equal(calls(), 1); - assert.equal(readRemoteMeta(base, "team").visibility, "private-or-missing"); - // Expired answers are checked again. - const meta = readRemoteMeta(base, "team"); - writeRemoteMeta(base, "team", { ...meta, visibilityCheckedAt: new Date(Date.now() - 25 * 3600_000).toISOString() }); - assert.equal(propose(inv, "p3").exitCode, 0); - assert.equal(calls(), 2); - }); -}); - -test("a repo that becomes public is refused once the cached answer expires; sync never refetches early", () => { - const { inv, base } = fixture(); - withChecker("private-or-missing", () => assert.equal(propose(inv, "p1").exitCode, 0)); - withChecker("public", (calls) => { - // Within 24 hours the cached private answer stands, so a minute-by-minute sync makes no API calls. - exec(inv, "sync", {}); - assert.equal(calls(), 0); - const meta = readRemoteMeta(base, "team"); - writeRemoteMeta(base, "team", { ...meta, visibilityCheckedAt: new Date(Date.now() - 25 * 3600_000).toISOString() }); - assert.ok((exec(inv, "sync", {}).data.issues as any[]).some((i) => i.code === "public-repo-plans")); - assert.equal(calls(), 1); - assert.equal(propose(inv, "p2").exitCode, 3); - }); - const graph = JSON.parse(readFileSync(loadInventory(inv).scopes[0]!.root + "/mozak.json", "utf8")); - assert.equal(graph.plans.length, 1); -}); diff --git a/packages/obsidian/test/model.test.ts b/packages/obsidian/test/model.test.ts index a0e448b..54ae5b8 100644 --- a/packages/obsidian/test/model.test.ts +++ b/packages/obsidian/test/model.test.ts @@ -126,29 +126,21 @@ test("remote scopes carry their badge data through the view model and are counte assert.deepEqual(countRemote([a, b]), { remote: 1, stale: 1 }); }); -test("vault-plans scopes keep the repo badge, are never stale, open plans inside the vault, and need no sync", () => { +test("a legacy vault-plans entry is a failed row naming scope move, and opening its folder stays inside the vault", () => { const base = vaultTemp(join(process.env.JCODE_SCRATCH_DIR ?? tmpdir(), "mozak-obs-vault-")); const vault = join(base, "vault"); const plans = join(vault, "creations", "tool"); mkdirSync(plans, { recursive: true }); writeFileSync(join(plans, "README.md"), "# r\n"); writeFileSync(join(plans, "AGENTS.md"), "# a\n"); + initScopeState({ id: "tool", root: plans }, { operationId: "i", scopeId: "tool", kind: "project", title: "Tool", expectedAbsent: { graph: true, bridge: true }, ownerRef: "host:t", ownerMessageAt: "2026-10-18T08:50:00.000Z" }); const inv = join(vault, "mozak-inventory.json"); writeFileSync(inv, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "tool", remote: "github:o/tool", plans: "creations/tool" }] })); - initScopeState(loadInventory(inv).scopes[0]!, { operationId: "i", scopeId: "tool", kind: "project", title: "Tool", expectedAbsent: { graph: true, bridge: true }, ownerRef: "host:t", ownerMessageAt: "2026-10-18T08:50:00.000Z" }); - const model = loadScopesModel(inv); - const scope = model.scopes[0]!; - assert.equal(scope.status, "ok"); - assert.equal(scope.remote?.spec, "github:o/tool"); - assert.equal(scope.remote?.vault, true); - assert.equal(scope.remote?.stale, false); - assert.deepEqual(countRemote(model.scopes), { remote: 0, stale: 0 }); + const scope = loadScopesModel(inv).scopes[0]!; + assert.equal(scope.status, "failed"); + assert.equal(scope.errorCode, "legacy-repo-scope"); + assert.match(scope.errorMessage!, /mozak scope move --scope tool --to creations\/tool/); assert.equal(resolveOpenTarget(vault, join(scope.root, "mozak.md"), realOrSelf).kind, "vault"); - assert.equal(remoteVM("github:o/r", "main", { lastFetchAt: null, lastError: "offline" }, new Date(), undefined, true).stale, false); - assert.equal(scope.remote?.visibility, null, "never checked shows no badge"); - assert.equal(remoteVM("github:o/r", "main", { lastFetchAt: null, lastError: null, visibility: "public" }, new Date(), undefined, true).visibility, "public"); - assert.equal(remoteVM("github:o/r", "main", { lastFetchAt: null, lastError: null, visibility: "private-or-missing" }).visibility, "private"); - assert.equal(remoteVM("github:o/r", "main", { lastFetchAt: null, lastError: null, visibility: "unknown" }).visibility, null); }); // ---------- roadmap navigation (plan obsidian-roadmap) ---------- From 5b1df414ddb993ff1273cd1699056ede4ccac32d Mon Sep 17 00:00:00 2001 From: pitfa19 <166558275+pitfa19@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:51:30 +0100 Subject: [PATCH 04/10] Add a display-only repo link per scope: mozak scope link and move --repo Why: spec step 5, owner answer of 2026-11-01 ("keep a display-only repo link per scope"). With repo scopes gone, the sidebar and scopes still point at the code repo, without git or the network. What: - core repo-link.ts: parseRepoLink (github:owner/repo or an https URL with a host, nothing else), repoLinkUrl, repoLinkLabel. Pure. - Inventory: optional `repo` on every entry, validated at load (inventory-invalid with the accepted forms), carried on ScopeEntry. The digest ignores it, as with focus. - core scope-link.ts: mozak scope link --scope ID (--repo SPEC | --clear), owner route, same inventory lock and validated write as focus; entry order, indent and other keys kept; idempotent. - scope move --repo SPEC sets the link on the moved entry (spec step 2's form); without it an existing link is kept. --repo with --drop is refused. - scopes prints "repo: SPEC" and the JSON row carries repo. The plugin view model has repo { spec, url, label } and the scope row shows a hover link icon (an anchor, opened by Obsidian, never fetched). - MCP: no write tool (owner route only). Proof: repo-link.test.ts and the CLI scope link test failed first (missing modules, unknown route) and pass. npm test 645 of 645 under default TMPDIR, /tmp and a realpath folder, test:install 73 + 1 skipped. ub-mode: CRAP parseRepoLink 8.0, parseMoveArgs 6.0 (repo parsing split into moveRepoArg), linkScope 5.0, localEntry 5.0, movedEntry 5.0, others under 5. dryer: no candidates. mutator repo-link.ts and scope-link.ts 17 of 17 killed (dead "."/".." checks removed: the slug pattern already refuses them); moveRepoArg, movedEntry and the loader repo lines all killed. --- packages/cli/src/index.ts | 23 ++++- packages/cli/test/scope-move-cli.test.ts | 19 ++++ packages/core/src/index.ts | 2 + packages/core/src/repo-link.ts | 30 ++++++ packages/core/src/scope-index.ts | 19 +++- packages/core/src/scope-link.ts | 55 +++++++++++ packages/core/src/scope-list.ts | 10 +- packages/core/src/scope-move.ts | 27 ++++-- packages/core/test/repo-link.test.ts | 111 +++++++++++++++++++++++ packages/obsidian/src/load.ts | 3 +- packages/obsidian/src/model.ts | 15 ++- packages/obsidian/src/views.ts | 8 ++ packages/obsidian/styles.css | 4 + 13 files changed, 308 insertions(+), 18 deletions(-) create mode 100644 packages/core/src/repo-link.ts create mode 100644 packages/core/src/scope-link.ts create mode 100644 packages/core/test/repo-link.test.ts diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 3c3bcfd..b47ecb2 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -5,7 +5,7 @@ import { closeSync, fstatSync, openSync, readSync } from "node:fs"; import { parseArgs } from "node:util"; -import { decideWithFlags, deleteWithFlags, observePayload, observeWithFlags, planShow, executeOperation, loadInventory, MAX_REQUEST_BYTES, scopeForWorkingCopy, gitCommitScope, DomainError, focusChange, focusList, renderFocus, renderMove, scopeMoveOutput, type OperationOutput, type ScopeInventory } from "@mozak/core"; +import { decideWithFlags, deleteWithFlags, observePayload, observeWithFlags, planShow, executeOperation, loadInventory, MAX_REQUEST_BYTES, scopeForWorkingCopy, gitCommitScope, DomainError, focusChange, focusList, renderFocus, renderMove, scopeLinkOutput, scopeMoveOutput, type OperationOutput, type ScopeInventory } from "@mozak/core"; import { runningVersion, upgrade } from "./upgrade.js"; import { doctor, renderDoctor } from "./doctor.js"; @@ -62,7 +62,8 @@ const ROUTES: Record = { "focus list": { operation: "focus-list", flags: ["config", "scope", "json"], requires: ["config"], requestFile: false }, "focus add": { operation: "focus-add", flags: ["config", "scope", "plan", "json"], requires: ["config", "scope", "plan"], requestFile: false }, "focus remove": { operation: "focus-remove", flags: ["config", "scope", "plan", "json"], requires: ["config", "scope", "plan"], requestFile: false }, - "scope move": { operation: "scope-move", flags: ["config", "scope", "to", "drop", "dry-run", "owner-ref", "owner-message-at", "reason", "json"], requires: ["config", "scope", "owner-ref", "owner-message-at", "reason"], requestFile: false }, + "scope move": { operation: "scope-move", flags: ["config", "scope", "to", "drop", "repo", "dry-run", "owner-ref", "owner-message-at", "reason", "json"], requires: ["config", "scope", "owner-ref", "owner-message-at", "reason"], requestFile: false }, + "scope link": { operation: "scope-link", flags: ["config", "scope", "repo", "clear", "json"], requires: ["config", "scope"], requestFile: false }, observe: { operation: "observe", flags: ["config", "scope", "request", ...OBSERVE_FLAGS], requires: ["config", "scope"], requestFile: true }, "review decide": { operation: "decide", flags: ["config", "scope", "request", ...DECIDE_FLAGS], requires: ["config", "scope"], requestFile: true }, "plan prune": { operation: "prune", flags: ["config", "scope", "rejected", "request"], requires: ["config", "scope", "rejected", "request"], requestFile: true }, @@ -78,7 +79,7 @@ const ROUTES: Record = { }; const ROUTE_NAMES = Object.keys(ROUTES); -const BOOLEAN_FLAGS = new Set(["json", "include-rejected", "all", "write", "brief", "dry-run", "allow-completed", "commit", "rejected", "local", "print", "include-private", "drop"]); +const BOOLEAN_FLAGS = new Set(["json", "include-rejected", "all", "write", "brief", "dry-run", "allow-completed", "commit", "rejected", "local", "print", "include-private", "drop", "clear"]); class UsageError extends Error {} @@ -87,9 +88,11 @@ function usage(): string { "usage: mozak [--config FILE] [--config FILE] [flags]", " mozak scope init --scope ID --request FILE (owner)", " mozak scope retitle --scope ID --request FILE (owner; change the scope's display title)", - " mozak scope move --scope ID (--to PATH | --drop) --owner-ref REF --owner-message-at ISO --reason TEXT [--dry-run] [--json]", + " mozak scope move --scope ID (--to PATH [--repo SPEC] | --drop) --owner-ref REF --owner-message-at ISO --reason TEXT [--dry-run] [--json]", " (owner; copy the scope's files into a vault folder, verify them,", " point its inventory entry there; old files stay. --drop: 0-plan entry only)", + " mozak scope link --scope ID (--repo SPEC | --clear) [--json]", + " (owner; display-only repo link, github:owner/repo or https URL; never fetched)", " mozak context [--scope ID] [--brief] [--plan ID] [--json]", " mozak plans [--scope ID | --all] [--include-rejected] [--limit 1..100] [--sort deadline] [--continuation TOKEN] [--json]", " mozak graph (--scope ID | --all) [--json] (cross-plan refs from owner annotations, with resolution)", @@ -312,6 +315,7 @@ interface IndexRow { kind?: string; plans?: { completed: number; open: number; awaiting: number }; entryFiles: string[]; + repo?: string; remote?: string; ref?: string; stale?: boolean; @@ -327,6 +331,7 @@ function renderScopesHuman(data: { coverage?: { selected: number; ok: number; fa lines.push(`${s.id} [${s.kind}] ${s.title}${s.remote ? " [remote" + (s.stale ? ", STALE" : "") + "]" : ""}`); if (s.remote) lines.push(` remote: ${s.remote}@${s.ref}${s.stale ? ` (cached copy, ${s.staleReason ?? "fetch failed"})` : ""}`); lines.push(` folder: ${s.root}`); + if (s.repo) lines.push(` repo: ${s.repo}`); lines.push(` plans: ${p.completed} completed, ${p.open} open, ${p.awaiting} awaiting`); lines.push(` files: ${s.entryFiles.join(", ") || "none"}`); } else { @@ -465,12 +470,21 @@ function focusRoute(configPath: string, inventory: ScopeInventory, operation: st function moveRoute(configPath: string, values: Record): number { const out = scopeMoveOutput(configPath, { scope: values.scope, ...(values.to !== undefined ? { to: values.to } : {}), ...(values.drop ? { drop: true } : {}), ...(values["dry-run"] ? { dryRun: true } : {}), + ...(values.repo !== undefined ? { repo: values.repo } : {}), ownerRef: values["owner-ref"], ownerMessageAt: values["owner-message-at"], reason: values.reason, }); process.stdout.write(values.json === true ? `${JSON.stringify(out.data, null, 2)}\n` : renderMove(out.data)); return out.exitCode; } +/** `mozak scope link`: owner route on the inventory file. Sets or clears the display-only repo link. Not in MCP. */ +function linkRoute(configPath: string, values: Record): number { + const out = scopeLinkOutput(configPath, { scope: values.scope, ...(values.repo !== undefined ? { repo: values.repo } : {}), ...(values.clear ? { clear: true } : {}) }); + const d = out.data as Record; + process.stdout.write(values.json === true || d.status !== "ok" ? `${JSON.stringify(d, null, 2)}\n` : `${d.scope}: ${d.repo === null ? "no repo link" : `repo ${d.repo}`}${d.changed ? "" : " (unchanged)"}\n`); + return out.exitCode; +} + /** upgrade and doctor work on the installation, not on scopes, so they have their own flags and no --config rule. */ function maintenance(name: "upgrade" | "doctor", argv: string[]): number { let values: Record; @@ -553,6 +567,7 @@ function run(argv: string[]): number { const cwdScope = CWD_SCOPE_ROUTES.has(routeName) && values.scope === undefined && values.all === undefined && values.continuation === undefined; if (route.operation.startsWith("focus-")) return focusRoute(configPath, inventory, route.operation, values); if (route.operation === "scope-move") return moveRoute(configPath, values); + if (route.operation === "scope-link") return linkRoute(configPath, values); if (cwdScope) { try { values.scope = scopeForWorkingCopy(inventory, process.cwd()).id; diff --git a/packages/cli/test/scope-move-cli.test.ts b/packages/cli/test/scope-move-cli.test.ts index 1df9c35..af60b41 100644 --- a/packages/cli/test/scope-move-cli.test.ts +++ b/packages/cli/test/scope-move-cli.test.ts @@ -58,6 +58,25 @@ test("CLI: scope move needs the owner flags and exactly one of --to or --drop, a assert.match(cli(["--help"]).out, /mozak scope move --scope ID/); }); +test("CLI: scope link sets and clears a display-only link that scopes prints; move --repo sets it too", () => { + const w = setup(); + const set = cli(["scope", "link", "--config", w.config, "--scope", "alpha", "--repo", "github:o/alpha"]); + assert.equal(set.code, 0, set.out + set.err); + assert.equal(set.out, "alpha: repo github:o/alpha\n"); + assert.equal(cli(["scope", "link", "--config", w.config, "--scope", "alpha", "--repo", "github:o/alpha"]).out, "alpha: repo github:o/alpha (unchanged)\n"); + const bad = cli(["scope", "link", "--config", w.config, "--scope", "alpha", "--repo", "ftp://x"]); + assert.equal(bad.code, 2); + assert.equal(JSON.parse(bad.out).status, "invalid-input"); + const moved = cli(["scope", "move", "--config", w.config, "--scope", "alpha", "--to", "vault/alpha", "--repo", "github:o/alpha2", "--json", ...OWNER]); + assert.equal(moved.code, 0, moved.out); + assert.deepEqual(JSON.parse(moved.out).entry, { id: "alpha", root: "vault/alpha", repo: "github:o/alpha2" }); + assert.match(cli(["scopes", "--config", w.config]).out, /\n repo: github:o\/alpha2\n/); + const cleared = cli(["scope", "link", "--config", w.config, "--scope", "alpha", "--clear", "--json"]); + assert.deepEqual(JSON.parse(cleared.out), { status: "ok", scope: "alpha", repo: null, changed: true }); + assert.doesNotMatch(cli(["scopes", "--config", w.config]).out, /repo:/); + assert.match(cli(["--help"]).out, /mozak scope link --scope ID \(--repo SPEC \| --clear\)/); +}); + test("CLI: scope move --drop removes a 0-plan entry and refuses a scope with plans", () => { const w = world(["alpha", "empty"]); w.propose("alpha", "a1"); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index aee06fd..fe71037 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -15,6 +15,8 @@ export * from "./delete.ts"; export * from "./focus.ts"; export * from "./inventory-file.ts"; export * from "./scope-move.ts"; +export * from "./scope-link.ts"; +export * from "./repo-link.ts"; export * from "./roadmap.ts"; export { mdText, stopLabel, completedPlanLine, planHeading, planDisplayState, progressStrip, type PlanDisplayState } from "./bridge.ts"; export * from "./api.ts"; diff --git a/packages/core/src/repo-link.ts b/packages/core/src/repo-link.ts new file mode 100644 index 0000000..d0c62ec --- /dev/null +++ b/packages/core/src/repo-link.ts @@ -0,0 +1,30 @@ +// Display-only repo link of a scope (0.6.0): `github:owner/repo` or an https URL. It is shown in `mozak scopes` and the +// Obsidian sidebar so the owner can open the code repo. It is never used for git, never fetched, and never decides +// where plans live. Pure helpers, no IO. + +/** Owner or repo name: starts with a letter or digit, so "." and ".." can never pass. */ +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const HTTPS = /^https:\/\/[A-Za-z0-9][A-Za-z0-9.-]*(:\d{1,5})?(\/[A-Za-z0-9._~%/-]*)?$/; + +/** The link exactly as given when it is `github:owner/repo` or an https URL with a host, else null. */ +export function parseRepoLink(value: unknown): string | null { + if (typeof value !== "string") return null; + if (value.startsWith("github:")) { + const parts = value.slice("github:".length).split("/"); + return parts.length === 2 && parts.every((p) => SLUG.test(p)) ? value : null; + } + return HTTPS.test(value) ? value : null; +} + +export const REPO_LINK_HELP = `repo must be "github:owner/repo" or an https:// URL`; + +/** A browsable URL for the link. */ +export function repoLinkUrl(spec: string): string { + if (spec.startsWith("github:")) return `https://github.com/${spec.slice("github:".length)}`; + return spec.replace(/\.git$/, ""); +} + +/** Short label: owner/repo for GitHub, host/path otherwise. */ +export function repoLinkLabel(spec: string): string { + return repoLinkUrl(spec).replace(/^https:\/\/(github\.com\/)?/, ""); +} diff --git a/packages/core/src/scope-index.ts b/packages/core/src/scope-index.ts index d0b64ce..9e8774c 100644 --- a/packages/core/src/scope-index.ts +++ b/packages/core/src/scope-index.ts @@ -4,6 +4,7 @@ import { basename, dirname, join, resolve } from "node:path"; import { DomainError } from "./errors.ts"; import type { RemoteInfo } from "./remote-meta.ts"; import { isLegacyEntry, LEGACY_KEYS, legacyLocation } from "./legacy-entry.ts"; +import { parseRepoLink, REPO_LINK_HELP } from "./repo-link.ts"; import { vaultOf } from "./vault-config.ts"; /** Pilot-local explicit inventory. Never a global registration or a directory scan. */ @@ -22,6 +23,8 @@ export interface ScopeEntry { remote?: RemoteInfo; /** Diagnostic only: reserved x settings were ignored at inventory or selected-entry level. */ inventoryExtensionsIgnored?: true; + /** Display-only link to the code repo (`github:owner/repo` or an https URL), when the entry has one. */ + repo?: string; /** * Set when the entry is kept in the inventory but every route refuses it (for example a root outside any vault). * `resolveScope` throws it. `mozak scope move` still reads the entry, so the owner can move it. @@ -40,8 +43,9 @@ export interface ScopeInventory { const INVENTORY_KEYS = ["format", "scopes"] as const; const ENTRY_KEYS = ["id", "root"] as const; -/** Optional on every scope entry. `focus`: the owner's starred plan ids, read by the plugin and `mozak focus` only. */ -const OPTIONAL_ENTRY_KEYS = ["focus"] as const; +/** Optional on every scope entry. `focus`: the owner's starred plan ids, read by the plugin and `mozak focus` only. + * `repo`: a display-only link to the code repo (never used for git or the network). */ +const OPTIONAL_ENTRY_KEYS = ["focus", "repo"] as const; /** A legacy entry's id named a cache folder, so it never held path characters. */ const LEGACY_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; @@ -166,8 +170,17 @@ function localEntry(entry: Record, file: string, base: string): const rawRoot = entry.root; if (typeof rawRoot !== "string" || rawRoot.trim() === "") throw invalidInventory(file, `scope "${id}" root must be a nonempty string`); const root = canonicalPath(resolve(base, rawRoot)); + const scope: ScopeEntry = { id, root }; + if ("repo" in entry) scope.repo = repoOf(entry.repo, id, file); const refused = vaultRule(id, root); - return refused ? { id, root, refused } : { id, root }; + if (refused) scope.refused = refused; + return scope; +} + +function repoOf(value: unknown, id: string, file: string): string { + const repo = parseRepoLink(value); + if (repo === null) throw invalidInventory(file, `scope "${id}" ${REPO_LINK_HELP}`); + return repo; } /** Each id and each canonical root appears once. */ diff --git a/packages/core/src/scope-link.ts b/packages/core/src/scope-link.ts new file mode 100644 index 0000000..d024d7e --- /dev/null +++ b/packages/core/src/scope-link.ts @@ -0,0 +1,55 @@ +// `mozak scope link` (owner route): set or clear the display-only `repo` link of one inventory entry. Same inventory +// lock and validated atomic write as `focus` and `scope move`. Entry order, indent and every other key are kept, and +// running it twice is a no-op. Never touches mozak.json or mozak.md, and never runs git. + +import { readFileSync } from "node:fs"; +import { DomainError } from "./errors.ts"; +import { inventoryText, withInventoryLock, writeInventoryValidated } from "./inventory-file.ts"; +import { loadInventory } from "./scope-index.ts"; +import { parseRepoLink, REPO_LINK_HELP } from "./repo-link.ts"; +import { nonEmptyString } from "./validate.ts"; +import type { OperationOutput } from "./api.ts"; + +export interface LinkArgs { scope: unknown; repo?: unknown; clear?: unknown } +export interface LinkResult { scope: string; repo: string | null; changed: boolean } + +const invalid = (message: string) => new DomainError("invalid-input", message, 2); + +/** Boundary: exactly one of a valid repo link or clear. */ +function parseLinkArgs(a: LinkArgs): { scope: string; repo: string | null } { + const scope = nonEmptyString(a.scope, "scope"); + const clear = a.clear === true; + if (clear === (a.repo !== undefined)) throw invalid("scope link needs exactly one of --repo SPEC or --clear"); + if (clear) return { scope, repo: null }; + const repo = parseRepoLink(a.repo); + if (repo === null) throw invalid(`${REPO_LINK_HELP}, not ${JSON.stringify(a.repo)}`); + return { scope, repo }; +} + +/** Set or clear one entry's repo link. */ +export function linkScope(inventoryPath: string, args: LinkArgs): LinkResult { + const req = parseLinkArgs(args); + return withInventoryLock(inventoryPath, () => { + const text = readFileSync(inventoryPath, "utf8"); + loadInventory(inventoryPath); + const doc = JSON.parse(text) as { scopes: (Record & { id: string })[] }; + const entry = doc.scopes.find((e) => e.id === req.scope); + if (!entry) throw new DomainError("scope-not-found", `no scope "${req.scope}" in the inventory; run mozak scopes to list the scope ids`, 2); + const current = typeof entry.repo === "string" ? entry.repo : null; + if (current === req.repo) return { scope: req.scope, repo: req.repo, changed: false }; + if (req.repo === null) delete entry.repo; + else entry.repo = req.repo; + writeInventoryValidated(inventoryPath, inventoryText(doc, text)); + return { scope: req.scope, repo: req.repo, changed: true }; + }); +} + +/** Route used by the CLI: linkScope with its errors as an envelope. Owner only; MCP never exposes it. */ +export function scopeLinkOutput(inventoryPath: string, args: LinkArgs): OperationOutput { + try { + return { exitCode: 0, data: { status: "ok", ...linkScope(inventoryPath, args) } }; + } catch (err) { + if (!(err instanceof DomainError)) throw err; + return { exitCode: err.exitCode, data: { status: err.code, issues: [{ code: err.code, message: err.message }] } }; + } +} diff --git a/packages/core/src/scope-list.ts b/packages/core/src/scope-list.ts index 564d43d..c0482b0 100644 --- a/packages/core/src/scope-list.ts +++ b/packages/core/src/scope-list.ts @@ -25,6 +25,8 @@ export interface ScopeIndexRow { plans?: { completed: number; open: number; awaiting: number }; /** Which of AGENTS.md, mozak.json, mozak.md (or their pre-0.4 uppercase names) and README.md exist as regular files in the root. */ entryFiles: string[]; + /** Display-only link to the code repo, when the inventory entry has one. */ + repo?: string; } export interface ScopeIndex { @@ -58,6 +60,8 @@ function failedRow(id: string, root: string, err: DomainError): ScopeIndexRow { return { id, root, status: "failed", code: err.code, message: err.message, entryFiles: entryFilesOf(root) }; } +const withRepo = (row: ScopeIndexRow, repo: string | undefined): ScopeIndexRow => (repo === undefined ? row : { ...row, repo }); + export function scopeIndex(inv: ScopeInventory): ScopeIndex { const scopes: ScopeIndexRow[] = []; for (const entry of inv.scopes) { @@ -65,7 +69,7 @@ export function scopeIndex(inv: ScopeInventory): ScopeIndex { const resolved = resolveScope(inv, entry.id); const read = readScope(resolved); const groups = reviewRows(read.state); - scopes.push({ + scopes.push(withRepo({ id: entry.id, root: resolved.root, status: "ok", @@ -73,10 +77,10 @@ export function scopeIndex(inv: ScopeInventory): ScopeIndex { kind: read.state.scope.kind, plans: { completed: groups.completed.length, open: groups.open.length, awaiting: groups.awaiting.length }, entryFiles: entryFilesOf(resolved.root), - }); + }, entry.repo)); } catch (err) { if (!(err instanceof DomainError)) throw err; - scopes.push(failedRow(entry.id, entry.root, err)); + scopes.push(withRepo(failedRow(entry.id, entry.root, err), entry.repo)); } } const ok = scopes.filter((s) => s.status === "ok").length; diff --git a/packages/core/src/scope-move.ts b/packages/core/src/scope-move.ts index 8a4b978..f3d1a0d 100644 --- a/packages/core/src/scope-move.ts +++ b/packages/core/src/scope-move.ts @@ -18,6 +18,7 @@ import { readScope, withScopeLocks } from "./scope-store.ts"; import { ANNOTATIONS_FILE } from "./annotations.ts"; import { isUtcTimestamp } from "./understanding.ts"; import { nonEmptyString } from "./validate.ts"; +import { parseRepoLink, REPO_LINK_HELP } from "./repo-link.ts"; import { vaultOf } from "./vault-config.ts"; /** Files a move carries, in copy order. The plan file comes first so a reader never sees a projection without it. */ @@ -26,7 +27,7 @@ export const MOVED_FILES = [...SCOPE_FILE_NAMES, ANNOTATIONS_FILE, "README.md", const LOCATION_KEYS = new Set(["root", "remote", "ref", "plans"]); export interface MoveArgs { - scope: unknown; to?: unknown; drop?: unknown; dryRun?: unknown; + scope: unknown; to?: unknown; drop?: unknown; dryRun?: unknown; repo?: unknown; ownerRef: unknown; ownerMessageAt: unknown; reason: unknown; } export interface MovedFile { name: string; bytes: number; sha256: string } @@ -49,7 +50,7 @@ export interface MoveOptions { onPhase?: (phase: string) => void; lockTimeoutMs? type RawEntry = Record & { id: string }; type SourceFile = { name: string; bytes: Buffer; mode: number }; -interface Request { scope: string; to: string | null; dryRun: boolean; owner: MoveResult["owner"] } +interface Request { scope: string; to: string | null; repo: string | null; dryRun: boolean; owner: MoveResult["owner"] } const sha256 = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex"); const invalid = (message: string) => new DomainError("invalid-input", message, 2); @@ -61,10 +62,20 @@ export function parseMoveArgs(a: MoveArgs): Request { if (a.drop !== undefined && typeof a.drop !== "boolean") throw invalid("drop must be a boolean"); if (drop === (a.to !== undefined)) throw invalid("scope move needs exactly one of --to PATH or --drop"); const to = drop ? null : nonEmptyString(a.to, "to"); + const repo = moveRepoArg(a.repo, drop); const ownerRef = nonEmptyString(a.ownerRef, "ownerRef"); if (!isUtcTimestamp(a.ownerMessageAt)) throw invalid("ownerMessageAt must be the UTC time of the owner's message, for example 2026-11-01T17:25:00.000Z"); const reason = nonEmptyString(a.reason, "reason"); - return { scope, to, dryRun: a.dryRun === true, owner: { ownerRef, ownerMessageAt: a.ownerMessageAt, reason } }; + return { scope, to, repo, dryRun: a.dryRun === true, owner: { ownerRef, ownerMessageAt: a.ownerMessageAt, reason } }; +} + +/** `--repo` on a move: absent (null), or a valid display-only link that goes with `--to`. */ +function moveRepoArg(value: unknown, drop: boolean): string | null { + if (value === undefined) return null; + if (drop) throw invalid("--repo goes with --to, not --drop"); + const repo = parseRepoLink(value); + if (repo === null) throw invalid(`${REPO_LINK_HELP}, not ${JSON.stringify(value)}`); + return repo; } /** Run `check` on the source folder as a plain local scope: no settings, no remote refresh, no network. */ @@ -114,10 +125,14 @@ function specsLeftBehind(source: ScopeEntry, target: string): { code: string; me })); } -/** The entry after the move: id, the new root, then every other key of the old entry in its order (focus, x). */ -function movedEntry(old: RawEntry, to: string): Record { +/** + * The entry after the move: id, the new root, then every other key of the old entry in its order (focus, x, repo). + * `repo`, when given, sets or replaces the display-only link. + */ +function movedEntry(old: RawEntry, to: string, repo: string | null): Record { const out: Record = { id: old.id, root: to }; for (const [k, v] of Object.entries(old)) if (k !== "id" && !LOCATION_KEYS.has(k)) out[k] = v; + if (repo !== null) out.repo = repo; return out; } @@ -233,7 +248,7 @@ function planMove(inventoryPath: string, req: Request): Planned { const files = inPlace ? [] : sourceFiles(source.root); if (!inPlace) assertTargetFree(target, files.map((f) => f.name), inv); assertSourceChecks(source); - const entry = movedEntry(old, req.to); + const entry = movedEntry(old, req.to, req.repo); const changed = JSON.stringify(entry) !== JSON.stringify(old); doc.scopes[index] = entry as RawEntry; const plans = readScope(source).state.plans.length; diff --git a/packages/core/test/repo-link.test.ts b/packages/core/test/repo-link.test.ts new file mode 100644 index 0000000..9b030b7 --- /dev/null +++ b/packages/core/test/repo-link.test.ts @@ -0,0 +1,111 @@ +// Display-only repo link (0.6.0): an optional `repo` on a scope entry, `github:owner/repo` or an https URL. It is +// validated where it enters (the loader and `mozak scope link`), shown by `scopes` and the plugin, never used for git or +// the network, and it does not change the inventory digest. Synthetic temp folders only. +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { cleanup, world, NOW } from "./annotations-fixture.ts"; +import { executeOperation } from "../src/api.ts"; +import { loadInventory } from "../src/scope-index.ts"; +import { linkScope, scopeLinkOutput } from "../src/scope-link.ts"; +import { parseRepoLink, repoLinkLabel, repoLinkUrl } from "../src/repo-link.ts"; +import { moveScope } from "../src/scope-move.ts"; +import { makeVault } from "./vault-temp.ts"; +import { loadScopesModel } from "../../obsidian/src/load.ts"; + +after(cleanup); +const raw = (path: string) => JSON.parse(readFileSync(path, "utf8")); + +function linked() { + const w = world(["alpha", "beta"]); + makeVault(w.base); + writeFileSync(w.config, '{\n "format": "mozak.local/v3",\n "scopes": [\n { "id": "alpha", "root": "alpha", "focus": [] },\n { "id": "beta", "root": "beta" }\n ]\n}\n'); + return w; +} + +test("parseRepoLink accepts github:owner/repo and https URLs, and nothing else", () => { + assert.equal(parseRepoLink("github:pitfa19/mozak"), "github:pitfa19/mozak"); + assert.equal(parseRepoLink("https://github.com/ANPIT-hr/anpit-web"), "https://github.com/ANPIT-hr/anpit-web"); + assert.equal(parseRepoLink("https://gitlab.example.org/team/app.git"), "https://gitlab.example.org/team/app.git"); + for (const bad of ["", " github:a/b", "github:a", "github:a/b/c", "github:../b", "http://x/y", "file:///tmp/x", "https://", "https://x y/z", "git@github.com:a/b.git", 3, null]) { + assert.equal(parseRepoLink(bad), null, String(bad)); + } + assert.equal(repoLinkUrl("github:pitfa19/mozak"), "https://github.com/pitfa19/mozak"); + assert.equal(repoLinkUrl("https://github.com/a/b.git"), "https://github.com/a/b"); + assert.equal(repoLinkLabel("github:pitfa19/mozak"), "pitfa19/mozak"); + assert.equal(repoLinkLabel("https://github.com/a/b.git"), "a/b"); + assert.equal(repoLinkLabel("https://gitlab.example.org/team/app"), "gitlab.example.org/team/app"); +}); + +test("the loader keeps a valid repo on the entry, refuses a bad one, and the digest ignores it", () => { + const w = linked(); + const digest = loadInventory(w.config).digest; + const doc = raw(w.config); + doc.scopes[0].repo = "github:o/alpha"; + writeFileSync(w.config, JSON.stringify(doc)); + const inv = loadInventory(w.config); + assert.equal(inv.scopes.find((s) => s.id === "alpha")!.repo, "github:o/alpha"); + assert.equal(inv.scopes.find((s) => s.id === "beta")!.repo, undefined); + assert.equal(inv.digest, digest, "repo never changes the inventory digest"); + for (const bad of ["ftp://x/y", 7, ""]) { + doc.scopes[0].repo = bad; + writeFileSync(w.config, JSON.stringify(doc)); + assert.throws(() => loadInventory(w.config), { code: "inventory-invalid", message: /repo must be "github:owner\/repo" or an https:\/\/ URL/ }); + } +}); + +test("scope link sets, replaces and clears only that entry's repo; style, order and other keys kept; idempotent", () => { + const w = linked(); + const before = readFileSync(w.config, "utf8"); + assert.deepEqual(linkScope(w.config, { scope: "alpha", repo: "github:o/alpha" }), { scope: "alpha", repo: "github:o/alpha", changed: true }); + assert.deepEqual(raw(w.config).scopes, [{ id: "alpha", root: "alpha", focus: [], repo: "github:o/alpha" }, { id: "beta", root: "beta" }]); + assert.match(readFileSync(w.config, "utf8"), /^\{\n "format"/, "one-space indent kept"); + const once = readFileSync(w.config, "utf8"); + assert.equal(linkScope(w.config, { scope: "alpha", repo: "github:o/alpha" }).changed, false); + assert.equal(readFileSync(w.config, "utf8"), once); + linkScope(w.config, { scope: "alpha", repo: "https://github.com/o/alpha2" }); + assert.equal(raw(w.config).scopes[0].repo, "https://github.com/o/alpha2"); + assert.deepEqual(linkScope(w.config, { scope: "alpha", clear: true }), { scope: "alpha", repo: null, changed: true }); + assert.deepEqual(raw(w.config), JSON.parse(before), "clearing restores the same content"); + assert.equal(linkScope(w.config, { scope: "alpha", clear: true }).changed, false); +}); + +test("scope link refuses a bad link, an unknown scope and a missing or double choice, writing nothing", () => { + const w = linked(); + const before = readFileSync(w.config, "utf8"); + assert.throws(() => linkScope(w.config, { scope: "alpha", repo: "git@github.com:o/a.git" }), { code: "invalid-input", message: /github:owner\/repo/ }); + assert.throws(() => linkScope(w.config, { scope: "gamma", repo: "github:o/g" }), { code: "scope-not-found" }); + assert.throws(() => linkScope(w.config, { scope: "alpha" }), { code: "invalid-input", message: /--repo SPEC or --clear/ }); + assert.throws(() => linkScope(w.config, { scope: "alpha", repo: "github:o/a", clear: true }), { code: "invalid-input" }); + assert.equal(readFileSync(w.config, "utf8"), before); + const out = scopeLinkOutput(w.config, { scope: "gamma", repo: "github:o/g" }); + assert.equal(out.exitCode, 2); + assert.equal(out.data.status, "scope-not-found"); + const ok = scopeLinkOutput(w.config, { scope: "beta", repo: "github:o/b" }); + assert.deepEqual([ok.exitCode, ok.data.status], [0, "ok"]); +}); + +test("scopes and the plugin show the link; nothing reads the network", () => { + const w = linked(); + linkScope(w.config, { scope: "alpha", repo: "github:o/alpha" }); + const idx = executeOperation(loadInventory(w.config), "scopes", {}); + const rows = idx.data.scopes as { id: string; repo?: string }[]; + assert.equal(rows.find((r) => r.id === "alpha")!.repo, "github:o/alpha"); + assert.equal("repo" in rows.find((r) => r.id === "beta")!, false); + const model = loadScopesModel(w.config); + assert.deepEqual(model.scopes.find((s) => s.id === "alpha")!.repo, { spec: "github:o/alpha", url: "https://github.com/o/alpha", label: "o/alpha" }); + assert.equal(model.scopes.find((s) => s.id === "beta")!.repo, null); +}); + +test("scope move --repo adds the link to the moved entry; without it an existing link is kept", () => { + const w = world(["alpha", "beta"]); + makeVault(join(w.base, "vault")); + writeFileSync(w.config, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "alpha", root: "alpha" }, { id: "beta", root: "beta", repo: "github:o/beta" }] })); + const owner = { ownerRef: "synthetic:owner", ownerMessageAt: NOW, reason: "into the vault" }; + assert.deepEqual(moveScope(w.config, { scope: "alpha", to: "vault/alpha", repo: "github:o/alpha", ...owner }).entry, { id: "alpha", root: "vault/alpha", repo: "github:o/alpha" }); + assert.deepEqual(moveScope(w.config, { scope: "beta", to: "vault/beta", ...owner }).entry, { id: "beta", root: "vault/beta", repo: "github:o/beta" }); + assert.throws(() => moveScope(w.config, { scope: "beta", to: "vault/beta", repo: "ftp://x", ...owner }), { code: "invalid-input", message: /github:owner\/repo/ }); + assert.throws(() => moveScope(w.config, { scope: "beta", drop: true, repo: "github:o/beta", ...owner }), { code: "invalid-input", message: /--repo goes with --to/ }); + assert.deepEqual(raw(w.config).scopes, [{ id: "alpha", root: "vault/alpha", repo: "github:o/alpha" }, { id: "beta", root: "vault/beta", repo: "github:o/beta" }]); +}); diff --git a/packages/obsidian/src/load.ts b/packages/obsidian/src/load.ts index fe9fa7e..4a9586b 100644 --- a/packages/obsidian/src/load.ts +++ b/packages/obsidian/src/load.ts @@ -49,9 +49,10 @@ export function loadScopesModel(inventoryPath: string): ScopesModel { annotations: annotationsEnabled(inv, resolved) ? readAnnotations(resolved.root, entry.id).doc : null, focus: focus[entry.id] ?? [], ...(remote ? { remote } : {}), + ...(entry.repo ? { repo: entry.repo } : {}), }; } catch (err) { - return { id: entry.id, root: entry.root, entryFiles: entryFiles(entry.root), error: fail(err), ...(remote ? { remote } : {}) }; + return { id: entry.id, root: entry.root, entryFiles: entryFiles(entry.root), error: fail(err), ...(remote ? { remote } : {}), ...(entry.repo ? { repo: entry.repo } : {}) }; } }); return scopesModel(inventoryPath, loads); diff --git a/packages/obsidian/src/model.ts b/packages/obsidian/src/model.ts index 9c3d8ca..d887361 100644 --- a/packages/obsidian/src/model.ts +++ b/packages/obsidian/src/model.ts @@ -1,6 +1,6 @@ // Pure view models. Turns core ScopeState plus review rows into plain data for the UI. No IO. // Plans are read in mozak.md, so the sidebar only needs identity, state, progress and a heading to jump to. -import { completedPlanLine, isBridgeFileName, planDisplayState, planHeading, planRoadmap, resolveRef, type AnnotationsDoc, type Plan, type PlanDisplayState, type ScopeLookup, type ScopeState } from "@mozak/core"; +import { completedPlanLine, isBridgeFileName, planDisplayState, planHeading, planRoadmap, repoLinkLabel, repoLinkUrl, resolveRef, type AnnotationsDoc, type Plan, type PlanDisplayState, type ScopeLookup, type ScopeState } from "@mozak/core"; export type PlanStateKey = PlanDisplayState; export type StopKey = "done" | "evidence" | "current" | "todo"; @@ -69,9 +69,13 @@ export interface ScopeVM { bridgeFile: string | null; /** Null for a local scope. */ remote: RemoteVM | null; + /** Display-only link to the code repo, when the inventory entry has one. Never fetched. */ + repo: RepoVM | null; errorCode: string | null; errorMessage: string | null; } +/** A scope's repo link for the sidebar: the inventory value, a browsable URL and a short label. */ +export interface RepoVM { spec: string; url: string; label: string } export interface ScopesModel { inventoryPath: string; loadedAt: string; @@ -90,6 +94,8 @@ export interface ScopeLoad { awaitingRows?: { planId: string; rowKind: string }[]; reviewNeededPlanIds?: string[]; remote?: RemoteVM; + /** The entry's display-only repo link, when it has one. */ + repo?: string; error?: { code: string; message: string }; /** Parsed mozak.annotations.json, when the scope has a valid one. */ annotations?: AnnotationsDoc | null; @@ -172,6 +178,11 @@ export function planViewModel( }; } +/** The sidebar form of a repo link. Pure. */ +export function repoVM(spec: string | undefined): RepoVM | null { + return spec === undefined ? null : { spec, url: repoLinkUrl(spec), label: repoLinkLabel(spec) }; +} + export function scopeViewModel(load: ScopeLoad): ScopeVM { const bridgeName = load.entryFiles.find(isBridgeFileName) ?? null; const hasMozakMd = bridgeName !== null; @@ -188,6 +199,7 @@ export function scopeViewModel(load: ScopeLoad): ScopeVM { hasMozakMd, bridgeFile: bridgeName, remote: load.remote ?? null, + repo: repoVM(load.repo), errorCode: load.error?.code ?? "unknown", errorMessage: load.error?.message ?? "scope could not be read", }; @@ -209,6 +221,7 @@ export function scopeViewModel(load: ScopeLoad): ScopeVM { hasMozakMd, bridgeFile: bridgeName, remote: load.remote ?? null, + repo: repoVM(load.repo), errorCode: null, errorMessage: null, }; diff --git a/packages/obsidian/src/views.ts b/packages/obsidian/src/views.ts index a6b1bd9..74b86c6 100644 --- a/packages/obsidian/src/views.ts +++ b/packages/obsidian/src/views.ts @@ -207,6 +207,14 @@ export class ScopesView extends ItemView { } } el(row, "span", "mozak-scope-title", scope.title); + if (scope.repo) { + // Display-only link to the code repo. A plain anchor: Obsidian opens it in the browser, mozak never fetches it. + const link = el(row, "a", "clickable-icon mozak-repo"); + setIcon(link, "github"); + link.setAttr("href", scope.repo.url); + link.setAttr("aria-label", `Open ${scope.repo.label}`); + link.addEventListener("click", (ev) => ev.stopPropagation()); + } const counts = el(row, "span", "mozak-counts"); if (scope.status === "failed") { const e = el(counts, "span", "mozak-count is-error"); diff --git a/packages/obsidian/styles.css b/packages/obsidian/styles.css index 9b3b3ec..f48b85e 100644 --- a/packages/obsidian/styles.css +++ b/packages/obsidian/styles.css @@ -90,6 +90,10 @@ .mozak-md { flex: none; padding: 2px; opacity: 0; transition: opacity 100ms ease; } .mozak-md svg { width: 14px; height: 14px; } .mozak-scope-row:hover .mozak-md { opacity: 1; } +/* Display-only link to a scope's code repo: shown on hover, like the mozak.md button. */ +.mozak-repo { flex: none; padding: 2px; color: var(--text-muted); opacity: 0; transition: opacity 100ms ease; } +.mozak-repo svg { width: 14px; height: 14px; } +.mozak-scope-row:hover .mozak-repo, .mozak-repo:focus-visible { opacity: 1; } /* ---------- Plans inside an expanded scope ---------- */ .mozak-plans { padding: 0 4px 4px 22px; } From 0a69570c5cc9b8790dd981028f7042692572e5ad Mon Sep 17 00:00:00 2001 From: pitfa19 <166558275+pitfa19@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:16:29 +0100 Subject: [PATCH 05/10] Remove repo scopes: no remote cache, pull, cwd scope or mozak_sync 0.6.0 is vault-only. Deletes remote.ts, remote-meta.ts, visibility.ts and working-copy.ts. sync is local-only (fetch, then fast-forward each vault repo); the pull route and the MCP mozak_sync tool are gone; scoped reads always need --scope (no scope from a clone's git origin); bare plans lists every scope. The plugin drops the Repos group, stale and visibility badges, remote polling and the cache watch; a scope's display-only repo link stays. Release-scope tests guard that no remote module, export, pull route or clone remains and that fetch is used only by upgrade and local sync. --- packages/cli/src/index.ts | 83 ++---- packages/cli/test/cli.test.ts | 9 +- packages/cli/test/s2-cli.test.ts | 2 +- ...d-scope.test.ts => scope-required.test.ts} | 62 ++-- packages/core/src/api.ts | 172 +++--------- packages/core/src/git-commit.ts | 6 +- packages/core/src/index.ts | 5 +- packages/core/src/legacy-entry.ts | 5 +- packages/core/src/local-sync.ts | 6 +- packages/core/src/locators.ts | 10 +- packages/core/src/plans-index.ts | 7 +- packages/core/src/remote-meta.ts | 117 -------- packages/core/src/remote.ts | 264 ------------------ packages/core/src/scope-index.ts | 8 +- packages/core/src/scope-move.ts | 2 +- packages/core/src/scope-store.ts | 4 +- packages/core/src/settings.ts | 6 +- packages/core/src/usage.ts | 3 +- packages/core/src/visibility.ts | 82 ------ packages/core/src/working-copy.ts | 44 --- packages/core/test/annotations.test.ts | 7 +- packages/core/test/durable-write.test.ts | 10 +- packages/core/test/legacy-entries.test.ts | 9 +- packages/core/test/release-scope.test.ts | 30 ++ packages/mcp/src/server.ts | 7 - packages/mcp/test/mcp.test.ts | 2 +- packages/obsidian/src/load.ts | 67 ++--- packages/obsidian/src/main.ts | 37 +-- packages/obsidian/src/model.ts | 41 --- packages/obsidian/src/views.ts | 72 +---- packages/obsidian/src/watch.ts | 4 +- packages/obsidian/styles.css | 12 - packages/obsidian/test/model.test.ts | 25 +- packages/obsidian/test/sync.test.ts | 14 +- 34 files changed, 204 insertions(+), 1030 deletions(-) rename packages/cli/test/{cwd-scope.test.ts => scope-required.test.ts} (56%) delete mode 100644 packages/core/src/remote-meta.ts delete mode 100644 packages/core/src/remote.ts delete mode 100644 packages/core/src/visibility.ts delete mode 100644 packages/core/src/working-copy.ts diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index b47ecb2..5c6cd25 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -5,13 +5,11 @@ import { closeSync, fstatSync, openSync, readSync } from "node:fs"; import { parseArgs } from "node:util"; -import { decideWithFlags, deleteWithFlags, observePayload, observeWithFlags, planShow, executeOperation, loadInventory, MAX_REQUEST_BYTES, scopeForWorkingCopy, gitCommitScope, DomainError, focusChange, focusList, renderFocus, renderMove, scopeLinkOutput, scopeMoveOutput, type OperationOutput, type ScopeInventory } from "@mozak/core"; +import { decideWithFlags, deleteWithFlags, observePayload, observeWithFlags, planShow, executeOperation, loadInventory, MAX_REQUEST_BYTES, gitCommitScope, focusChange, focusList, renderFocus, renderMove, scopeLinkOutput, scopeMoveOutput, type OperationOutput, type ScopeInventory } from "@mozak/core"; import { runningVersion, upgrade } from "./upgrade.js"; import { doctor, renderDoctor } from "./doctor.js"; -const OWNER_ROUTES = new Set(["decide", "init", "repair", "pull", "rename-files", "retitle", "delete", "annotate", "recover", "prune", "plans-md"]); -/** Read routes that may omit --scope: the scope is then found from the current folder's git origin. */ -const CWD_SCOPE_ROUTES = new Set(["context", "check", "review show", "plans", "plan show"]); +const OWNER_ROUTES = new Set(["decide", "init", "repair", "rename-files", "retitle", "delete", "annotate", "recover", "prune", "plans-md"]); /** Flag forms that replace hand-written request files. Owner provenance is always explicit. */ const DECIDE_FLAGS = ["plan", "purpose", "outcome", "spec", "owner-ref", "owner-message-at", "reason", "dry-run"] as const; @@ -33,7 +31,7 @@ type Route = { const ROUTES: Record = { "scope init": { operation: "init", flags: ["config", "scope", "request"], requires: ["config", "scope", "request"], requestFile: true }, - context: { operation: "context", flags: ["config", "scope", "brief", "plan", "json"], requires: ["config"], requestFile: false }, + context: { operation: "context", flags: ["config", "scope", "brief", "plan", "json"], requires: ["config", "scope"], requestFile: false }, plans: { operation: "plans", flags: ["config", "scope", "all", "include-rejected", "limit", "continuation", "sort", "json"], @@ -48,17 +46,16 @@ const ROUTES: Record = { "plans-md": { operation: "plans-md", flags: ["config", "print", "json"], requires: ["config"], requestFile: false }, annotate: { operation: "annotate", flags: ["config", "scope", "request"], requires: ["config", "scope", "request"], requestFile: true }, recover: { operation: "recover", flags: ["config", "scope", "request"], requires: ["config", "scope", "request"], requestFile: true }, - "review show": { operation: "review", flags: ["config", "scope", "plan", "purpose", "outcome", "json"], requires: ["config", "plan"], requestFile: false }, + "review show": { operation: "review", flags: ["config", "scope", "plan", "purpose", "outcome", "json"], requires: ["config", "scope", "plan"], requestFile: false }, scopes: { operation: "scopes", flags: ["config", "json"], requires: ["config"], requestFile: false }, sync: { operation: "sync", flags: ["config", "scope", "local", "json"], requires: ["config"], requestFile: false }, - pull: { operation: "pull", flags: ["config", "scope", "into", "json"], requires: ["config", "scope"], requestFile: false }, - check: { operation: "check", flags: ["config", "scope", "history", "json"], requires: ["config"], requestFile: false }, + check: { operation: "check", flags: ["config", "scope", "history", "json"], requires: ["config", "scope"], requestFile: false }, operation: { operation: "operation", flags: ["config", "scope", "id", "json"], requires: ["config", "scope", "id"], requestFile: false }, "plan propose": { operation: "propose", flags: ["config", "scope", "request"], requires: ["config", "scope", "request"], requestFile: true }, "plan revise": { operation: "revise", flags: ["config", "scope", "request"], requires: ["config", "scope", "request"], requestFile: true }, "plan complete": { operation: "complete", flags: ["config", "scope", "request"], requires: ["config", "scope", "request"], requestFile: true }, "plan delete": { operation: "delete", flags: ["config", "scope", "request", ...DELETE_FLAGS], requires: ["config", "scope"], requestFile: true }, - "plan show": { operation: "plan-show", flags: ["config", "scope", "plan", "json"], requires: ["config", "plan"], requestFile: false }, + "plan show": { operation: "plan-show", flags: ["config", "scope", "plan", "json"], requires: ["config", "scope", "plan"], requestFile: false }, "focus list": { operation: "focus-list", flags: ["config", "scope", "json"], requires: ["config"], requestFile: false }, "focus add": { operation: "focus-add", flags: ["config", "scope", "plan", "json"], requires: ["config", "scope", "plan"], requestFile: false }, "focus remove": { operation: "focus-remove", flags: ["config", "scope", "plan", "json"], requires: ["config", "scope", "plan"], requestFile: false }, @@ -93,7 +90,7 @@ function usage(): string { " point its inventory entry there; old files stay. --drop: 0-plan entry only)", " mozak scope link --scope ID (--repo SPEC | --clear) [--json]", " (owner; display-only repo link, github:owner/repo or https URL; never fetched)", - " mozak context [--scope ID] [--brief] [--plan ID] [--json]", + " mozak context --scope ID [--brief] [--plan ID] [--json]", " mozak plans [--scope ID | --all] [--include-rejected] [--limit 1..100] [--sort deadline] [--continuation TOKEN] [--json]", " mozak graph (--scope ID | --all) [--json] (cross-plan refs from owner annotations, with resolution)", " mozak ready (--scope ID | --all) [--json] (open plans whose needs are met, by deadline; blocked and superseded apart)", @@ -103,13 +100,11 @@ function usage(): string { " mozak plans-md [--print] [--json] (owner; write plans.md with plan titles and states at each repo root; --print only shows it)", " mozak annotate --scope ID --request FILE (owner; refs and deadlines in mozak.annotations.json)", " mozak scopes [--json] (read-only index of every scope: id, folder, title, plan counts)", - " mozak sync [--scope ID | --local] [--json] (force-refresh remote scopes; reads refresh them after 10 minutes)", - " (a local --scope or --local: fetch, then fast-forward the vault repo under the scope locks)", - " mozak pull --scope ID [--into PATH] (owner; clone the code; vault-plans scopes keep plans in the vault)", - " mozak review show [--scope ID] --plan ID [--purpose P] [--outcome ID] [--json]", - " mozak check [--scope ID] [--history N] [--json] (--history: hand edits in the last N commits of mozak.json)", + " mozak sync [--scope ID] [--json] (fetch, then fast-forward each vault repo under the scope locks; never pushes)", + " mozak review show --scope ID --plan ID [--purpose P] [--outcome ID] [--json]", + " mozak check --scope ID [--history N] [--json] (--history: hand edits in the last N commits of mozak.json)", " mozak operation --scope ID --id OP [--json]", - " mozak plan show [--scope ID] --plan ID [--json] (compact: lifecycle, eligibility, grants, outcomes, spec, next action)", + " mozak plan show --scope ID --plan ID [--json] (compact: lifecycle, eligibility, grants, outcomes, spec, next action)", " mozak focus list [--scope ID] [--json] (the owner's starred plans per scope, from the inventory)", " mozak focus add|remove --scope ID --plan ID (owner; star or unstar a plan; edits only the inventory's focus list)", " mozak plan propose|revise|complete --scope ID --request FILE", @@ -134,14 +129,13 @@ function usage(): string { " mozak doctor [--fix] [--config FILE] [--json] (check the setup; --fix only links, wrappers, plugin copies)", "Writes (every --request/flag write route) accept --commit: commit the scope's mozak.json and mozak.md in the", " containing git repo, then pull --rebase and push when it has an upstream (never forces; stops on conflict).", - " Without it a local scope's status says \"written ... not committed to git\". Repo-mode remote scopes always push.", + " Without it the status says \"written ... not committed to git\".", "Exit: 0 success, 2 invalid or unavailable, 3 stale/conflict/owner-review, 4 busy/recovery,", " 5 committed with unfinished projection or cleanup, 6 partial all-scope coverage.", "Config: FILE is the explicit inventory JSON. There is no default path and no directory scan.", - ' Shape: { "format": "mozak.local/v3", "scopes": [ { "id": "name", "root": "path" } ] }', - ' Repo scopes: { "id": "x", "remote": "github:owner/repo" } keeps plans in the repo (private repos);', - ' add "plans": "vault/folder" to keep them in that folder instead (public repos).', - " Read routes run inside a clone of an inventoried repo may omit --scope; it is found from the git origin.", + ' Shape: { "format": "mozak.local/v3", "scopes": [ { "id": "name", "root": "path", "repo": "github:owner/repo" } ] }', + " Every root is a folder inside an Obsidian vault (a folder with .obsidian at or above it). repo is optional and", + " display-only. An entry with remote, ref or plans is a pre-0.6 repo scope: move it with mozak scope move.", " Relative roots resolve against the inventory file's directory. Ask the owner for the path;", " first use (creating an inventory or a scope) is documented in the skill's references/bootstrap.md.", ].join("\n"); @@ -235,7 +229,7 @@ function parseCommand(argv: string[]): Parsed { } } // A continuation pins its own selector, so it may stand alone. Mixed selectors are refused by the facade. - // Without --scope or --all, plans is scoped to the current clone (resolved later from its git origin). + // Without --scope or --all, plans lists every scope (the same as --all). if (route.mode === "scope" && values.continuation === undefined) { const hasScope = values.scope !== undefined; const hasAll = values.all !== undefined; @@ -267,12 +261,7 @@ interface HumanRow { deadline?: string | null; deadlineStatus?: string; } -interface RemoteInfoRow { scope: string; remote: string; ref: string; stale: boolean; lastFetchAt: string | null; error?: string; source: string } -function remoteLines(remote: RemoteInfoRow[] | undefined): string[] { - return (remote ?? []).map((r) => `remote ${r.scope}: ${r.remote}@${r.ref}${r.stale ? ` STALE (cached copy, ${r.error ?? "fetch failed"})` : ""}${r.lastFetchAt ? `, last fetch ${r.lastFetchAt}` : ""}`); -} function renderPlansHuman(data: { - remote?: RemoteInfoRow[]; status: string; uniquePlanCount?: number; reviewItemCount?: number; @@ -300,7 +289,6 @@ function renderPlansHuman(data: { if (g.hasMore && g.continuation) lines.push(` more: --continuation ${g.continuation}`); } for (const issue of data.issues ?? []) lines.push(`issue ${issue.scope ? `[${issue.scope}] ` : ""}${issue.code}: ${issue.message}`); - lines.push(...remoteLines(data.remote)); return `${lines.join("\n")}\n`; } @@ -316,11 +304,6 @@ interface IndexRow { plans?: { completed: number; open: number; awaiting: number }; entryFiles: string[]; repo?: string; - remote?: string; - ref?: string; - stale?: boolean; - staleReason?: string; - lastFetchAt?: string | null; } function renderScopesHuman(data: { coverage?: { selected: number; ok: number; failed: number }; scopes?: IndexRow[] }): string { const c = data.coverage; @@ -328,14 +311,13 @@ function renderScopesHuman(data: { coverage?: { selected: number; ok: number; fa for (const s of data.scopes ?? []) { if (s.status === "ok") { const p = s.plans ?? { completed: 0, open: 0, awaiting: 0 }; - lines.push(`${s.id} [${s.kind}] ${s.title}${s.remote ? " [remote" + (s.stale ? ", STALE" : "") + "]" : ""}`); - if (s.remote) lines.push(` remote: ${s.remote}@${s.ref}${s.stale ? ` (cached copy, ${s.staleReason ?? "fetch failed"})` : ""}`); + lines.push(`${s.id} [${s.kind}] ${s.title}`); lines.push(` folder: ${s.root}`); if (s.repo) lines.push(` repo: ${s.repo}`); lines.push(` plans: ${p.completed} completed, ${p.open} open, ${p.awaiting} awaiting`); lines.push(` files: ${s.entryFiles.join(", ") || "none"}`); } else { - lines.push(`${s.id} failed (${s.code})${s.remote ? " [remote" + (s.stale ? ", STALE" : "") + "]" : ""}`); + lines.push(`${s.id} failed (${s.code})`); lines.push(` folder: ${s.root}`); lines.push(` ${s.message}`); } @@ -344,12 +326,9 @@ function renderScopesHuman(data: { coverage?: { selected: number; ok: number; fa } interface LocalSyncInfoRow { repo: string | null; scopes: string[]; status: string; from?: string; to?: string; error?: string } -function renderSyncHuman(data: { remote?: RemoteInfoRow[]; local?: LocalSyncInfoRow[]; issues?: { code: string; message: string }[] }): string { - const rows = data.remote ?? []; - const local = (data.local ?? []).map((r) => `local ${r.repo ?? r.scopes.join(", ")}: ${r.status}${r.from && r.to && r.from !== r.to ? ` ${r.from.slice(0, 8)}..${r.to.slice(0, 8)}` : ""}${r.error ? ` (${r.error})` : ""}`); - if (rows.length === 0 && local.length === 0) return "no remote scopes in the inventory\n"; - const warn = (data.issues ?? []).filter((i) => i.code === "cache-not-ignored").map((i) => `warning: ${i.message}`); - return `${[...remoteLines(rows), ...local, ...warn].join("\n")}\n`; +function renderSyncHuman(data: { local?: LocalSyncInfoRow[] }): string { + const local = (data.local ?? []).map((r) => `${r.repo ?? r.scopes.join(", ")}: ${r.status}${r.from && r.to && r.from !== r.to ? ` ${r.from.slice(0, 8)}..${r.to.slice(0, 8)}` : ""}${r.error ? ` (${r.error})` : ""}`); + return local.length === 0 ? "no scopes to sync\n" : `${local.join("\n")}\n`; } function flagForm(inventory: ReturnType, operation: string, v: Record) { @@ -371,11 +350,9 @@ const camel = (k: string) => k.replace(/-([a-z])/g, (_, c: string) => c.toUpperC /** * "committed" in the envelope means the scope transaction reached mozak.json and mozak.md on disk. - * Git is a separate step: repo-mode remote scopes commit and push on their own (remotePush), and - * local or vault-plans scopes are only committed to git with --commit. Say which one happened. + * Git is a separate step: the scope files are committed to git only with --commit. Say which one happened. */ function committedLabel(d: Record): string { - if (d.remotePush) return d.remotePush.pushed ? "written, committed and pushed" : "written and committed to git"; if (d.git) return d.git.committed || d.git.pushed ? `written, ${d.git.message}` : `written, ${d.git.message.replace(/^written, /, "")}`; return "written to mozak.json and mozak.md, not committed to git; add --commit to commit and push"; } @@ -383,7 +360,7 @@ function committedLabel(d: Record): string { /** After a successful write with --commit, commit the scope files in their git repo and push. */ function withGitCommit(out: OperationOutput, scope: unknown, inventory: ReturnType, operation: string, enabled: boolean): OperationOutput { const d = out.data as Record; - if (!enabled || !d.committed || d.remotePush || d.status === "dry-run") return out; + if (!enabled || !d.committed || d.status === "dry-run") return out; const entry = inventory.scopes.find((e) => e.id === scope); if (!entry) return out; const git = gitCommitScope(entry.root, `mozak: ${operation} ${entry.id}`); @@ -564,19 +541,9 @@ function run(argv: string[]): number { return 2; } - const cwdScope = CWD_SCOPE_ROUTES.has(routeName) && values.scope === undefined && values.all === undefined && values.continuation === undefined; if (route.operation.startsWith("focus-")) return focusRoute(configPath, inventory, route.operation, values); if (route.operation === "scope-move") return moveRoute(configPath, values); if (route.operation === "scope-link") return linkRoute(configPath, values); - if (cwdScope) { - try { - values.scope = scopeForWorkingCopy(inventory, process.cwd()).id; - } catch (err) { - if (!(err instanceof DomainError)) throw err; - process.stdout.write(`${JSON.stringify({ status: err.code, committed: false, snapshot: null, projectionStatus: null, projectionUpdated: false, issues: [{ code: err.code, message: err.message }] }, null, 2)}\n`); - return err.exitCode; - } - } let args: Record; if (route.operation === "plans") { @@ -624,8 +591,6 @@ function run(argv: string[]): number { return 2; } args = values.all ? { all: true } : { scope: values.scope }; - } else if (route.operation === "pull") { - args = { scope: values.scope, ...(values.into !== undefined ? { into: values.into } : {}) }; } else if (route.operation === "review") { args = { scope: values.scope, plan: values.plan, ...(values.purpose !== undefined ? { purpose: values.purpose } : {}), ...(values.outcome !== undefined ? { outcome: values.outcome } : {}) }; } else if (route.operation === "context") { @@ -689,7 +654,7 @@ function run(argv: string[]): number { const actor = OWNER_ROUTES.has(route.operation) ? "owner" : "agent"; const raw = executeOperation(inventory, route.operation, args, actor); const output = route.requestFile ? withGitCommit(raw, values.scope, inventory, route.operation, values.commit === true) : raw; - if (route.requestFile && (output.data as Record).committed && !values.commit && !(output.data as Record).remotePush) { + if (route.requestFile && (output.data as Record).committed && !values.commit) { process.stderr.write(`note: ${committedLabel(output.data as Record)}\n`); } printEnvelope(output, values.json === true || (routeName !== "plans" && routeName !== "scopes" && routeName !== "sync" && routeName !== "plans-md"), routeName); diff --git a/packages/cli/test/cli.test.ts b/packages/cli/test/cli.test.ts index 8fe0b5c..d80b6c6 100644 --- a/packages/cli/test/cli.test.ts +++ b/packages/cli/test/cli.test.ts @@ -153,12 +153,13 @@ test("a read route without --config exits 2", async () => { assert.match(r.err, /missing --config/); }); -test("plans refuses both --scope and --all; with neither it needs a clone of an inventoried repo", async () => { +test("plans refuses both --scope and --all; with neither it lists every scope, the same as --all", async () => { const f = fixture(); - const neither = await run(["plans", "--config", f.config]); + const neither = await run(["plans", "--config", f.config, "--json"]); + const all = await run(["plans", "--config", f.config, "--all", "--json"]); const both = await run(["plans", "--config", f.config, "--scope", "sample", "--all"]); - assert.equal(neither.code, 2); - assert.equal(json(neither).status, "scope-not-found"); + assert.equal(neither.code, all.code, neither.out + neither.err); + assert.deepEqual(json(neither).scopes, json(all).scopes); assert.equal(both.code, 2); }); diff --git a/packages/cli/test/s2-cli.test.ts b/packages/cli/test/s2-cli.test.ts index 5a6cff8..3c2cf3d 100644 --- a/packages/cli/test/s2-cli.test.ts +++ b/packages/cli/test/s2-cli.test.ts @@ -56,7 +56,7 @@ test("CLI: check --history validates N; sync of a local scope outside git explai assert.equal(JSON.parse(ok.out).history.available, false); const sync = cli(["sync", "--config", w.config, "--scope", "alpha"]); assert.equal(sync.code, 2); - assert.match(sync.out, /local .*not-in-git/); + assert.match(sync.out, /alpha: not-in-git/); const json = cli(["sync", "--config", w.config, "--local", "--json"]); assert.equal(JSON.parse(json.out).local[0].status, "not-in-git"); }); diff --git a/packages/cli/test/cwd-scope.test.ts b/packages/cli/test/scope-required.test.ts similarity index 56% rename from packages/cli/test/cwd-scope.test.ts rename to packages/cli/test/scope-required.test.ts index 9243120..1e38135 100644 --- a/packages/cli/test/cwd-scope.test.ts +++ b/packages/cli/test/scope-required.test.ts @@ -5,11 +5,11 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -import { initScopeState, loadInventory, repoKey } from "@mozak/core"; +import { initScopeState, loadInventory } from "@mozak/core"; import { vaultTemp } from "../../core/test/vault-temp.ts"; -// Real-process tests: the built CLI run from inside a plain git clone finds its scope from the clone's origin, -// so an agent working in ~/Downloads/ reads the same vault plans. Writes still need --scope. +// 0.6.0: mozak never derives a scope from the working directory's git origin, and there is no pull route. +// Run from inside a code clone, every scoped read needs --scope, and the clone is never touched. const here = fileURLToPath(new URL(".", import.meta.url)); const cliPath = resolve(here, "..", "dist", "index.js"); @@ -47,8 +47,8 @@ function fixture() { writeFileSync(join(plans, "README.md"), "# r\n"); writeFileSync(join(plans, "AGENTS.md"), "# a\n"); const inv = join(base, "vault", "inventory.json"); - writeFileSync(inv, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "tool", remote: `file://${bare}`, plans: "tool" }, { id: "other", root: "other" }] })); - mkdirSync(join(base, "vault", "other")); + // A 0.6.0 entry: a vault folder, with a display-only link to the code repo (never fetched, never matched to a cwd). + writeFileSync(inv, JSON.stringify({ format: "mozak.local/v3", scopes: [{ id: "tool", root: "tool", repo: "github:someone/tool" }] })); initScopeState(loadInventory(inv).scopes.find((s) => s.id === "tool")!, { operationId: "i", scopeId: "tool", kind: "project", title: "Tool", expectedAbsent: { graph: true, bridge: true }, ownerRef: "host:t", ownerMessageAt: "2026-10-18T08:50:00.000Z" }); const clone = join(base, "Downloads", "tool"); mkdirSync(join(base, "Downloads")); @@ -56,55 +56,33 @@ function fixture() { return { base, bare, plans, inv, clone }; } -test("repoKey normalizes https, ssh, scp-like, github: and file forms", () => { - const k = "github.com/pitfa19/mozak"; - for (const u of ["github:pitfa19/mozak", "https://github.com/pitfa19/mozak.git", "https://github.com/Pitfa19/Mozak", "git@github.com:pitfa19/mozak.git", "ssh://git@github.com/pitfa19/mozak.git"]) assert.equal(repoKey(u), k, u); - assert.equal(repoKey("file:///tmp/x/tool.git"), "file:/tmp/x/tool"); - assert.equal(repoKey("not a url"), null); -}); - -test("context, plans, check and review show without --scope inside a clone no longer resolve a legacy repo scope", async () => { +test("inside a clone, context, check, review show and plan show need --scope, even for a scope with a repo link", async () => { const { inv, clone } = fixture(); - // 0.6.0: a remote entry is legacy-repo-scope, so a clone's origin matches no working scope. - const ctx = await run(["context", "--config", inv], clone); - assert.equal(ctx.code, 2, ctx.out + ctx.err); - assert.equal(JSON.parse(ctx.out).status, "scope-not-found"); - // The clone never receives plan files. + for (const args of [["context"], ["check"], ["review", "show", "--plan", "p"], ["plan", "show", "--plan", "p"]]) { + const r = await run([...args, "--config", inv], clone); + assert.equal(r.code, 2, `${args.join(" ")}: ${r.out}${r.err}`); + assert.match(r.err, /missing --scope/, args.join(" ")); + } assert.ok(!existsSync(join(clone, "mozak.json"))); assert.equal(g(clone, "status", "--porcelain"), ""); }); -test("an unrelated repo or plain folder gives scope-not-found, and writes still need --scope", async () => { - const { inv, base, clone } = fixture(); - const stranger = join(base, "stranger"); - mkdirSync(stranger); - g(stranger, "init", "-q", "-b", "main"); - g(stranger, "remote", "add", "origin", "https://github.com/someone/else.git"); - const r1 = await run(["context", "--config", inv], stranger); - assert.equal(r1.code, 2); - assert.equal(JSON.parse(r1.out).status, "scope-not-found"); - const plain = join(base, "plain"); - mkdirSync(plain); - assert.equal(JSON.parse((await run(["context", "--config", inv], plain)).out).status, "scope-not-found"); - writeFileSync(join(base, "req.json"), "{}"); - const w = await run(["plan", "propose", "--config", inv, "--request", join(base, "req.json")], clone); - assert.equal(w.code, 2); - assert.match(w.err, /missing --scope/); -}); - -test("explicit --scope still wins inside a clone", async () => { - const { inv, clone } = fixture(); - const r = await run(["context", "--config", inv, "--scope", "other"], clone); - assert.notEqual(JSON.parse(r.out).context?.scope?.id, "tool"); +test("explicit --scope reads the vault folder from anywhere, including a clone", async () => { + const { inv, clone, plans } = fixture(); + const r = await run(["context", "--config", inv, "--scope", "tool", "--json"], clone); + assert.equal(r.code, 0, r.out + r.err); + assert.equal(JSON.parse(r.out).context.scope.id, "tool"); + assert.ok(existsSync(join(plans, "mozak.json"))); + assert.equal(g(clone, "status", "--porcelain"), ""); }); -test("pull refuses a legacy repo scope and clones nothing", async () => { +test("pull is gone: an unknown route that clones nothing and leaves the plans as they were", async () => { const { inv, base, plans } = fixture(); const before = readFileSync(join(plans, "mozak.json")); const dest = join(base, "Downloads", "fresh"); const r = await run(["pull", "--config", inv, "--scope", "tool", "--into", dest, "--json"], base); assert.equal(r.code, 2, r.out + r.err); - assert.equal(JSON.parse(r.out).status, "legacy-repo-scope"); + assert.match(r.err, /unknown route "pull/); assert.ok(!existsSync(dest)); assert.deepEqual(readFileSync(join(plans, "mozak.json")), before); }); diff --git a/packages/core/src/api.ts b/packages/core/src/api.ts index 29bda88..347abea 100644 --- a/packages/core/src/api.ts +++ b/packages/core/src/api.ts @@ -4,7 +4,6 @@ import { DomainError } from "./errors.ts"; import { nonEmptyString as nonEmpty } from "./validate.ts"; -import { existsSync } from "node:fs"; import { resolveScope, type ScopeEntry, type ScopeInventory } from "./scope-index.ts"; import { initScopeState, @@ -23,15 +22,12 @@ import { import { contextView, reviewRows, reviewShow } from "./review.ts"; import { selectContext } from "./context-selection.ts"; import { scopeIndex } from "./scope-list.ts"; -import { cacheIgnoreWarning, commitAndPush, pullRemote, remoteEntries, repoEntries, statusOf, syncRemote } from "./remote.ts"; -import type { RemoteStatus } from "./remote-meta.ts"; -import { cachedVisibility, publicRepoPlansMessage, scopeVisibility } from "./visibility.ts"; import { leftoverTempFiles } from "./durable.ts"; import { cachedUpdateNotice, installedVersion, npmInstall, refreshUpdateCacheIfStale } from "./update.ts"; import { canonical, digest } from "./understanding.ts"; import { decideWarnings, reviseWarnings, tracePlan } from "./assist.ts"; import { annotateScope } from "./scope-store.ts"; -import { ANNOTATIONS_FILE, readAnnotations, type AnnotationsDoc, type AnnotationsRead } from "./annotations.ts"; +import { readAnnotations, type AnnotationsDoc, type AnnotationsRead } from "./annotations.ts"; import { annotationFindings, graphView, readyView, type Universe } from "./crossplan.ts"; import { effectiveDeadline, planDeadline, today } from "./deadlines.ts"; import { annotationsEnabled, annotationsMode, ignoredScopeSettingsFile, loadSettings, rebaseEnabled, SETTINGS_FILE, usageLogSetting } from "./settings.ts"; @@ -40,7 +36,7 @@ import { inspectLock, recoverLock } from "./lock-recover.ts"; import { handEditHistory, MAX_HISTORY } from "./history.ts"; import { LOCAL_SYNC_OK, localEntries, syncLocal, type LocalSyncRow } from "./local-sync.ts"; import { appendUsage, usageLine, usageLogEnabled } from "./usage.ts"; -import { dirname, join } from "node:path"; +import { dirname } from "node:path"; import { readFocus } from "./focus.ts"; import { citedNoteChanges, LocatorResolver, planCitations } from "./locators.ts"; import { similarReport } from "./similar.ts"; @@ -82,7 +78,6 @@ export const OPERATIONS = [ "init", "repair", "sync", - "pull", "render", "rename-files", "retitle", @@ -98,7 +93,7 @@ export const OPERATIONS = [ ] as const; /** Owner-only: refused for every other actor before any file is touched. */ -const OWNER_ONLY = new Set(["decide", "init", "repair", "pull", "rename-files", "retitle", "delete", "annotate", "recover", "prune"]); +const OWNER_ONLY = new Set(["decide", "init", "repair", "rename-files", "retitle", "delete", "annotate", "recover", "prune"]); /** Route name must equal request.action for these routes. */ const ROUTE_ACTIONS = new Set(["propose", "revise", "observe", "complete", "save-discussion", "attach-spec"]); export const DECISION_ACTIONS = [ @@ -434,8 +429,8 @@ function annotationsToken(inv: ScopeInventory, id: string): unknown { } /** - * Read-only, cached view of every inventoried scope for cross-plan resolution. Never fetches: a remote scope is read - * from its local copy as it is. A scope that cannot be read is "unavailable", an id not in the inventory "unknown". + * Read-only, cached view of every inventoried scope for cross-plan resolution. Never fetches. + * A scope that cannot be read is "unavailable", an id not in the inventory "unknown". */ function universeOf(inv: ScopeInventory, seed: Record = {}): Universe { const states = new Map(Object.entries(seed)); @@ -555,10 +550,6 @@ function annotationCheck(inv: ScopeInventory, entry: ScopeEntry, read: ScopeRead try { const settings = loadSettings(inv); out.push(...settings.issues); - // A sidecar in a repo-mode scope is pushed with the plans. Warn about the file even though it is never read. - if (annotationsMode(settings, entry).source === "repo-mode" && existsSync(join(entry.root, ANNOTATIONS_FILE))) { - out.push({ code: "annotations-on-remote", message: "mozak.annotations.json exists in a repo-mode remote scope; annotate refuses these scopes, and the file is ignored by owner routes" }); - } } catch (err) { if (!(err instanceof DomainError)) throw err; out.push({ code: err.code, message: err.message }); @@ -573,7 +564,6 @@ function annotateOp(inv: ScopeInventory, a: Record, actor: Acto if (!isPlain(o.request)) throw invalid("request must be an object"); const entry = resolveScope(inv, nonEmpty(o.scope, "scope")); const mode = annotationsMode(loadSettings(inv), entry); - if (mode.source === "repo-mode") throw new DomainError("annotations-refused-remote", "annotations are refused on repo-mode remote scopes: their plans are committed and pushed to a repository", 2); if (!mode.enabled) throw new DomainError("annotations-disabled", `annotations are off for scope "${entry.id}"; the owner turns them on with "scopes": { "${entry.id}": { "annotations": true } } in the mozak-settings.json next to the inventory`, 2); const result = annotateScope(entry, o.request, universeOf(inv).state); const lockOrCleanup = result.status.startsWith("committed-") || result.status === "projection-updated-lock-held"; @@ -962,99 +952,42 @@ function writeOp(inv: ScopeInventory, operation: string, a: Record e.id === scope); - return all; - } - if (operation === "graph" || operation === "ready") return scope === undefined ? all : all.filter((e) => e.id === scope); - return scope === undefined ? [] : all.filter((e) => e.id === scope); -} - -function remoteOp(inv: ScopeInventory, operation: string, a: Record): OperationOutput { - const base = { committed: false, operation, snapshot: null, projectionStatus: null, projectionUpdated: false } as const; - if (operation === "sync") { - const o = closed(a, "sync arguments", [], ["scope", "local"]); - const local = strictBoolean(o.local, "local"); - if (local && o.scope !== undefined) throw invalid("sync takes scope or local, not both"); - // A local scope syncs the git repo that holds it. A refused scope (outside a vault, legacy repo scope) is refused. - const named = o.scope === undefined ? undefined : resolveScope(inv, nonEmpty(o.scope, "scope")); - if (named && !named.remote) return localSyncOutput(inv, [named], base); - const targets = o.scope === undefined ? remoteEntries(inv) : [resolveRemoteTarget(inv, nonEmpty(o.scope, "scope"))]; - const remote = targets.map((e) => syncRemote(e, { force: true })); - const stale = remote.filter((r) => r.stale).length; - const bases = [...new Set(targets.map((e) => e.remote?.baseDir).filter((b): b is string => b !== undefined))]; - const warnings = bases.flatMap((b) => { const w = cacheIgnoreWarning(b); return w ? [{ code: "cache-not-ignored", message: w }] : []; }); - // Uses the 24-hour cached answer: the plugin syncs every minute and the unauthenticated API allows 60 calls an hour. - // Every remote scope gets an answer for the sidebar label; only repo-mode scopes publish plans, so only they warn. - const exposed = targets.filter((e) => scopeVisibility(e) === "public" && e.remote?.plansMode === "repo").map((e) => ({ code: "public-repo-plans", message: publicRepoPlansMessage(e), scope: e.id })); - const localRows = local ? syncLocal(localEntries(inv.scopes), inv.scopes) : []; - const localBad = localRows.filter((r) => !LOCAL_SYNC_OK.has(r.status)); - return { - exitCode: stale > 0 || localBad.length > 0 ? 6 : 0, - data: { status: stale > 0 || localBad.length > 0 ? "partial" : "ok", ...base, issues: [...remote.filter((r) => r.stale).map((r) => ({ code: "remote-stale", message: `${r.scope}: ${r.error ?? "stale"}`, scope: r.scope })), ...warnings, ...exposed, ...localIssues(localRows)], remote, ...(local ? { local: localRows } : {}) }, - }; - } - const o = closed(a, "pull arguments", ["scope"], ["into"]); - const entry = resolveRemoteTarget(inv, nonEmpty(o.scope, "scope")); - if (entry.remote?.plansMode !== "vault") { - const synced = syncRemote(entry, { force: true }); - if (synced.stale && !existsSync(entry.root)) throw new DomainError("remote-unavailable", `cannot fetch ${synced.remote}: ${synced.error ?? "unknown error"}`, 2); - } - const pulled = pullRemote(entry, o.into === undefined ? undefined : nonEmpty(o.into, "into")); - return { exitCode: 0, data: { status: "ok", ...base, issues: [], pull: pulled } }; +/** + * `mozak sync`: fetch, then fast-forward the git repo (vault) that holds each scope, under the locks of every scope in + * it. `--scope ID` syncs the repo of that scope, otherwise every vault repo in the inventory (`--local` is the same and + * is kept for older callers such as the plugin's sync button). Never pushes, never merges anything but a fast-forward, + * and never touches a code repo: plans live only in vaults since 0.6.0. + */ +function syncOp(inv: ScopeInventory, a: Record): OperationOutput { + const base = { committed: false, operation: "sync", snapshot: null, projectionStatus: null, projectionUpdated: false } as const; + const o = closed(a, "sync arguments", [], ["scope", "local"]); + const local = strictBoolean(o.local, "local"); + if (local && o.scope !== undefined) throw invalid("sync takes scope or local, not both"); + if (o.scope !== undefined) return localSyncOutput(inv, [resolveScope(inv, nonEmpty(o.scope, "scope"))], base); + const rows = syncLocal(localEntries(inv.scopes), inv.scopes); + const bad = rows.filter((r) => !LOCAL_SYNC_OK.has(r.status)).length; + return { exitCode: bad > 0 ? 6 : 0, data: { status: bad > 0 ? "partial" : "ok", ...base, issues: localIssues(rows), local: rows } }; } function localIssues(rows: LocalSyncRow[]): { code: string; message: string; scope?: string }[] { return rows.filter((r) => !LOCAL_SYNC_OK.has(r.status)).map((r) => ({ code: `local-sync-${r.status}`, message: `${r.repo ?? r.scopes.join(", ")}: ${r.error ?? r.status}`, scope: r.scopes[0] })); } -/** `sync --scope LOCAL`: fast-forward the git repo that holds a local scope, under the locks of every scope in it. */ +/** `sync --scope ID`: fast-forward the git repo that holds one scope, under the locks of every scope in it. */ function localSyncOutput(inv: ScopeInventory, targets: ScopeEntry[], base: Record): OperationOutput { const rows = syncLocal(targets, inv.scopes); const bad = rows.filter((r) => !LOCAL_SYNC_OK.has(r.status)); const only = rows.length === 1 ? rows[0]! : null; const exitCode = bad.length === 0 ? 0 : only?.status === "not-fast-forward" ? 3 : only?.status === "busy" ? 4 : only?.status === "not-in-git" || only?.status === "no-upstream" || only?.status === "detached" ? 2 : 6; - return { exitCode, data: { status: bad.length === 0 ? "ok" : only ? `local-sync-${only.status}` : "partial", ...base, issues: localIssues(rows), remote: [], local: rows } }; -} - -function resolveRemoteTarget(inv: ScopeInventory, id: string): ScopeEntry { - const entry = resolveScope(inv, id); - if (!entry.remote) throw new DomainError("scope-not-remote", `scope "${id}" is a local scope, there is nothing to sync`); - return entry; -} - -function attachRemote(output: OperationOutput, statuses: RemoteStatus[]): OperationOutput { - if (statuses.length === 0) return output; - const data: Record = { ...output.data, remote: statuses }; - const rows = data.scopes; - if (Array.isArray(rows)) { - data.scopes = rows.map((row: Record) => { - const st = statuses.find((x) => x.scope === row.id); - return st ? { ...row, remote: st.remote, ref: st.ref, stale: st.stale, lastFetchAt: st.lastFetchAt, source: st.source, ...(st.error ? { staleReason: st.error } : {}) } : row; - }); - } - const stale = statuses.filter((s) => s.stale); - if (stale.length > 0 && Array.isArray(data.issues)) { - data.issues = [...(data.issues as unknown[]), ...stale.map((s) => ({ code: "remote-stale", message: `${s.scope}: using cached copy, fetch failed (${s.error ?? "unknown"})`, scope: s.scope }))]; - } - return { ...output, data }; + return { exitCode, data: { status: bad.length === 0 ? "ok" : only ? `local-sync-${only.status}` : "partial", ...base, issues: localIssues(rows), local: rows } }; } /** - * Regenerate stale mozak.md projections for one local scope or every local scope. Writes only mozak.md. - * Remote scopes are skipped: their projection follows their next sync or write. Conflicts are reported, not overwritten. + * Regenerate stale mozak.md projections for one scope or every scope. Writes only mozak.md. + * Conflicts are reported, not overwritten. */ function renderOp(inv: ScopeInventory, a: Record): OperationOutput { const o = closed(a, "render arguments", [], ["scope", "all"]); @@ -1062,7 +995,6 @@ function renderOp(inv: ScopeInventory, a: Record): OperationOut if ((o.scope === undefined) === !all) throw invalid("render needs exactly one of scope or all"); const targets = all ? inv.scopes : [resolveScope(inv, nonEmpty(o.scope, "scope"))]; const rows = targets.map((entry) => { - if (entry.remote && entry.remote.plansMode === "repo") return { scope: entry.id, result: "remote-skipped", exitCode: 0 }; try { const { result, outcome } = renderProjection(resolveScope(inv, entry.id)); return { scope: entry.id, result, exitCode: resultExit(outcome), code: outcome.status, projectionUpdated: outcome.projectionUpdated, projectionStatus: outcome.projectionStatus, ...(outcome.issues.length ? { issues: outcome.issues } : {}) }; @@ -1089,8 +1021,7 @@ function renderOp(inv: ScopeInventory, a: Record): OperationOut } /** - * Rename pre-0.4 MOZAK.json / MOZAK.md to mozak.json / mozak.md for one local scope or every local scope. - * Repo-mode remote scopes are skipped: rename those in their own clone and push. Never changes plan content. + * Rename pre-0.4 MOZAK.json / MOZAK.md to mozak.json / mozak.md for one scope or every scope. Never changes plan content. */ function renameFilesOp(inv: ScopeInventory, a: Record): OperationOutput { const o = closed(a, "rename-files arguments", [], ["scope", "all"]); @@ -1098,7 +1029,6 @@ function renameFilesOp(inv: ScopeInventory, a: Record): Operati if ((o.scope === undefined) === !all) throw invalid("rename-files needs exactly one of scope or all"); const targets = all ? inv.scopes : [resolveScope(inv, nonEmpty(o.scope, "scope"))]; const rows = targets.map((entry) => { - if (entry.remote && entry.remote.plansMode === "repo") return { scope: entry.id, result: "remote-skipped", exitCode: 0 }; try { const { result, outcome } = renameScopeFiles(resolveScope(inv, entry.id)); return { scope: entry.id, result, exitCode: resultExit(outcome), code: outcome.status, ...(outcome.issues.length ? { issues: outcome.issues } : {}) }; @@ -1235,10 +1165,9 @@ function runOperation(inv: ScopeInventory, operation: string, args: unknown, act if (!(OPERATIONS as readonly string[]).includes(operation)) { throw new DomainError("unsupported-operation", `unknown operation "${operation}"`, 2); } - if (operation === "sync" || operation === "pull") { - if (OWNER_ONLY.has(operation)) requireOwner(operation, actor); + if (operation === "sync") { if (!isPlain(args)) throw invalid("arguments must be an object"); - return remoteOp(inv, operation, args); + return syncOp(inv, args); } if (operation === "render") { if (!isPlain(args)) throw invalid("arguments must be an object"); @@ -1255,7 +1184,7 @@ function runOperation(inv: ScopeInventory, operation: string, args: unknown, act return recoverOp(inv, args); } if (operation === "annotate") { - // Never routed through remoteWrite: annotations never commit or push. Repo-mode scopes are refused inside. + // Annotations never commit or push. requireOwner(operation, actor); if (!isPlain(args)) throw invalid("arguments must be an object"); return annotateOp(inv, args, actor); @@ -1265,49 +1194,20 @@ function runOperation(inv: ScopeInventory, operation: string, args: unknown, act if (!isPlain(args)) throw invalid("arguments must be an object"); return operation === "similar" ? similarOp(inv, args) : operation === "locators" ? locatorsOp(inv, args) : plansMdOp(inv, args, actor); } - if (REMOTE_READ_OPS.has(operation)) { + if (READ_OPS.has(operation)) { if (!isPlain(args)) throw invalid("arguments must be an object"); - const touched = touchedRemotes(inv, operation, args); - const statuses = touched.map((e) => syncRemote(e)); - const out = attachRemote(readOp(inv, operation, args), statuses); + const out = readOp(inv, operation, args); if (operation !== "scopes") return out; - // Reads never wait on the network for this: only an already cached "public" answer warns. - const exposed = repoEntries(inv).filter((e) => cachedVisibility(e) === "public"); + // Reads never wait on the network for this: only an already cached newer release is reported. const update = scopesUpdateIssue(); - if ((exposed.length === 0 && !update) || !Array.isArray(out.data.issues)) return out; - return { ...out, data: { ...out.data, issues: [...(out.data.issues as unknown[]), ...exposed.map((e) => ({ code: "public-repo-plans", message: publicRepoPlansMessage(e), scope: e.id })), ...(update ? [update] : [])] } }; + if (!update || !Array.isArray(out.data.issues)) return out; + return { ...out, data: { ...out.data, issues: [...(out.data.issues as unknown[]), update] } }; } - const input = isPlain(args) ? args : {}; - // Only repo-mode remote scopes commit and push. Vault-plans scopes write like local scopes. - const target = touchedRemotes(inv, operation, input).find((e) => e.remote?.plansMode === "repo"); - if (target === undefined) return attachRemote(writeOp(inv, operation, input, actor), touchedRemotes(inv, operation, input).map((e) => statusOf(e, false))); - return remoteWrite(inv, operation, input, actor, target); + return writeOp(inv, operation, isPlain(args) ? args : {}, actor); } catch (err) { if (err instanceof DomainError) return errorOutput(err, operation, args); throw err; } } -/** Write against a remote scope: refresh first, refuse on a stale base, then commit mozak.json and mozak.md and push. */ -function remoteWrite(inv: ScopeInventory, operation: string, input: Record, actor: Actor, entry: ScopeEntry): OperationOutput { - if (OWNER_ONLY.has(operation)) requireOwner(operation, actor); - if (scopeVisibility(entry) === "public") throw new DomainError("public-repo-plans", `refusing to write: ${publicRepoPlansMessage(entry)}`, 3); - const status = syncRemote(entry, { force: true }); - if (status.stale) { - throw new DomainError("remote-stale", `refusing to write: cannot refresh ${status.remote} (${status.error ?? "unknown"}). Run \`mozak sync\` when online.`, 3); - } - const output = writeOp(inv, operation, input, actor); - const data = output.data as { committed?: boolean; projectionUpdated?: boolean; issues?: { code: string; message: string }[] }; - if (!data.committed && !data.projectionUpdated) return attachRemote(output, [status]); - try { - const done = commitAndPush(entry, `mozak: ${operation} ${plainScope(input) ?? entry.id}`); - const after = syncRemote(entry, { force: false }); - return attachRemote({ exitCode: output.exitCode, data: { ...output.data, remotePush: done } }, [after]); - } catch (err) { - if (!(err instanceof Error) || err instanceof DomainError) throw err; - const issue = { code: "remote-push-failed", message: `committed locally but not pushed: ${err.message}. It is pushed on the next \`mozak sync\`.` }; - return attachRemote({ exitCode: 5, data: { ...output.data, issues: [...(data.issues ?? []), issue] } }, [{ ...statusOf(entry, true, err.message) }]); - } -} - export { DEFAULT_LIMIT, MAX_LIMIT, OWNER_ONLY, ROUTE_ACTIONS }; diff --git a/packages/core/src/git-commit.ts b/packages/core/src/git-commit.ts index 6245362..29f70f2 100644 --- a/packages/core/src/git-commit.ts +++ b/packages/core/src/git-commit.ts @@ -1,7 +1,7 @@ -// Opt-in git commit for a local (or vault-plans) scope after a write. `mozak --commit`. +// Opt-in git commit for a scope after a write. `mozak --commit`. // A mozak write "commits" the scope transaction to mozak.json and mozak.md on disk. It does not -// touch git for local scopes, because those usually live in a repo the caller owns (a vault, a -// project). This helper is the explicit follow-up: commit just the two scope files in the +// touch git by itself, because scopes live in a repo the caller owns (a vault). This helper is the +// explicit follow-up: commit just the scope files in the // containing repo, then pull --rebase and push when the branch has an upstream. Never forces. import { execFileSync } from "node:child_process"; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index fe71037..761cb38 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -21,10 +21,7 @@ export * from "./roadmap.ts"; export { mdText, stopLabel, completedPlanLine, planHeading, planDisplayState, progressStrip, type PlanDisplayState } from "./bridge.ts"; export * from "./api.ts"; export * from "./assist.ts"; -export * from "./remote-meta.ts"; -export * from "./remote.ts"; -export * from "./visibility.ts"; -export * from "./working-copy.ts"; +export * from "./legacy-entry.ts"; export * from "./durable.ts"; export * from "./update.ts"; export * from "./annotations.ts"; diff --git a/packages/core/src/legacy-entry.ts b/packages/core/src/legacy-entry.ts index c61b508..f65c3e7 100644 --- a/packages/core/src/legacy-entry.ts +++ b/packages/core/src/legacy-entry.ts @@ -6,11 +6,12 @@ import { readFileSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; +import { CACHE_DIR } from "./usage.ts"; import { vaultOf } from "./vault-config.ts"; export const LEGACY_KEYS = ["remote", "ref", "plans"] as const; -/** The cache folder 0.5.0 kept next to the inventory for repo scopes. */ -export const LEGACY_CACHE_DIR = ".mozak-cache"; +/** The cache folder 0.5.0 kept next to the inventory for repo scopes (same folder as the usage log). */ +export const LEGACY_CACHE_DIR = CACHE_DIR; export interface LegacyLocation { root: string; refused: { code: string; message: string } } diff --git a/packages/core/src/local-sync.ts b/packages/core/src/local-sync.ts index 3976d81..97c0e33 100644 --- a/packages/core/src/local-sync.ts +++ b/packages/core/src/local-sync.ts @@ -27,13 +27,13 @@ function git(cwd: string, args: string[], timeout = 20_000): string { } function tryGit(cwd: string, args: string[]): string | null { try { return git(cwd, args); } catch { return null; } } -/** Scopes whose plan files live in a local folder: local scopes and vault-plans scopes. Repo-mode remotes have their own sync. Refused entries are never synced. */ +/** Scopes whose plan files live in a vault folder (every working scope). Refused entries are never synced. */ export function localEntries(scopes: ScopeEntry[]): ScopeEntry[] { - return scopes.filter((s) => !s.refused && (!s.remote || s.remote.plansMode === "vault")); + return scopes.filter((s) => !s.refused); } /** - * Sync the git repos that hold `targets`. Every inventoried local or vault-plans scope inside such a repo is locked + * Sync the git repos that hold `targets`. Every inventoried scope inside such a repo is locked * during the merge, not only the targets, because the merge rewrites the whole working tree. */ export function syncLocal(targets: ScopeEntry[], all: ScopeEntry[], options: StoreOptions = {}): LocalSyncRow[] { diff --git a/packages/core/src/locators.ts b/packages/core/src/locators.ts index a030d65..285eea0 100644 --- a/packages/core/src/locators.ts +++ b/packages/core/src/locators.ts @@ -29,8 +29,6 @@ export type LocatorStatus = | "missing" /** A note link with several matching notes and none in the citing scope. */ | "ambiguous" - /** A relative path in a scope whose code lives in a remote repo that is not cloned here. */ - | "remote" /** Prose (an owner message, a command): nothing to resolve. */ | "not-checked"; @@ -62,7 +60,7 @@ const inside = (path: string, dir: string) => path === dir || path.startsWith(di export function defaultIndexRoots(inv: ScopeInventory): LocatorRoot[] { const out = new Map(); for (const entry of inv.scopes) { - if (entry.refused || (entry.remote && entry.remote.plansMode === "repo")) continue; + if (entry.refused) continue; const root = realOrSelf(entry.root); const repo = findRepoRoot(root); if (!repo || repo === root) continue; @@ -172,7 +170,7 @@ export class LocatorResolver { const pathLike = explicit || (!/['"`;,]|\s{2}/.test(path) && /^[^\s:]+(?: [^\s:]+){0,6}$/.test(path) && (path.includes("/") || EXT_RE.test(path))); if (!pathLike) return { kind: "text", status: "not-checked" }; - for (const candidate of this.candidates(entry, scopeRoot, path)) { + for (const candidate of this.candidates(scopeRoot, path)) { if (existsSync(candidate)) return this.found(realOrSelf(candidate), anchorUsed, scopeRoot, "path"); } // A bare note name with .md may be a note anywhere in the roots, as Obsidian would find it. @@ -180,17 +178,15 @@ export class LocatorResolver { const note = this.resolveNote(scopeRoot, path, anchorUsed); if (note.status !== "missing") return { ...note, kind: "path" }; } - if (!explicit && entry.remote && !entry.remote.fullClone) return { kind: "path", status: "remote" }; return { kind: "path", status: "missing" }; } - private candidates(entry: ScopeEntry, scopeRoot: string, path: string): string[] { + private candidates(scopeRoot: string, path: string): string[] { if (path === "~" || path.startsWith("~/")) return [join(homedir(), path.slice(1))]; if (isAbsolute(path)) return [path]; const bases = [scopeRoot]; const repo = findRepoRoot(scopeRoot); if (repo) bases.push(repo); - if (entry.remote?.fullClone) bases.push(entry.remote.fullClone); for (const r of this.roots) bases.push(dirname(r.path), r.path); return [...new Set(bases.map((b) => resolve(b, path)))]; } diff --git a/packages/core/src/plans-index.ts b/packages/core/src/plans-index.ts index 8c68749..adb90bd 100644 --- a/packages/core/src/plans-index.ts +++ b/packages/core/src/plans-index.ts @@ -39,7 +39,7 @@ export interface PlansIndexFile { content: string; } -export interface PlansIndexSkip { scope: string; reason: "repo-mode-remote" | "not-in-git-repo" } +export interface PlansIndexSkip { scope: string; reason: "not-in-git-repo" } export interface PlansIndexResult { files: PlansIndexFile[]; skipped: PlansIndexSkip[] } @@ -60,14 +60,13 @@ export function renderPlansIndex(scopes: { id: string; folder: string; state: Sc } /** - * Build plans.md for every repository in the inventory. `write: false` only returns the text. Never fetches: repo-mode - * remote scopes are skipped (their plans live in a code repo, not a vault), and scopes outside git are skipped. + * Build plans.md for every repository in the inventory. `write: false` only returns the text. Never fetches. + * Scopes outside git are skipped; a refused scope is listed without plans. */ export function plansIndex(inv: ScopeInventory, opts: { write: boolean }): PlansIndexResult { const byRepo = new Map(); const skipped: PlansIndexSkip[] = []; for (const entry of inv.scopes) { - if (entry.remote && entry.remote.plansMode === "repo") { skipped.push({ scope: entry.id, reason: "repo-mode-remote" }); continue; } const repo = findRepoRoot(entry.root); if (!repo) { skipped.push({ scope: entry.id, reason: "not-in-git-repo" }); continue; } const folder = relative(repo, realOrSelf(entry.root)).split(sep).join("/") || "."; diff --git a/packages/core/src/remote-meta.ts b/packages/core/src/remote-meta.ts deleted file mode 100644 index 67d3173..0000000 --- a/packages/core/src/remote-meta.ts +++ /dev/null @@ -1,117 +0,0 @@ -// Pure helpers for remote scopes: spec parsing and the small cache metadata file. No git and no network here, -// so the inventory loader can use them. All git work lives in remote.ts. - -import { mkdirSync, readFileSync } from "node:fs"; -import { join } from "node:path"; -import { replaceFileDurable } from "./durable.ts"; - -export const CACHE_DIR = ".mozak-cache"; -export const DEFAULT_REF = "main"; -/** Plain branch names only. No leading dash, no "..", no whitespace or git revision syntax. */ -export const REF_PATTERN = /^(?!.*\.\.)[A-Za-z0-9][A-Za-z0-9._/-]{0,99}$/; -/** A remote scope is considered fresh for this long after a successful fetch. */ -export const FRESH_MS = 10 * 60 * 1000; - -export interface RemoteInfo { - /** The inventory value, for example "github:pitfa19/genome-mcp". */ - spec: string; - /** The URL handed to git. */ - url: string; - ref: string; - repoName: string; - /** Directory of the inventory file. The cache lives under it. */ - baseDir: string; - /** Canonical sparse cache copy: /.mozak-cache/. */ - cacheRoot: string; - /** Canonical full working clone created by `mozak pull`, when it still exists. Reads and writes prefer it. */ - fullClone: string | null; - /** - * Where the plan files live. "repo": inside the linked repo (sparse cache or full clone), committed and pushed. - * "vault": in a local plans folder named by the inventory; the repo is linked for display and cloning only. - */ - plansMode: "repo" | "vault"; -} - -export interface ParsedRemote { url: string; repoName: string } - -const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; - -export function parseRemoteSpec(spec: string): ParsedRemote | null { - if (spec !== spec.trim() || spec === "") return null; - if (spec.startsWith("github:")) { - const parts = spec.slice("github:".length).split("/"); - if (parts.length !== 2) return null; - const [owner, repoRaw] = parts as [string, string]; - const repo = repoRaw.replace(/\.git$/, ""); - if (!SLUG.test(owner) || !SLUG.test(repo)) return null; - return { url: `https://github.com/${owner}/${repo}.git`, repoName: repo }; - } - const https = /^https:\/\/[A-Za-z0-9][A-Za-z0-9.-]*(:\d{1,5})?\/([A-Za-z0-9._~/-]+)$/.exec(spec); - const file = /^file:\/\/(\/[A-Za-z0-9._~/@+-]+)$/.exec(spec); - const match = https ?? file; - if (!match) return null; - const path = (https ? https[2] : file?.[1]) as string; - if (path.split("/").includes("..")) return null; - const last = path.split("/").filter(Boolean).pop() as string; - const repoName = last.replace(/\.git$/, ""); - if (!SLUG.test(repoName)) return null; - return { url: spec, repoName }; -} - -export function cacheRootFor(baseDir: string, id: string): string { - return join(baseDir, CACHE_DIR, id); -} - -export interface RemoteMeta { - lastFetchAt: string | null; - lastError: string | null; - fullClone: string | null; - /** Last fetch attempt, successful or not. After a failure, reads skip the network until it is ten minutes old. */ - lastAttemptAt?: string | null; - /** Last unauthenticated GitHub visibility answer for a repo-mode scope, and when it was taken. */ - visibility?: Visibility | null; - visibilityCheckedAt?: string | null; -} - -export type Visibility = "public" | "private-or-missing" | "unknown"; - -function metaPath(baseDir: string, id: string): string { - return join(baseDir, CACHE_DIR, `${id}.meta.json`); -} - -export function readRemoteMeta(baseDir: string, id: string): RemoteMeta { - const empty: RemoteMeta = { lastFetchAt: null, lastError: null, fullClone: null }; - try { - const raw = JSON.parse(readFileSync(metaPath(baseDir, id), "utf8")) as Record; - const str = (v: unknown) => (typeof v === "string" && v !== "" ? v : null); - const vis = raw.visibility === "public" || raw.visibility === "private-or-missing" || raw.visibility === "unknown" ? raw.visibility : null; - return { lastFetchAt: str(raw.lastFetchAt), lastError: str(raw.lastError), fullClone: str(raw.fullClone), visibility: vis, visibilityCheckedAt: str(raw.visibilityCheckedAt), lastAttemptAt: str(raw.lastAttemptAt) }; - } catch { - return empty; - } -} - -export function writeRemoteMeta(baseDir: string, id: string, meta: RemoteMeta): void { - mkdirSync(join(baseDir, CACHE_DIR), { recursive: true }); - replaceFileDurable(metaPath(baseDir, id), `${JSON.stringify(meta, null, 2)}\n`); -} - -/** Status shown next to a remote scope in every read output. */ -export interface RemoteStatus { - scope: string; - remote: string; - ref: string; - /** True when the last refresh failed or is older than the freshness window and could not be renewed. */ - stale: boolean; - lastFetchAt: string | null; - /** Why the copy is stale, when it is. */ - error?: string; - /** "full-clone" when reads use a clone made by `mozak pull`, "vault" when plans live in a vault folder, otherwise "sparse-cache". */ - source: "sparse-cache" | "full-clone" | "vault"; - /** - * "fetched": refreshed by this call. "cached": the last fetch is under ten minutes old, nothing was fetched. - * "offline": the fetch failed (now or within the last ten minutes) and the cached copy is used. - * "local": plans live in a vault folder and are never fetched. - */ - remoteFreshness: "fetched" | "cached" | "offline" | "local"; -} diff --git a/packages/core/src/remote.ts b/packages/core/src/remote.ts deleted file mode 100644 index bfd1aef..0000000 --- a/packages/core/src/remote.ts +++ /dev/null @@ -1,264 +0,0 @@ -// Remote scopes. A remote scope is a git repo cached next to the inventory file. Only README.md, the plan files -// (mozak.json, mozak.md, or their pre-0.4 MOZAK.* names) and AGENTS.md are checked out (sparse, blobless, depth 1). Everything shells out to git with -// execFile (no shell), a hard timeout and no terminal prompts. Nothing outside inventoried scopes is touched. - -import { execFileSync } from "node:child_process"; -import { SCOPE_FILE_NAMES, scopeFile, scopeFileName } from "./scope-files.ts"; -import { randomUUID } from "node:crypto"; -import { existsSync, lstatSync, mkdirSync, renameSync, rmSync } from "node:fs"; -import { homedir } from "node:os"; -import { basename, dirname, join, resolve } from "node:path"; -import { DomainError } from "./errors.ts"; -import { FRESH_MS, readRemoteMeta, writeRemoteMeta, type RemoteStatus } from "./remote-meta.ts"; -import type { ScopeEntry, ScopeInventory } from "./scope-index.ts"; - -export const SPARSE_FILES = ["README.md", ...SCOPE_FILE_NAMES, "AGENTS.md"] as const; -const CLONE_TIMEOUT_MS = 120_000; -const GIT_TIMEOUT_MS = 60_000; - -function git(args: string[], cwd: string | undefined, timeout = GIT_TIMEOUT_MS): string { - try { - return execFileSync("git", args, { - cwd, - encoding: "utf8", - timeout, - maxBuffer: 8 * 1024 * 1024, - stdio: ["ignore", "pipe", "pipe"], - env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "", LC_ALL: "C" }, - }); - } catch (err) { - const e = err as { stderr?: Buffer | string; killed?: boolean; code?: string; message?: string }; - const stderr = String(e.stderr ?? "").trim().split("\n").slice(-3).join(" "); - const why = e.killed || e.code === "ETIMEDOUT" ? `timed out after ${timeout / 1000}s` : stderr || e.message || "git failed"; - throw new GitFailure(`git ${args[0]}: ${why}`); - } -} - -class GitFailure extends Error {} - -function remoteOf(entry: ScopeEntry) { - if (!entry.remote) throw new DomainError("scope-not-remote", `scope "${entry.id}" is not a remote scope`); - return entry.remote; -} - -function isRepo(dir: string): boolean { - try { - return lstatSync(join(dir, ".git")).isDirectory(); - } catch { - return false; - } -} - -function sparsePatterns(): string[] { - return SPARSE_FILES.map((name) => `/${name}`); -} - -function cloneSparse(entry: ScopeEntry): void { - const r = remoteOf(entry); - mkdirSync(dirname(r.cacheRoot), { recursive: true }); - const tmp = `${r.cacheRoot}.tmp-${randomUUID()}`; - try { - git(["clone", "--filter=blob:none", "--no-checkout", "--depth", "1", "--sparse", "--branch", r.ref, "--", r.url, tmp], undefined, CLONE_TIMEOUT_MS); - git(["sparse-checkout", "set", "--no-cone", "--", ...sparsePatterns()], tmp); - git(["checkout", "--quiet", r.ref], tmp, CLONE_TIMEOUT_MS); - if (existsSync(r.cacheRoot)) rmSync(r.cacheRoot, { recursive: true, force: true }); - renameSync(tmp, r.cacheRoot); - } finally { - if (existsSync(tmp)) rmSync(tmp, { recursive: true, force: true }); - } -} - -function pendingFiles(dir: string): boolean { - return git(["status", "--porcelain", "--", ...SCOPE_FILE_NAMES], dir).trim() !== ""; -} - -function aheadCount(dir: string, ref: string): number { - try { - return Number(git(["rev-list", "--count", `refs/remotes/origin/${ref}..HEAD`], dir).trim()) || 0; - } catch { - return 0; - } -} - -function identityEnvFix(dir: string): string[] { - // Commit with the user's git identity. Fall back to a neutral one only when none is configured. - let email = ""; - try { email = git(["config", "user.email"], dir).trim(); } catch { /* unset */ } - return email ? [] : ["-c", "user.name=mozak", "-c", "user.email=mozak@localhost"]; -} - -function currentBranch(dir: string): string { - return git(["rev-parse", "--abbrev-ref", "HEAD"], dir).trim(); -} - -/** Commit only the two plan files, then push. Returns whether a commit was made. */ -export function commitAndPush(entry: ScopeEntry, message: string): { committed: boolean; pushed: boolean } { - const r = remoteOf(entry); - const dir = entry.root; - if (currentBranch(dir) !== r.ref) { - throw new GitFailure(`checked out branch is "${currentBranch(dir)}", expected "${r.ref}"`); - } - let committed = false; - if (pendingFiles(dir)) { - const present = [scopeFileName(dir, "graph"), scopeFileName(dir, "bridge")].filter((n) => existsSync(join(dir, n))); - git(["add", "--", ...present], dir); - git([...identityEnvFix(dir), "commit", "--no-verify", "--quiet", "-m", message, "--", ...present], dir); - committed = true; - } - let pushed = false; - if (aheadCount(dir, r.ref) > 0) { - git(["push", "--quiet", "origin", `HEAD:refs/heads/${r.ref}`], dir, CLONE_TIMEOUT_MS); - pushed = true; - } - return { committed, pushed }; -} - -function refresh(entry: ScopeEntry): void { - const r = remoteOf(entry); - const full = r.fullClone !== null && r.fullClone === entry.root; - const dir = entry.root; - if (!isRepo(dir)) { - if (full) throw new GitFailure("full clone is missing"); - cloneSparse(entry); - return; - } - if (currentBranch(dir) !== r.ref) throw new GitFailure(`checked out branch is "${currentBranch(dir)}", expected "${r.ref}"`); - if (!full) { - // The sparse cache is a mirror. Recover interrupted writes and push unpushed commits before replacing it. - if (pendingFiles(dir)) commitAndPush(entry, "mozak: recover uncommitted scope state"); - else if (aheadCount(dir, r.ref) > 0) commitAndPush(entry, "mozak: push pending scope state"); - git(["fetch", "--quiet", "--depth", "1", "origin", r.ref], dir, CLONE_TIMEOUT_MS); - const head = git(["rev-parse", "HEAD"], dir).trim(); - const fetched = git(["rev-parse", "FETCH_HEAD"], dir).trim(); - if (head !== fetched) git(["reset", "--hard", "--quiet", "FETCH_HEAD"], dir); - return; - } - git(["fetch", "--quiet", "origin", r.ref], dir, CLONE_TIMEOUT_MS); - git(["merge", "--ff-only", "--quiet", "FETCH_HEAD"], dir); -} - -export function statusOf(entry: ScopeEntry, stale: boolean, error?: string, freshness?: RemoteStatus["remoteFreshness"]): RemoteStatus { - const r = remoteOf(entry); - if (r.plansMode === "vault") return vaultStatus(entry); - const meta = readRemoteMeta(r.baseDir, entry.id); - return { - scope: entry.id, - remote: r.spec, - ref: r.ref, - stale, - lastFetchAt: meta.lastFetchAt, - ...(error ? { error } : {}), - source: r.fullClone !== null && r.fullClone === entry.root ? "full-clone" : "sparse-cache", - remoteFreshness: freshness ?? (stale ? "offline" : "cached"), - }; -} - -/** Status row for a vault-plans scope. Plans are local, so nothing is fetched and nothing is ever stale. */ -export function vaultStatus(entry: ScopeEntry): RemoteStatus { - const r = remoteOf(entry); - return { scope: entry.id, remote: r.spec, ref: r.ref, stale: false, lastFetchAt: null, source: "vault", remoteFreshness: "local" }; -} - -/** - * Refresh one remote scope when forced or when the last successful fetch is older than ten minutes. - * A fetch failure never throws: the cached copy is used and reported stale. - * After a failed fetch, unforced reads use the cached copy for ten minutes without retrying the network, so an - * offline machine does not pay a git timeout on every read. `mozak sync` and writes always force a fetch. - * Vault-plans scopes never run git: their plans are local and the repo is linked for display only. - */ -export function syncRemote(entry: ScopeEntry, opts: { force?: boolean; now?: Date } = {}): RemoteStatus { - const r = remoteOf(entry); - if (r.plansMode === "vault") return vaultStatus(entry); - const now = opts.now ?? new Date(); - const meta = readRemoteMeta(r.baseDir, entry.id); - const have = isRepo(entry.root); - const age = meta.lastFetchAt ? now.getTime() - Date.parse(meta.lastFetchAt) : Infinity; - if (!opts.force && have && meta.lastError === null && age < FRESH_MS) return statusOf(entry, false, undefined, "cached"); - const attemptAge = meta.lastAttemptAt ? now.getTime() - Date.parse(meta.lastAttemptAt) : Infinity; - if (!opts.force && have && meta.lastError !== null && attemptAge >= 0 && attemptAge < FRESH_MS) return statusOf(entry, true, meta.lastError, "offline"); - try { - refresh(entry); - writeRemoteMeta(r.baseDir, entry.id, { ...meta, lastFetchAt: now.toISOString(), lastError: null, fullClone: meta.fullClone, lastAttemptAt: now.toISOString() }); - return statusOf(entry, false, undefined, "fetched"); - } catch (err) { - if (!(err instanceof GitFailure)) throw err; - writeRemoteMeta(r.baseDir, entry.id, { ...meta, lastError: err.message, lastAttemptAt: now.toISOString() }); - return statusOf(entry, true, err.message, "offline"); - } -} - -/** Every remote scope, repo-mode and vault-mode. Use repoEntries for anything that runs git on plan files. */ -export function remoteEntries(inv: ScopeInventory): ScopeEntry[] { - return inv.scopes.filter((s) => s.remote !== undefined); -} - -/** Remote scopes whose plan files live in the repo, so reads fetch and writes commit and push. */ -export function repoEntries(inv: ScopeInventory): ScopeEntry[] { - return inv.scopes.filter((s) => s.remote !== undefined && s.remote.plansMode === "repo"); -} - -function normalizeUrl(url: string): string { - return url.trim().replace(/\/+$/, "").replace(/\.git$/, "").toLowerCase(); -} - -export interface PullResult { scope: string; destination: string; created: boolean; remote: string; ref: string } - -/** Convert a remote scope into a full working clone. Never overwrites a different repo. - * For a vault-plans scope this only clones the code: plans stay in the vault and nothing is recorded as the scope root. */ -export function pullRemote(entry: ScopeEntry, into?: string): PullResult { - const r = remoteOf(entry); - const dest = resolve(into ? (into === "~" || into.startsWith("~/") ? join(homedir(), into.slice(1)) : into) : join(homedir(), "Documents", r.repoName)); - const vault = r.plansMode === "vault"; - const meta = readRemoteMeta(r.baseDir, entry.id); - let created = false; - if (existsSync(dest)) { - let origin = ""; - try { - if (!isRepo(dest)) throw new GitFailure("not a git repository"); - origin = git(["remote", "get-url", "origin"], dest).trim(); - } catch { - throw new DomainError("pull-destination-exists", `${dest} exists and is not the ${r.spec} repository`, 2); - } - if (normalizeUrl(origin) !== normalizeUrl(r.url)) { - throw new DomainError("pull-destination-exists", `${dest} exists and its origin is ${origin}, not ${r.spec}`, 2); - } - } else { - // Push anything the sparse cache still holds, so the full clone starts from the same history. - if (!vault && isRepo(r.cacheRoot) && r.fullClone === null) { - try { if (pendingFiles(r.cacheRoot) || aheadCount(r.cacheRoot, r.ref) > 0) commitAndPush({ ...entry, root: r.cacheRoot }, "mozak: push pending scope state"); } catch (err) { - if (!(err instanceof GitFailure)) throw err; - throw new DomainError("pull-unpushed-state", `sparse cache has unpushed mozak state: ${err.message}`, 3); - } - } - try { - mkdirSync(dirname(dest), { recursive: true }); - git(["clone", "--branch", r.ref, "--", r.url, dest], undefined, CLONE_TIMEOUT_MS * 3); - } catch (err) { - if (!(err instanceof GitFailure)) throw err; - if (existsSync(dest) && basename(dest) !== "") rmSync(dest, { recursive: true, force: true }); - throw new DomainError("pull-failed", err.message, 2); - } - created = true; - } - if (vault) return { scope: entry.id, destination: dest, created, remote: r.spec, ref: r.ref }; - if (!existsSync(scopeFile(dest, "graph"))) { - throw new DomainError("scope-uninitialized", `not a scope: no mozak.json at the root of ${dest}`, 2); - } - writeRemoteMeta(r.baseDir, entry.id, { lastFetchAt: meta.lastFetchAt, lastError: null, fullClone: dest }); - return { scope: entry.id, destination: dest, created, remote: r.spec, ref: r.ref }; -} - -/** Warning text when the inventory directory is a git repo that does not ignore .mozak-cache. Null otherwise. */ -export function cacheIgnoreWarning(baseDir: string): string | null { - try { - if (git(["rev-parse", "--is-inside-work-tree"], baseDir).trim() !== "true") return null; - } catch { - return null; - } - try { - git(["check-ignore", "-q", "--no-index", "--", ".mozak-cache/probe"], baseDir); - return null; - } catch { - return `${baseDir} is a git repository that does not ignore .mozak-cache/. Add ".mozak-cache/" to its .gitignore.`; - } -} diff --git a/packages/core/src/scope-index.ts b/packages/core/src/scope-index.ts index 9e8774c..6d5cada 100644 --- a/packages/core/src/scope-index.ts +++ b/packages/core/src/scope-index.ts @@ -2,14 +2,13 @@ import { createHash } from "node:crypto"; import { lstatSync, readFileSync, realpathSync, statSync, type Stats } from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; import { DomainError } from "./errors.ts"; -import type { RemoteInfo } from "./remote-meta.ts"; import { isLegacyEntry, LEGACY_KEYS, legacyLocation } from "./legacy-entry.ts"; import { parseRepoLink, REPO_LINK_HELP } from "./repo-link.ts"; import { vaultOf } from "./vault-config.ts"; /** Pilot-local explicit inventory. Never a global registration or a directory scan. */ export const INVENTORY_FORMAT_V2 = "mozak.local/v2" as const; -/** v3 adds optional remote scope entries. v2 inventories are still accepted unchanged. */ +/** v3 adds optional entry keys (focus, repo). v2 inventories are still accepted unchanged. */ export const INVENTORY_FORMAT = "mozak.local/v3" as const; export type InventoryFormat = typeof INVENTORY_FORMAT_V2 | typeof INVENTORY_FORMAT; export const WRITE_LOCK_DIR = ".mozak-write-lock"; @@ -19,8 +18,6 @@ export interface ScopeEntry { id: string; /** Canonical absolute root as observed at inventory load (or lexical path for a root not yet present). */ root: string; - /** Present only for a remote scope. `root` is then the cache working copy, or the full clone after `mozak pull`. */ - remote?: RemoteInfo; /** Diagnostic only: reserved x settings were ignored at inventory or selected-entry level. */ inventoryExtensionsIgnored?: true; /** Display-only link to the code repo (`github:owner/repo` or an https URL), when the entry has one. */ @@ -262,8 +259,7 @@ export function resolveScope(inv: ScopeInventory, id: string): ScopeEntry { stats = statSync(real); } catch (err) { if (isMissing(err)) { - const hint = entry.remote ? (entry.remote.plansMode === "vault" ? " (vault plans folder missing)" : " (remote scope not fetched yet: run `mozak sync`)") : ""; - throw new DomainError("scope-root-missing", `scope "${id}" root is missing: ${entry.root}${hint}`); + throw new DomainError("scope-root-missing", `scope "${id}" root is missing: ${entry.root}`); } throw new DomainError("scope-root-unreadable", `scope "${id}" root is unreadable: ${entry.root}`); } diff --git a/packages/core/src/scope-move.ts b/packages/core/src/scope-move.ts index f3d1a0d..8eeec41 100644 --- a/packages/core/src/scope-move.ts +++ b/packages/core/src/scope-move.ts @@ -78,7 +78,7 @@ function moveRepoArg(value: unknown, drop: boolean): string | null { return repo; } -/** Run `check` on the source folder as a plain local scope: no settings, no remote refresh, no network. */ +/** Run `check` on the source folder as a plain scope: no settings, no vault rule, no network. */ function assertSourceChecks(entry: ScopeEntry): void { const local: ScopeInventory = { format: "mozak.local/v3", scopes: [{ id: entry.id, root: entry.root }], digest: "" }; const out = executeOperation(local, "check", { scope: entry.id }); diff --git a/packages/core/src/scope-store.ts b/packages/core/src/scope-store.ts index 4dcccad..533adec 100644 --- a/packages/core/src/scope-store.ts +++ b/packages/core/src/scope-store.ts @@ -141,7 +141,7 @@ function readScopeWith(entry: ScopeEntry, options: StoreOptions, diagnostics: bo assertScopeFiles(entry.root); for (let attempt = 0; attempt < 3; attempt++) { const a = file(scopeFile(entry.root, "graph")); - if (a.bytes === null) throw new DomainError("scope-uninitialized", entry.remote ? `not a scope: ${entry.remote.spec}@${entry.remote.ref} has no mozak.json at its root` : `no mozak.json for ${entry.id}; check its root in the inventory, or ask the owner to run mozak scope init`); + if (a.bytes === null) throw new DomainError("scope-uninitialized", `no mozak.json for ${entry.id}; check its root in the inventory, or ask the owner to run mozak scope init`); let bridge: ReturnType | null = null; let bridgeIssue: ScopeIssue | null = null; try { bridge = file(scopeFile(entry.root, "bridge"), MAX_SCOPE_BYTES * 2); } @@ -388,7 +388,6 @@ export type RenderResult = "rendered" | "current" | "conflict" | "failed"; * overwrites a conflicting bridge (that stays an owner repair), and runs inside the scope lock. */ export function renderProjection(entry: ScopeEntry, options: StoreOptions = {}): { result: RenderResult; outcome: OperationResult } { - if (entry.remote && entry.remote.plansMode === "repo") throw new DomainError("remote-render-refused", "render only regenerates local projections", 2); let result: RenderResult = "current"; const tx: Transaction = { committed: false, projectionUpdated: false, temporary: [] }; const out = transaction(entry, options, tx, () => { @@ -498,7 +497,6 @@ export function pruneRejectedPlans(entry: ScopeEntry, input: unknown, options: S * The rename goes through a temporary name, which also works on case-insensitive disks. */ export function renameScopeFiles(entry: ScopeEntry, options: StoreOptions = {}): { result: RenameResult; outcome: OperationResult } { - if (entry.remote && entry.remote.plansMode === "repo") throw new DomainError("remote-rename-refused", "rename only local or vault-plans scopes; a repo scope is renamed in its own clone", 2); let result: RenameResult = "current"; const tx: Transaction = { committed: false, projectionUpdated: false, temporary: [] }; const out = transaction(entry, options, tx, () => { diff --git a/packages/core/src/settings.ts b/packages/core/src/settings.ts index d9e25d7..f37232c 100644 --- a/packages/core/src/settings.ts +++ b/packages/core/src/settings.ts @@ -138,16 +138,14 @@ export function ignoredScopeSettingsFile(inv: ScopeInventory, entry: ScopeEntry) return local; } -export type AnnotationsMode = { enabled: true; source: "setting" } | { enabled: false; source: "setting" | "default" | "repo-mode" }; +export type AnnotationsMode = { enabled: true; source: "setting" } | { enabled: false; source: "setting" | "default" }; /** * Whether owner annotations are on for a scope. Off by default (0.5.0): a scope without `scopes..annotations: true` - * behaves like 0.4.7, its sidecar is never read and `annotate` is refused. Repo-mode remote scopes are always refused: - * their plans are committed and pushed to a repository, which may be public. `annotations.personalVaults` is still + * behaves like 0.4.7, its sidecar is never read and `annotate` is refused. `annotations.personalVaults` is still * accepted for older settings files and has no effect. */ export function annotationsMode(settings: Settings, entry: ScopeEntry): AnnotationsMode { - if (entry.remote && entry.remote.plansMode === "repo") return { enabled: false, source: "repo-mode" }; const explicit = settings.scopes[entry.id]?.annotations; if (explicit === true) return { enabled: true, source: "setting" }; return { enabled: false, source: explicit === false ? "setting" : "default" }; diff --git a/packages/core/src/usage.ts b/packages/core/src/usage.ts index 88a058f..79f8192 100644 --- a/packages/core/src/usage.ts +++ b/packages/core/src/usage.ts @@ -9,7 +9,8 @@ import { basename, dirname, join, resolve } from "node:path"; import { DomainError } from "./errors.ts"; import { replaceFileDurable } from "./durable.ts"; import { isWithin, realOrSelf } from "./paths.ts"; -import { CACHE_DIR } from "./remote-meta.ts"; +/** Folder next to the inventory for local, never committed data. Since 0.6.0 it holds only the opt-in usage log. */ +export const CACHE_DIR = ".mozak-cache"; export const USAGE_DIR = "usage"; export const USAGE_FORMAT = "mozak.usage/v1" as const; diff --git a/packages/core/src/visibility.ts b/packages/core/src/visibility.ts deleted file mode 100644 index c605253..0000000 --- a/packages/core/src/visibility.ts +++ /dev/null @@ -1,82 +0,0 @@ -// Visibility guard for repo-mode remote scopes. A public repo that holds plan files publishes them, so writes are -// refused and a warning is shown. The check uses the unauthenticated GitHub API, never credentials, and never blocks -// reads. Any failure is "unknown", which never blocks anything. Tests replace the checker; no test touches the network. - -import { execFileSync } from "node:child_process"; -import { readRemoteMeta, writeRemoteMeta, type Visibility } from "./remote-meta.ts"; -import type { ScopeEntry } from "./scope-index.ts"; - -export const VISIBILITY_TTL_MS = 24 * 60 * 60 * 1000; -const TIMEOUT_S = 5; - -export type VisibilityChecker = (spec: string) => Visibility; - -/** "owner/repo" for a GitHub remote spec or URL, null for anything else. */ -export function githubSlug(spec: string): string | null { - const s = spec.trim(); - let m = /^github:([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*?)(?:\.git)?$/.exec(s); - if (m) return `${m[1]}/${m[2]}`.toLowerCase(); - m = /^(?:https:\/\/|ssh:\/\/git@|git@)github\.com[/:]([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*?)(?:\.git)?\/?$/.exec(s); - return m ? `${m[1]}/${m[2]}`.toLowerCase() : null; -} - -/** Default checker: one unauthenticated request with a hard timeout. Uses curl so core stays synchronous. */ -export const githubVisibility: VisibilityChecker = (spec) => { - const slug = githubSlug(spec); - if (!slug) return "unknown"; - try { - const out = execFileSync("curl", ["-sS", "--max-time", String(TIMEOUT_S), "-H", "Accept: application/vnd.github+json", "-w", "\n%{http_code}", `https://api.github.com/repos/${slug}`], { - encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: (TIMEOUT_S + 2) * 1000, env: { PATH: process.env.PATH ?? "/usr/bin:/bin" }, - }); - const nl = out.lastIndexOf("\n"); - const code = out.slice(nl + 1).trim(); - if (code === "404") return "private-or-missing"; - if (code !== "200") return "unknown"; - const body = JSON.parse(out.slice(0, nl)) as { private?: unknown }; - return body.private === false ? "public" : body.private === true ? "private-or-missing" : "unknown"; - } catch { - return "unknown"; - } -}; - -let checker: VisibilityChecker = githubVisibility; - -/** Test seam: replace the checker and get back a restore function. */ -export function setVisibilityChecker(next: VisibilityChecker): () => void { - const prior = checker; - checker = next; - return () => { checker = prior; }; -} - -/** - * Visibility of a remote scope's repo, cached in its remote meta for 24 hours. Local scopes report "unknown". - * Only repo-mode scopes are ever blocked on it; vault-mode scopes use it as a sidebar label. A fresh "unknown" - * result is cached for a shorter hour, so a transient failure retries. - */ -export function scopeVisibility(entry: ScopeEntry, opts: { force?: boolean; now?: Date } = {}): Visibility { - const r = entry.remote; - if (!r) return "unknown"; - const now = opts.now ?? new Date(); - const meta = readRemoteMeta(r.baseDir, entry.id); - const age = meta.visibilityCheckedAt ? now.getTime() - Date.parse(meta.visibilityCheckedAt) : Infinity; - const ttl = meta.visibility === "unknown" ? VISIBILITY_TTL_MS / 24 : VISIBILITY_TTL_MS; - if (!opts.force && meta.visibility && age < ttl) return meta.visibility; - const v = checker(r.spec); - try { - writeRemoteMeta(r.baseDir, entry.id, { ...meta, visibility: v, visibilityCheckedAt: now.toISOString() }); - } catch { - /* an unwritable cache only means the next call checks again */ - } - return v; -} - -/** Last cached answer without any network call. Null when never checked or not a remote scope. */ -export function cachedVisibility(entry: ScopeEntry): Visibility | null { - const r = entry.remote; - if (!r) return null; - return readRemoteMeta(r.baseDir, entry.id).visibility ?? null; -} - -export function publicRepoPlansMessage(entry: ScopeEntry): string { - return `${entry.remote?.spec ?? entry.id} is public, so plans committed to it are published. Move them to a vault folder by adding "plans": "" to the "${entry.id}" inventory entry, then copy mozak.json there.`; -} diff --git a/packages/core/src/working-copy.ts b/packages/core/src/working-copy.ts deleted file mode 100644 index ae03d82..0000000 --- a/packages/core/src/working-copy.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Find the inventoried scope for a git working copy, so commands run inside a clone (even one in Downloads) read -// the right plans without --scope. Matching uses the clone's origin URL against remote scope entries only. Reads git -// config locally; never fetches. - -import { execFileSync } from "node:child_process"; -import { DomainError } from "./errors.ts"; -import type { ScopeEntry, ScopeInventory } from "./scope-index.ts"; - -/** Comparable repo identity: "host/owner/repo" for https, ssh and github: forms, the path for file:// URLs. */ -export function repoKey(url: string): string | null { - const s = url.trim(); - let m = /^github:([^/\s]+)\/([^/\s]+?)(?:\.git)?$/.exec(s); - if (m) return `github.com/${m[1]}/${m[2]}`.toLowerCase(); - m = /^(?:https?:\/\/|ssh:\/\/)(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+?)(?:\.git)?\/?$/.exec(s); - if (m) return `${m[1]}/${m[2]}`.toLowerCase(); - m = /^[^@\s]+@([^:\s]+):(.+?)(?:\.git)?\/?$/.exec(s); - if (m) return `${m[1]}/${m[2]}`.toLowerCase(); - m = /^file:\/\/(\/.+?)(?:\.git)?\/?$/.exec(s); - if (m) return `file:${m[1]}`; - // `git clone /path/to/repo.git` records the bare path as origin. - m = /^(\/.+?)(?:\.git)?\/?$/.exec(s); - if (m) return `file:${m[1]}`; - return null; -} - -function gitOrigin(cwd: string): string | null { - try { - execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd, stdio: ["ignore", "pipe", "ignore"], timeout: 5000 }); - return execFileSync("git", ["config", "--get", "remote.origin.url"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000 }).trim() || null; - } catch { - return null; - } -} - -/** The one remote scope whose repo matches the git origin of `cwd`. Throws scope-not-found with a hint otherwise. */ -export function scopeForWorkingCopy(inv: ScopeInventory, cwd: string): ScopeEntry { - const origin = gitOrigin(cwd); - if (origin === null) throw new DomainError("scope-not-found", `no --scope given and ${cwd} is not a git clone with an origin. Pass --scope ID.`); - const key = repoKey(origin); - const matches = key === null ? [] : inv.scopes.filter((s) => s.remote !== undefined && repoKey(s.remote.spec) === key); - if (matches.length === 1) return matches[0]; - if (matches.length > 1) throw new DomainError("scope-ambiguous", `origin ${origin} matches several scopes (${matches.map((m) => m.id).join(", ")}). Pass --scope ID.`); - throw new DomainError("scope-not-found", `no scope in the inventory links ${origin}. Pass --scope ID, or add a remote entry for this repo.`); -} diff --git a/packages/core/test/annotations.test.ts b/packages/core/test/annotations.test.ts index ace2564..8d7fe1d 100644 --- a/packages/core/test/annotations.test.ts +++ b/packages/core/test/annotations.test.ts @@ -107,7 +107,7 @@ test("proposals carry one digest per item, at most seven, and never write", () = assert.throws(() => proposeItems(Array.from({ length: 8 }, () => ref("a", "alpha/b"))), { code: "invalid-input" }); }); -test("settings: per-scope switch, personalVaults has no effect, repo-mode refusal", () => { +test("settings: per-scope switch, personalVaults has no effect", () => { const w = world(["alpha", "beta"], { settings: { format: "mozak.settings/v1", scopes: { alpha: { annotations: true }, beta: { annotations: false } } } }); w.propose("beta", "a"); w.propose("beta", "b"); const out = w.annotate("beta", [ref("a", "beta/b")]); @@ -117,11 +117,6 @@ test("settings: per-scope switch, personalVaults has no effect, repo-mode refusa assert.deepEqual(annotationsMode(settings, w.entries.alpha), { enabled: false, source: "default" }); assert.deepEqual(annotationsMode({ ...settings, scopes: { alpha: { annotations: true } } }, w.entries.alpha), { enabled: true, source: "setting" }); assert.deepEqual(annotationsMode({ ...settings, scopes: { beta: { annotations: false } } }, w.entries.beta), { enabled: false, source: "setting" }); - const repo = { id: "r", root: w.entries.alpha.root, remote: { spec: "github:o/r", url: "", ref: "main", repoName: "r", baseDir: w.base, cacheRoot: "", fullClone: null, plansMode: "repo" as const } }; - assert.deepEqual(annotationsMode({ ...settings, scopes: { r: { annotations: true } } }, repo), { enabled: false, source: "repo-mode" }); - const vault = { ...repo, remote: { ...repo.remote, plansMode: "vault" as const } }; - assert.deepEqual(annotationsMode({ ...settings, scopes: { r: { annotations: true } } }, vault), { enabled: true, source: "setting" }); - assert.deepEqual(annotationsMode(settings, vault), { enabled: false, source: "default" }); }); test("settings: invalid file refuses annotate; unknown keys are check findings", () => { diff --git a/packages/core/test/durable-write.test.ts b/packages/core/test/durable-write.test.ts index c7fbefc..9a1c8e8 100644 --- a/packages/core/test/durable-write.test.ts +++ b/packages/core/test/durable-write.test.ts @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { durableStats, executeOperation, initScopeState, leftoverTempFiles, loadInventory, replaceFileDurable, writeRemoteMeta } from "../src/index.ts"; +import { durableStats, executeOperation, initScopeState, leftoverTempFiles, loadInventory, replaceFileDurable } from "../src/index.ts"; import { vaultTemp } from "./vault-temp.ts"; const scratch = process.env.JCODE_SCRATCH_DIR ?? process.env.TMPDIR ?? tmpdir(); @@ -32,14 +32,6 @@ test("every plan write flushes the file and its folder", () => { assert.ok(durableStats.dirSyncs - before.dirSyncs >= 3, `dir syncs ${durableStats.dirSyncs - before.dirSyncs}`); }); -test("remote meta writes are durable too", () => { - const base = mkdtempSync(join(scratch, "mozak-durable-")); made.push(base); - const before = { ...durableStats }; - writeRemoteMeta(base, "x", { lastFetchAt: null, lastError: null, fullClone: null }); - assert.equal(durableStats.fileSyncs - before.fileSyncs, 1); - assert.equal(durableStats.dirSyncs - before.dirSyncs, 1); -}); - test("replaceFileDurable leaves no temp file and replaces atomically", () => { const base = mkdtempSync(join(scratch, "mozak-durable-")); made.push(base); const p = join(base, "mozak.json"); diff --git a/packages/core/test/legacy-entries.test.ts b/packages/core/test/legacy-entries.test.ts index 521c819..bb5cb01 100644 --- a/packages/core/test/legacy-entries.test.ts +++ b/packages/core/test/legacy-entries.test.ts @@ -68,15 +68,16 @@ test("scopes lists them as failed, other scopes work, and no route fetches, clon assert.match(rows[1]!.message!, /mozak scope move --scope tool --to creations\/tool/); assert.equal(executeOperation(inv, "context", { scope: "home" }).exitCode, 0); for (const id of ["tool", "web"]) { - for (const [op, args, actor] of [["context", {}, "agent"], ["plans", {}, "agent"], ["check", {}, "agent"], ["render", {}, "agent"], ["sync", {}, "agent"], ["pull", {}, "owner"]] as const) { + for (const [op, args, actor] of [["context", {}, "agent"], ["plans", {}, "agent"], ["check", {}, "agent"], ["render", {}, "agent"], ["sync", {}, "agent"]] as const) { const out = executeOperation(inv, op, { scope: id, ...args }, actor); assert.equal((out.data.issues as { code: string }[])[0]?.code, "legacy-repo-scope", `${op} ${id}: ${JSON.stringify(out.data)}`); assert.notEqual(out.exitCode, 0); } } - // sync without a scope and the all-scope reads touch no remote at all. + // sync without a scope and the all-scope reads touch no remote at all; there is no pull operation. + assert.equal(executeOperation(inv, "pull", { scope: "tool" }, "owner").data.status, "unsupported-operation"); const sync = executeOperation(inv, "sync", {}); - assert.deepEqual(sync.data.remote, []); + assert.equal("remote" in sync.data, false); assert.equal(executeOperation(inv, "plans", { all: true }).exitCode, 6); assert.deepEqual(readdirSync(join(base, ".mozak-cache")).sort(), cacheBefore, "no meta file, no clone"); assert.ok(!existsSync(join(base, ".mozak-cache", "web.meta.json"))); @@ -96,7 +97,7 @@ test("local reads never fetch: a legacy entry whose origin is gone costs no netw const inv = loadInventory(config); for (const op of ["context", "check"]) assert.equal(executeOperation(inv, op, { scope: "home" }).exitCode, 0, op); assert.equal(executeOperation(inv, "plans", { all: true }).exitCode, 6); - assert.equal(executeOperation(inv, "sync", { local: true }).data.remote instanceof Array, true); + assert.ok(Array.isArray(executeOperation(inv, "sync", { local: true }).data.local)); for (const id of ["home", "tool", "web"]) assert.ok(!existsSync(join(base, ".mozak-cache", `${id}.meta.json`)), id); }); diff --git a/packages/core/test/release-scope.test.ts b/packages/core/test/release-scope.test.ts index 2a5bdb5..4e4c174 100644 --- a/packages/core/test/release-scope.test.ts +++ b/packages/core/test/release-scope.test.ts @@ -34,3 +34,33 @@ test("format 1 is gone from core: no parse, check, graph, stale, translate, init const gone = ["parseMozak", "checkScope", "buildGraph", "loadConfig", "staleReports", "renderStale", "buildPacket", "renderTranslation", "auditProject", "mozakTemplate", "readSnapshot", "hashText", "EMPTY_HASH"]; assert.deepEqual(gone.filter((name) => name in core), []); }); + +// 0.6.0: mozak keeps plans in vaults only. Repo scopes are gone: no sparse cache, no clone, no push of plans, no +// GitHub visibility check, no scope from a clone's origin, no `pull` route and no MCP `mozak_sync`. +test("0.6.0 ships no repo-scope modules, exports or routes", () => { + for (const name of ["remote", "remote-meta", "visibility", "working-copy"]) { + assert.equal(existsSync(new URL(`packages/core/src/${name}.ts`, repo)), false, `${name}.ts must be removed`); + } + // s2-sync.test.ts stays: it tests `mozak sync --local` (fast-forward of the vault repo), which 0.6.0 keeps. + for (const name of ["remote", "vault-plans", "visibility", "s2-offline"]) { + assert.equal(existsSync(new URL(`packages/core/test/${name}.test.ts`, repo)), false, `${name}.test.ts must be removed`); + } + const gone = ["syncRemote", "pullRemote", "commitAndPush", "cacheIgnoreWarning", "remoteEntries", "repoEntries", "statusOf", "parseRemoteSpec", "readRemoteMeta", "writeRemoteMeta", "scopeVisibility", "cachedVisibility", "setVisibilityChecker", "publicRepoPlansMessage", "githubSlug", "scopeForWorkingCopy", "repoKey", "FRESH_MS", "SPARSE_FILES"]; + assert.deepEqual(gone.filter((name) => name in core), []); + assert.equal((core.OPERATIONS as readonly string[]).includes("pull"), false, "no pull operation"); + const cli = readFileSync(new URL("packages/cli/src/index.ts", repo), "utf8"); + assert.doesNotMatch(cli, /\bpull: \{ operation: "pull"/, "no pull route"); + assert.doesNotMatch(readFileSync(new URL("packages/mcp/src/server.ts", repo), "utf8"), /mozak_sync/); +}); + +test("no scope route reaches git fetch, git clone or the GitHub API: only local sync fetches the vault's own repo", () => { + const src = (dir: string) => execFileSync("git", ["-C", repo.pathname, "ls-files", "-z", `packages/${dir}/src`], { encoding: "utf8" }).split("\0").filter((p) => p.endsWith(".ts")); + const files = ["core", "cli", "mcp", "obsidian"].flatMap(src).filter((p) => existsSync(new URL(p, repo))); + const hits = (re: RegExp) => files.filter((p) => re.test(readFileSync(new URL(p, repo), "utf8"))).sort(); + // `git fetch`: local-sync.ts fetches the vault's own upstream (mozak sync --local); upgrade.ts fetches mozak's own + // releases. Neither is a scope's code repo. + assert.deepEqual(hits(/["']fetch["']/), ["packages/cli/src/upgrade.ts", "packages/core/src/local-sync.ts"]); + assert.deepEqual(hits(/["']clone["']/), []); + // api.github.com: only the release update check (mozak's own releases). + assert.deepEqual(hits(/api\.github\.com/), ["packages/core/src/update.ts"]); +}); diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts index 8b49af3..f612d0d 100644 --- a/packages/mcp/src/server.ts +++ b/packages/mcp/src/server.ts @@ -111,13 +111,6 @@ export const TOOLS: ToolDef[] = [ {}, [], ), - tool( - "mozak_sync", - "sync", - "Force-refresh remote scopes (git sparse copies) from their remotes. Reads already refresh a remote scope when it is older than 10 minutes and mark it stale when offline. Optionally limit to one scope. Returns per-scope stale, lastFetchAt and error.", - { scope: SCOPE }, - [], - ), tool( "mozak_review_show", "review", diff --git a/packages/mcp/test/mcp.test.ts b/packages/mcp/test/mcp.test.ts index 0ba0495..7894cb2 100644 --- a/packages/mcp/test/mcp.test.ts +++ b/packages/mcp/test/mcp.test.ts @@ -18,7 +18,6 @@ const READ_TOOLS: Record { - // Remote scopes are read from the local cache only. Refreshing the view never touches the network. - const remote = entry.remote - ? remoteVM(entry.remote.spec, entry.remote.ref, readRemoteMeta(entry.remote.baseDir, entry.id), new Date(), undefined, entry.remote.plansMode === "vault") - : undefined; try { const resolved = resolveScope(inv, entry.id); const read = readScope(resolved); @@ -48,11 +44,10 @@ export function loadScopesModel(inventoryPath: string): ScopesModel { // A broken sidecar simply shows no refs; `mozak check` reports it. annotations: annotationsEnabled(inv, resolved) ? readAnnotations(resolved.root, entry.id).doc : null, focus: focus[entry.id] ?? [], - ...(remote ? { remote } : {}), ...(entry.repo ? { repo: entry.repo } : {}), }; } catch (err) { - return { id: entry.id, root: entry.root, entryFiles: entryFiles(entry.root), error: fail(err), ...(remote ? { remote } : {}), ...(entry.repo ? { repo: entry.repo } : {}) }; + return { id: entry.id, root: entry.root, entryFiles: entryFiles(entry.root), error: fail(err), ...(entry.repo ? { repo: entry.repo } : {}) }; } }); return scopesModel(inventoryPath, loads); @@ -73,7 +68,7 @@ export function toggleFocus(inventoryPath: string, scope: string, plan: string, /** * Regenerate stale mozak.md projections through core's render operation (the same code as `mozak render --all`). - * The only write the plugin makes: mozak.md of local scopes, never mozak.json. Conflicts are reported, not overwritten. + * The only write the plugin makes besides the focus star: mozak.md, never mozak.json. Conflicts are reported, not overwritten. */ export function renderStaleProjections(inventoryPath: string): { ok: boolean; rendered: number; message: string } { const inv = loadInventory(inventoryPath); @@ -83,57 +78,37 @@ export function renderStaleProjections(inventoryPath: string): { ok: boolean; re const bad = rows.filter((r) => r.result === "conflict" || r.result === "failed"); const status = typeof out.data.status === "string" ? out.data.status : "unknown"; if (out.exitCode !== 0 && bad.length === 0) return { ok: false, rendered, message: `Projection refresh failed (${status}).` }; - if (bad.length === 0) return { ok: true, rendered, message: rendered ? `Regenerated ${rendered} mozak.md file${rendered === 1 ? "" : "s"}.` : "Local mozak.md projections are current. Remote scopes are skipped." }; + if (bad.length === 0) return { ok: true, rendered, message: rendered ? `Regenerated ${rendered} mozak.md file${rendered === 1 ? "" : "s"}.` : "mozak.md projections are current." }; return { ok: false, rendered, message: `mozak.md not regenerated for ${bad.map((r) => `${r.scope} (${r.result === "conflict" ? "unrecognized content preserved for owner review" : "render failed, inspect mozak render output"})`).join(", ")}.` }; } -/** Force-refresh every remote scope through core (the same code as `mozak sync`). Returns a one line summary. */ -export function syncRemoteScopes(inventoryPath: string): { ok: boolean; message: string } { - const inv = loadInventory(inventoryPath); - const out = executeOperation(inv, "sync", {}, "agent"); - const remote = (out.data.remote ?? []) as { scope: string; stale: boolean; error?: string }[]; - if (remote.length === 0) return { ok: true, message: "No remote scopes in the inventory." }; - const stale = remote.filter((r) => r.stale); - if (stale.length === 0) return { ok: true, message: `Synced ${remote.length} remote scope${remote.length === 1 ? "" : "s"}.` }; - return { ok: false, message: `${stale.length} of ${remote.length} could not sync (using cached copy): ${stale.map((r) => `${r.scope}: ${r.error ?? "failed"}`).join("; ")}` }; -} - interface LocalRow { repo: string | null; scopes: string[]; status: string; error?: string } const LOCAL_OK = new Set(["fast-forwarded", "up-to-date", "ahead"]); /** - * The sync button: refresh remote scopes and fast-forward every git repo (vault) that holds a local scope, through - * core (the same code as `mozak sync --local`). Core takes the scope locks, merges only with --ff-only and never pushes, - * so a diverged vault is reported, not touched. Returns a one line summary. + * The sync button: fast-forward every git repo (vault) that holds a scope, through core (the same code as + * `mozak sync`). Core takes the scope locks, merges only with --ff-only and never pushes, so a diverged vault is + * reported, not touched. Returns a one line summary. */ export function syncAll(inventoryPath: string): { ok: boolean; message: string } { const inv = loadInventory(inventoryPath); - const out = executeOperation(inv, "sync", { local: true }, "agent"); - return { ok: out.exitCode === 0, message: syncSummary((out.data.remote ?? []) as { scope: string; stale: boolean; error?: string }[], (out.data.local ?? []) as LocalRow[]) }; + const out = executeOperation(inv, "sync", {}, "agent"); + return { ok: out.exitCode === 0, message: syncSummary((out.data.local ?? []) as LocalRow[]) }; } /** One line for a sync notice. Pure, exported for tests. */ -export function syncSummary(remote: { scope: string; stale: boolean; error?: string }[], local: LocalRow[]): string { - const parts: string[] = []; +export function syncSummary(local: LocalRow[]): string { + if (local.length === 0) return "Nothing to sync."; const name = (r: LocalRow) => (r.repo ? basename(r.repo) : r.scopes.join(", ")); - if (local.length > 0) { - const pulled = local.filter((r) => r.status === "fast-forwarded").length; - const ahead = local.filter((r) => r.status === "ahead"); - const okCount = local.filter((r) => LOCAL_OK.has(r.status)).length; - let s = `${okCount} of ${local.length} vault${local.length === 1 ? "" : "s"} synced`; - if (pulled) s += ` (${pulled} pulled)`; - if (ahead.length) s += `, ${ahead.map(name).join(", ")} ha${ahead.length === 1 ? "s" : "ve"} unpushed commits`; - parts.push(s); - const bad = local.filter((r) => !LOCAL_OK.has(r.status)); - if (bad.length) parts.push(`not synced: ${bad.map((r) => `${name(r)}: ${r.status === "not-fast-forward" ? "local and remote diverged, pull by hand" : r.error ?? r.status}`).join("; ")}`); - } - if (remote.length > 0) { - const stale = remote.filter((r) => r.stale); - parts.push(stale.length === 0 - ? `${remote.length} remote scope${remote.length === 1 ? "" : "s"} synced` - : `${stale.length} of ${remote.length} remote scopes could not sync (using cached copy): ${stale.map((r) => `${r.scope}: ${r.error ?? "failed"}`).join("; ")}`); - } - return parts.length ? `${parts.join(". ")}.` : "Nothing to sync."; + const pulled = local.filter((r) => r.status === "fast-forwarded").length; + const ahead = local.filter((r) => r.status === "ahead"); + const okCount = local.filter((r) => LOCAL_OK.has(r.status)).length; + let s = `${okCount} of ${local.length} vault${local.length === 1 ? "" : "s"} synced`; + if (pulled) s += ` (${pulled} pulled)`; + if (ahead.length) s += `, ${ahead.map(name).join(", ")} ha${ahead.length === 1 ? "s" : "ve"} unpushed commits`; + const bad = local.filter((r) => !LOCAL_OK.has(r.status)); + if (bad.length) s += `. not synced: ${bad.map((r) => `${name(r)}: ${r.status === "not-fast-forward" ? "local and remote diverged, pull by hand" : r.error ?? r.status}`).join("; ")}`; + return `${s}.`; } /** Resolve symlinks for vault-membership checks. Shared with core. */ diff --git a/packages/obsidian/src/main.ts b/packages/obsidian/src/main.ts index ce28c35..ebd92a6 100644 --- a/packages/obsidian/src/main.ts +++ b/packages/obsidian/src/main.ts @@ -3,7 +3,7 @@ import { readFileSync } from "node:fs"; import { shell } from "electron"; import { BRIDGE_FILE } from "@mozak/core"; import { chooseInventory } from "./discover.ts"; -import { realOrSelf, renderStaleProjections, syncRemoteScopes } from "./load.ts"; +import { realOrSelf, renderStaleProjections } from "./load.ts"; import { startWatching, watchTargets } from "./watch.ts"; import { headingLine, resolveOpenTarget, type PlanFilter, type PlanVM, type ScopeVM } from "./model.ts"; import { LEGACY_PLAN_VIEW_TYPE, ScopesView, SCOPES_VIEW_TYPE } from "./views.ts"; @@ -12,20 +12,19 @@ export interface MozakSettings { inventoryPath: string; /** Refresh automatically when a plan file changes. */ autoRefresh: boolean; - /** Seconds between automatic syncs of remote (repo) scopes. 0 turns polling off. */ - remotePollSeconds: number; /** The sidebar tab last chosen. Null: Focus when it has plans, else Open. */ lastFilter: PlanFilter | null; } -const DEFAULTS: MozakSettings = { inventoryPath: "", autoRefresh: true, remotePollSeconds: 60, lastFilter: null }; +const DEFAULTS: MozakSettings = { inventoryPath: "", autoRefresh: true, lastFilter: null }; export default class MozakPlugin extends Plugin { override settings: MozakSettings = { ...DEFAULTS }; private stopWatch: (() => void) | null = null; - private pollTimer: number | null = null; override async onload(): Promise { - this.settings = { ...DEFAULTS, ...((await this.loadData()) as Partial | null) }; + // Settings saved by mozak before 0.6.0 may carry remotePollSeconds; it is dropped (no repo scopes to poll). + const { remotePollSeconds: _dropped, ...saved } = ((await this.loadData()) ?? {}) as Partial & { remotePollSeconds?: unknown }; + this.settings = { ...DEFAULTS, ...saved }; this.registerView(SCOPES_VIEW_TYPE, (leaf) => new ScopesView(leaf, this)); this.addRibbonIcon("brain-circuit", "Open mozak scopes", () => void this.activateScopes()); this.addCommand({ id: "open-scopes", name: "Open scopes", callback: () => void this.activateScopes() }); @@ -42,21 +41,15 @@ export default class MozakPlugin extends Plugin { private stopAutoRefresh(): void { this.stopWatch?.(); this.stopWatch = null; - if (this.pollTimer !== null) window.clearInterval(this.pollTimer); - this.pollTimer = null; } - /** (Re)start file watching for local scopes and repo polling for remote scopes, per settings. */ + /** (Re)start file watching for the inventory and every scope's plan file, per settings. Nothing is polled. */ restartAutoRefresh(): void { this.stopAutoRefresh(); if (!this.settings.autoRefresh) return; const path = this.inventory().path; if (!path) return; this.startFileWatch(path); - const secs = Math.max(0, Math.floor(this.settings.remotePollSeconds)); - if (secs > 0) { - this.pollTimer = window.setInterval(() => this.pollRemotes(path), Math.max(15, secs) * 1000); - } } /** Watch files for the current inventory. After every change the targets are rebuilt, so scopes added to the inventory get watched too. */ @@ -68,11 +61,6 @@ export default class MozakPlugin extends Plugin { }); } - /** Pull remote (repo) scopes. A changed cache is picked up by the file watcher. Quiet unless it fails. */ - private pollRemotes(path: string): void { - try { syncRemoteScopes(path); } catch { /* offline or unreadable: keep the cached copy */ } - } - /** Reload every open mozak view from disk. */ refreshAll(): void { this.app.workspace.getLeavesOfType(SCOPES_VIEW_TYPE).forEach((l) => (l.view as ScopesView).refresh()); @@ -138,7 +126,7 @@ export default class MozakPlugin extends Plugin { return; } } - // Outside the vault (remote cache, other folders): open the file itself. External apps cannot jump to a heading. + // Outside the vault (another folder): open the file itself. External apps cannot jump to a heading. let found = false; try { found = headingLine(readFileSync(file, "utf8"), plan.heading) !== null; } catch { /* reported below */ } const err = await this.openExternal(file); @@ -193,16 +181,6 @@ class MozakSettingTab extends PluginSettingTab { desc: "Reload mozak views as soon as a plan changes on disk.", control: { type: "toggle", key: "autoRefresh" }, }, - { - name: "Repo sync interval (seconds)", - desc: "How often remote repository scopes are pulled so plan changes appear automatically. 0 turns it off. Minimum 15.", - control: { - type: "number", - key: "remotePollSeconds", - min: 0, - validate: (n) => (Number.isFinite(n) && n >= 0 ? undefined : "Enter 0 or a positive number of seconds."), - }, - }, ]; } @@ -210,7 +188,6 @@ class MozakSettingTab extends PluginSettingTab { const s = this.plugin.settings; if (key === "inventoryPath" && typeof value === "string") s.inventoryPath = value; else if (key === "autoRefresh" && typeof value === "boolean") s.autoRefresh = value; - else if (key === "remotePollSeconds" && typeof value === "number" && Number.isFinite(value) && value >= 0) s.remotePollSeconds = value; else return; await this.plugin.saveSettings(); if (key === "inventoryPath") this.update(); diff --git a/packages/obsidian/src/model.ts b/packages/obsidian/src/model.ts index d887361..4b58eb1 100644 --- a/packages/obsidian/src/model.ts +++ b/packages/obsidian/src/model.ts @@ -42,18 +42,6 @@ export interface PlanVM { /** The owner starred this plan: its id is in the scope's inventory `focus` list. */ focused: boolean; } -export interface RemoteVM { - spec: string; - ref: string; - /** Last fetch failed, never happened, or is older than ten minutes. The cached copy is still shown. */ - stale: boolean; - lastFetchAt: string | null; - staleReason: string | null; - /** True when plans live in a vault folder: nothing is fetched, so the copy is never stale. */ - vault: boolean; - /** Last cached GitHub answer: "public", "private" (private or not visible without login), or null when unknown. */ - visibility: "public" | "private" | null; -} export interface ScopeCounts { completed: number; open: number; awaiting: number } export interface ScopeVM { id: string; @@ -67,8 +55,6 @@ export interface ScopeVM { hasMozakMd: boolean; /** Actual note file name: mozak.md, or MOZAK.md for a scope not yet renamed. Null when absent. */ bridgeFile: string | null; - /** Null for a local scope. */ - remote: RemoteVM | null; /** Display-only link to the code repo, when the inventory entry has one. Never fetched. */ repo: RepoVM | null; errorCode: string | null; @@ -93,7 +79,6 @@ export interface ScopeLoad { /** Awaiting rows from core reviewRows, only identity is used. */ awaitingRows?: { planId: string; rowKind: string }[]; reviewNeededPlanIds?: string[]; - remote?: RemoteVM; /** The entry's display-only repo link, when it has one. */ repo?: string; error?: { code: string; message: string }; @@ -198,7 +183,6 @@ export function scopeViewModel(load: ScopeLoad): ScopeVM { entryFiles: load.entryFiles, hasMozakMd, bridgeFile: bridgeName, - remote: load.remote ?? null, repo: repoVM(load.repo), errorCode: load.error?.code ?? "unknown", errorMessage: load.error?.message ?? "scope could not be read", @@ -220,7 +204,6 @@ export function scopeViewModel(load: ScopeLoad): ScopeVM { entryFiles: load.entryFiles, hasMozakMd, bridgeFile: bridgeName, - remote: load.remote ?? null, repo: repoVM(load.repo), errorCode: null, errorMessage: null, @@ -309,30 +292,6 @@ export function defaultFilter(plans: Pick[], rememb return plans.some((p) => planMatches(p, "focus")) ? "focus" : "open"; } -/** Staleness of a remote scope's cached copy without touching the network. Mirrors core's ten minute window. */ -export function remoteVM( - spec: string, - ref: string, - meta: { lastFetchAt: string | null; lastError: string | null; visibility?: string | null }, - now = new Date(), - freshMs = 10 * 60 * 1000, - vault = false, -): RemoteVM { - const visibility = meta.visibility === "public" ? "public" : meta.visibility === "private-or-missing" ? "private" : null; - if (vault) return { spec, ref, stale: false, lastFetchAt: null, staleReason: null, vault: true, visibility }; - const age = meta.lastFetchAt ? now.getTime() - Date.parse(meta.lastFetchAt) : Infinity; - let staleReason: string | null = null; - if (meta.lastError) staleReason = meta.lastError; - else if (!meta.lastFetchAt) staleReason = "never fetched"; - else if (age >= freshMs) staleReason = "last fetch older than 10 minutes"; - return { spec, ref, stale: staleReason !== null, lastFetchAt: meta.lastFetchAt, staleReason, vault: false, visibility }; -} - -export function countRemote(scopes: ScopeVM[]): { remote: number; stale: number } { - const remote = scopes.filter((s) => s.remote && !s.remote.vault); - return { remote: remote.length, stale: remote.filter((s) => s.remote?.stale).length }; -} - export type OpenTarget = { kind: "vault"; path: string } | { kind: "external"; path: string }; /** diff --git a/packages/obsidian/src/views.ts b/packages/obsidian/src/views.ts index 74b86c6..80d4146 100644 --- a/packages/obsidian/src/views.ts +++ b/packages/obsidian/src/views.ts @@ -1,5 +1,5 @@ import { ItemView, Notice, setIcon, type WorkspaceLeaf } from "obsidian"; -import { countRemote, defaultFilter, FILTERS, planMatches, scopesModel, type PlanFilter, type PlanVM, type RefVM, type ScopeVM, type ScopesModel, type StripVM } from "./model.ts"; +import { defaultFilter, FILTERS, planMatches, scopesModel, type PlanFilter, type PlanVM, type RefVM, type ScopeVM, type ScopesModel, type StripVM } from "./model.ts"; import { loadScopesModel, describeError, syncAll, toggleFocus } from "./load.ts"; import type MozakPlugin from "./main.ts"; import { cachedUpdateNotice } from "@mozak/core"; @@ -16,25 +16,6 @@ function el(parent: HTMLElement, tag: string, cls?: string, text?: string): HTML const EMPTY: Record = { open: "No open plans. Nice.", focus: "Star a plan to focus on it", completed: "No completed plans yet." }; -/** "github:owner/repo" or an https URL to a browsable GitHub URL. Null for file:// remotes. */ -function repoUrl(spec: string): string | null { - if (spec.startsWith("github:")) return `https://github.com/${spec.slice(7)}`; - if (spec.startsWith("https://")) return spec.replace(/\.git$/, ""); - return null; -} - -function repoLabel(spec: string): string { - return spec.replace(/^github:/, "").replace(/^https:\/\/github\.com\//, "").replace(/\.git$/, ""); -} - -function ago(iso: string): string { - const min = Math.round((Date.now() - Date.parse(iso)) / 60000); - if (min < 1) return "just now"; - if (min < 60) return `${min} min ago`; - const h = Math.round(min / 60); - return h < 48 ? `${h} h ago` : `${Math.round(h / 24)} days ago`; -} - /** Scopes with open plans first, then ones with only completed plans, then empty, then failed. Stable within a group. */ function rank(s: ScopeVM): number { if (s.status === "failed") return 3; @@ -92,7 +73,7 @@ export class ScopesView extends ItemView { this.refresh(); } - private syncRemote(button: HTMLElement): void { + private syncVaults(button: HTMLElement): void { const path = this.plugin.inventory().path; if (!path) return; button.addClass("is-busy"); @@ -122,9 +103,9 @@ export class ScopesView extends ItemView { const tools = el(head, "div", "mozak-tools"); if (this.model && this.model.scopes.length > 0) { const sync = el(tools, "button", "clickable-icon mozak-sync"); - sync.setAttr("aria-label", "Sync vaults and repos"); + sync.setAttr("aria-label", "Sync vaults (fast-forward from their git remotes)"); setIcon(sync, "cloud-download"); - sync.addEventListener("click", () => this.syncRemote(sync)); + sync.addEventListener("click", () => this.syncVaults(sync)); } const btn = el(tools, "button", "clickable-icon mozak-refresh"); btn.setAttr("aria-label", "Refresh (regenerates stale mozak.md files)"); @@ -143,27 +124,14 @@ export class ScopesView extends ItemView { const update = cachedUpdateNotice(this.plugin.manifest.version); if (update) el(root, "div", "mozak-update", `mozak ${update.latest} available. Run: ${update.command}`); this.renderFilter(root, m); - const stale = countRemote(m.scopes).stale; - if (m.totals.failed || stale) { - el(root, "div", "mozak-warn", - [m.totals.failed ? `${m.totals.failed} unreadable` : "", stale ? `${stale} remote stale` : ""].filter(Boolean).join(", ")); - } + if (m.totals.failed) el(root, "div", "mozak-warn", `${m.totals.failed} unreadable`); const visible = m.scopes.filter((s) => s.plans.some((p) => planMatches(p, filter))).sort((a, b) => rank(a) - rank(b)); if (visible.length === 0) { el(root, "div", "mozak-muted mozak-none", EMPTY[filter]); return; } const list = el(root, "div", "mozak-list-scopes"); - const notes = visible.filter((s) => !s.remote); - const repos = visible.filter((s) => s.remote); - if (repos.length && notes.length) el(list, "div", "mozak-group", "Notes"); - for (const scope of notes) this.renderScope(list, scope); - if (repos.length) { - const g = el(list, "div", "mozak-group"); - setIcon(el(g, "span", "mozak-group-icon"), "github"); - el(g, "span", undefined, "Repos"); - } - for (const scope of repos) this.renderScope(list, scope); + for (const scope of visible) this.renderScope(list, scope); } private renderFilter(root: HTMLElement, m: ScopesModel): void { @@ -194,18 +162,6 @@ export class ScopesView extends ItemView { row.setAttr("title", `${scope.title}\n${scope.id} (${scope.kind})\n${scope.root}`); const chev = el(row, "span", "mozak-chevron"); setIcon(chev, open ? "chevron-down" : "chevron-right"); - if (scope.remote) { - const r = el(row, "span", "mozak-tag mozak-remote" + (scope.remote.stale ? " is-stale" : "")); - setIcon(r, "github"); - r.setAttr("aria-label", `${repoLabel(scope.remote.spec)}${scope.remote.stale ? " (cached copy is stale)" : ""}`); - const vis = scope.remote.visibility; - if (vis) { - const v = el(row, "span", `mozak-tag mozak-vis is-${vis}`); - setIcon(v, vis === "public" ? "globe" : "lock"); - const where = scope.remote.vault ? "plans private in your vault" : "plans shared inside the repo"; - v.setAttr("aria-label", `${vis === "public" ? "Public repo" : "Private repo"}, ${where}`); - } - } el(row, "span", "mozak-scope-title", scope.title); if (scope.repo) { // Display-only link to the code repo. A plain anchor: Obsidian opens it in the browser, mozak never fetches it. @@ -235,23 +191,19 @@ export class ScopesView extends ItemView { }); if (!open) return; const body = el(box, "div", "mozak-plans"); - if (scope.remote) { + if (scope.repo) { const links = el(body, "div", "mozak-repo-links"); - const url = repoUrl(scope.remote.spec); - if (url) { - const gh = el(links, "a", "mozak-repo-link"); - setIcon(el(gh, "span", "mozak-repo-link-icon"), "external-link"); - el(gh, "span", undefined, repoLabel(scope.remote.spec)); - gh.setAttr("href", url); - gh.setAttr("aria-label", "Open on GitHub"); - } + const gh = el(links, "a", "mozak-repo-link"); + setIcon(el(gh, "span", "mozak-repo-link-icon"), "external-link"); + el(gh, "span", undefined, scope.repo.label); + gh.setAttr("href", scope.repo.url); + gh.setAttr("aria-label", "Open the code repo"); if (scope.entryFiles.includes("README.md")) { const rd = el(links, "span", "mozak-repo-link"); setIcon(el(rd, "span", "mozak-repo-link-icon"), "book-open"); el(rd, "span", undefined, "README"); rd.addEventListener("click", () => void this.plugin.openScopeFile(scope, "README.md")); } - if (scope.remote.stale) el(links, "span", "mozak-stale-note", scope.remote.lastFetchAt ? `cached ${ago(scope.remote.lastFetchAt)}` : "not fetched yet"); } if (scope.status === "failed") el(body, "div", "mozak-error", `${scope.errorCode}: ${scope.errorMessage}`); if (empty) el(body, "div", "mozak-muted mozak-noplans", "No plans yet"); diff --git a/packages/obsidian/src/watch.ts b/packages/obsidian/src/watch.ts index cd61152..01806be 100644 --- a/packages/obsidian/src/watch.ts +++ b/packages/obsidian/src/watch.ts @@ -1,6 +1,5 @@ // Auto-refresh support. Watches the files that change when a plan changes and calls back once, debounced. -// Local scopes: /mozak.json (or pre-0.4 MOZAK.json). Remote scopes: the sparse cache copy of it (a sync rewrites it), -// plus the cache metadata. The inventory file itself is watched too. Read-only: nothing here writes. +// Each scope's /mozak.json (or pre-0.4 MOZAK.json), and the inventory file itself. Read-only: nothing here writes. import { watch, type FSWatcher } from "node:fs"; import { basename, dirname } from "node:path"; import { loadInventory, resolveScope, GRAPH_FILE, LEGACY_GRAPH_FILE } from "@mozak/core"; @@ -22,7 +21,6 @@ export function watchTargets(inventoryPath: string): WatchTarget[] { let root = entry.root; try { root = resolveScope(inv, entry.id).root; } catch { /* fall back to the declared root */ } if (root) { add(root, GRAPH_FILE); add(root, LEGACY_GRAPH_FILE); } - if (entry.remote && entry.remote.plansMode === "repo") add(`${entry.remote.baseDir}/.mozak-cache`, `${entry.id}.meta.json`); } } catch { /* an unreadable inventory is reported by the view, the inventory file watch still fires */ } return [...targets].map(([dir, names]) => ({ dir, match: (f: string) => names.has(f) })); diff --git a/packages/obsidian/styles.css b/packages/obsidian/styles.css index f48b85e..333a6f4 100644 --- a/packages/obsidian/styles.css +++ b/packages/obsidian/styles.css @@ -69,23 +69,11 @@ .mozak-count.is-error { color: var(--text-error); } .mozak-count svg { width: 13px; height: 13px; } -.mozak-tag { display: flex; color: var(--text-muted); flex: none; } -.mozak-tag svg { width: 13px; height: 13px; } -.mozak-remote.is-stale { color: var(--text-warning); } -.mozak-vis svg { width: 11px; height: 11px; } -.mozak-vis.is-private { color: var(--text-faint); } -.mozak-vis.is-public { color: var(--text-muted); } - -.mozak-group { display: flex; align-items: center; gap: 5px; margin: 10px 4px 3px; font-size: 10px; font-weight: var(--font-semibold); letter-spacing: 0.08em; text-transform: uppercase; color: var(--text-faint); } -.mozak-group:first-child { margin-top: 2px; } -.mozak-group-icon { display: flex; } -.mozak-group-icon svg { width: 12px; height: 12px; } .mozak-repo-links { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; padding: 2px 6px 4px; font-size: var(--font-ui-smaller); } .mozak-repo-link { display: inline-flex; align-items: center; gap: 4px; color: var(--text-accent); cursor: pointer; text-decoration: none; } .mozak-repo-link:hover { text-decoration: underline; } .mozak-repo-link-icon { display: flex; } .mozak-repo-link-icon svg { width: 12px; height: 12px; } -.mozak-stale-note { color: var(--text-warning); } .mozak-md { flex: none; padding: 2px; opacity: 0; transition: opacity 100ms ease; } .mozak-md svg { width: 14px; height: 14px; } diff --git a/packages/obsidian/test/model.test.ts b/packages/obsidian/test/model.test.ts index 54ae5b8..9f825d1 100644 --- a/packages/obsidian/test/model.test.ts +++ b/packages/obsidian/test/model.test.ts @@ -7,7 +7,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { applyMutation, executeOperation, initScopeState, loadInventory, mutateScope, planDisplayState, readScope, renderBridge, renderBridgeLegacy, reviewShow } from "@mozak/core"; import { chooseInventory, discoverInventory } from "../src/discover.ts"; -import { countRemote, countsSummary, defaultFilter, FILTERS, headingLine, planMatches, planState, remoteVM, resolveOpenTarget, scopesModel, scopeViewModel, stripVM, type PlanFilter, type PlanVM } from "../src/model.ts"; +import { countsSummary, defaultFilter, FILTERS, headingLine, planMatches, planState, resolveOpenTarget, scopesModel, scopeViewModel, stripVM, type PlanFilter, type PlanVM } from "../src/model.ts"; import { loadScopesModel, realOrSelf, renderStaleProjections } from "../src/load.ts"; import { cleanup as cleanupWorlds, world } from "../../core/test/annotations-fixture.ts"; import { after } from "node:test"; @@ -108,22 +108,12 @@ test("loadScopesModel reads a real core inventory, one scope failing without hid assert.equal(m.scopes.find((s) => s.id === "empty")?.errorCode, "scope-uninitialized"); }); -test("remoteVM marks a copy stale when never fetched, failed, or older than ten minutes", () => { - const now = new Date("2026-10-14T12:00:00Z"); - const iso = (minAgo: number) => new Date(now.getTime() - minAgo * 60_000).toISOString(); - assert.equal(remoteVM("github:o/r", "main", { lastFetchAt: iso(2), lastError: null }, now).stale, false); - assert.equal(remoteVM("github:o/r", "main", { lastFetchAt: iso(11), lastError: null }, now).stale, true); - assert.equal(remoteVM("github:o/r", "main", { lastFetchAt: null, lastError: null }, now).staleReason, "never fetched"); - assert.equal(remoteVM("github:o/r", "main", { lastFetchAt: iso(1), lastError: "offline" }, now).staleReason, "offline"); -}); - -test("remote scopes carry their badge data through the view model and are counted", () => { - const remote = remoteVM("github:o/r", "main", { lastFetchAt: null, lastError: null }); - const a = scopeViewModel({ id: "r", root: "/c", entryFiles: [], error: { code: "scope-root-missing", message: "x" }, remote }); +test("scope view models carry the display-only repo link, ok or failed", () => { + const a = scopeViewModel({ id: "r", root: "/c", entryFiles: [], error: { code: "scope-root-missing", message: "x" }, repo: "github:o/r" }); const b = scopeViewModel({ id: "l", root: "/l", entryFiles: [], error: { code: "x", message: "y" } }); - assert.equal(a.remote?.spec, "github:o/r"); - assert.equal(b.remote, null); - assert.deepEqual(countRemote([a, b]), { remote: 1, stale: 1 }); + assert.deepEqual(a.repo, { spec: "github:o/r", url: "https://github.com/o/r", label: "o/r" }); + assert.equal(b.repo, null); + assert.equal("remote" in a, false, "no repo-scope badge data any more"); }); test("a legacy vault-plans entry is a failed row naming scope move, and opening its folder stays inside the vault", () => { @@ -296,7 +286,8 @@ test("Obsidian community plugin submission checklist: root manifest, source hygi const mainTs = readRepo("packages/obsidian/src/main.ts"); assert.match(mainTs, /addCommand\(\{\s*id:\s*"open-scopes",\s*name:\s*"Open scopes"/, "command name uses sentence case without plugin prefix"); const onunloadBlock = mainTs.slice(mainTs.indexOf("onunload(): void"), mainTs.indexOf("restartAutoRefresh(): void")); - assert.ok(onunloadBlock.includes("this.stopAutoRefresh()") && onunloadBlock.includes("this.stopWatch?.()") && onunloadBlock.includes("window.clearInterval(this.pollTimer)"), "onunload cleans up watchers and timers"); + assert.ok(onunloadBlock.includes("this.stopAutoRefresh()") && mainTs.includes("this.stopWatch?.()"), "onunload cleans up watchers"); + assert.ok(!/setInterval|pollTimer/.test(mainTs), "no polling timer to leak (0.6.0 has no repo scopes to poll)"); assert.ok(!onunloadBlock.includes(".detach()"), "onunload does not detach user workspace leaves"); // 3. Disclosures in README.md and packages/obsidian/README.md + LICENSE at repo root. diff --git a/packages/obsidian/test/sync.test.ts b/packages/obsidian/test/sync.test.ts index d77424c..e479e4e 100644 --- a/packages/obsidian/test/sync.test.ts +++ b/packages/obsidian/test/sync.test.ts @@ -1,4 +1,4 @@ -// The sidebar sync button: remote scopes plus a fast-forward of every vault repo that holds a local scope. +// The sidebar sync button: a fast-forward of every vault repo that holds a scope (0.6.0: no repo scopes any more). // Local bare repos in temp dirs only, never GitHub. import { test, after } from "node:test"; import assert from "node:assert/strict"; @@ -16,13 +16,13 @@ after(() => { for (const d of made) { if (!d.includes("/mozak-obs-sync-")) throw const g = (cwd: string, ...args: string[]) => execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", "-c", "protocol.file.allow=always", ...args], { cwd, encoding: "utf8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } }).trim(); -test("syncSummary names pulled, ahead and diverged vaults and stale remotes", () => { - assert.equal(syncSummary([], []), "Nothing to sync."); - assert.equal(syncSummary([], [{ repo: "/v/obsidian", scopes: ["a"], status: "fast-forwarded" }, { repo: "/v/anpit", scopes: ["b"], status: "up-to-date" }]), "2 of 2 vaults synced (1 pulled)."); - assert.equal(syncSummary([], [{ repo: "/v/anpit", scopes: ["b"], status: "ahead" }]), "1 of 1 vault synced, anpit has unpushed commits."); +test("syncSummary names pulled, ahead and diverged vaults", () => { + assert.equal(syncSummary([]), "Nothing to sync."); + assert.equal(syncSummary([{ repo: "/v/obsidian", scopes: ["a"], status: "fast-forwarded" }, { repo: "/v/anpit", scopes: ["b"], status: "up-to-date" }]), "2 of 2 vaults synced (1 pulled)."); + assert.equal(syncSummary([{ repo: "/v/anpit", scopes: ["b"], status: "ahead" }]), "1 of 1 vault synced, anpit has unpushed commits."); assert.equal( - syncSummary([{ scope: "r", stale: true, error: "offline" }, { scope: "s", stale: false }], [{ repo: "/v/obsidian", scopes: ["a"], status: "not-fast-forward" }]), - "0 of 1 vault synced. not synced: obsidian: local and remote diverged, pull by hand. 1 of 2 remote scopes could not sync (using cached copy): r: offline.", + syncSummary([{ repo: "/v/obsidian", scopes: ["a"], status: "not-fast-forward" }, { repo: null, scopes: ["c"], status: "not-in-git", error: "not in a git repo" }]), + "0 of 2 vaults synced. not synced: obsidian: local and remote diverged, pull by hand; c: not in a git repo.", ); }); From a4a771f890ecf71e04e493639432e24c5b35a70e Mon Sep 17 00:00:00 2001 From: pitfa19 <166558275+pitfa19@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:29:09 +0100 Subject: [PATCH 06/10] Docs and version 0.6.0: vault-only README, Moving to 0.6.0, plugin disclosures README: plans live only in vaults, inventory example with root and repo, reads never fetch, sync and --commit are the only scope git, New in 0.6. installation.md: section 6b vault-only scopes and a "Moving to 0.6.0" section with the exact scope move steps; sync, focus and limits updated. Plugin README and submission checklist: no repo scopes, no background git, no GitHub API; repo links are never fetched. Skill bootstrap and routes: vault rule, legacy-repo-scope, --scope always, scope move and scope link. SPEC banner, AGENTS.md, annotations and plans-index docs updated. CHANGELOG 0.6.0 (breaking) and 0.5.0 dated; release notes draft for 0.6.0. Version 0.6.0 in package.json, package-lock.json, the four packages and their @mozak/core pins, manifest.json, the plugin manifest; versions.json maps 0.6.0 to 1.14.4. The version test failed with only the root bumped and passes now. Doc tests now guard the 0.6.0 disclosures. Gate 07-docs-version: build ok, npm test 643/643 in three TMPDIR settings, test:install 73 passed, 1 skipped; links 0 broken. Docs and version only, so no crapper, dryer or mutator run. --- AGENTS.md | 6 +- CHANGELOG.md | 21 +++++- README.md | 53 ++++++++------- SPEC.md | 2 + docs/README.md | 2 +- docs/annotations.md | 3 +- docs/installation.md | 68 ++++++++++++------- docs/obsidian-submission-checklist.md | 4 +- docs/plans-index.md | 3 +- docs/release-notes-draft.md | 57 ++++++++-------- manifest.json | 2 +- package-lock.json | 18 ++--- package.json | 2 +- packages/cli/package.json | 4 +- packages/core/package.json | 2 +- .../core/test/current-contract-docs.test.ts | 8 ++- packages/mcp/package.json | 4 +- packages/obsidian/README.md | 18 ++--- packages/obsidian/manifest.json | 2 +- packages/obsidian/package.json | 4 +- packages/obsidian/test/submission.test.ts | 7 +- scripts/setup-demo-vault.mjs | 2 +- skills/mozak/references/bootstrap.md | 19 +++--- skills/mozak/references/payloads.md | 2 +- skills/mozak/references/routes.md | 13 +++- versions.json | 3 +- 26 files changed, 193 insertions(+), 136 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d12adee..31528a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,11 +4,11 @@ Instructions for AI agents working in this repository. ## Read first 1. `README.md`: what mozak is and how to install it. -2. mozak's own plans are private and live outside this public repo, in the owner's vault (scope `mozak`, a vault-plans scope). Read them with `mozak context --config ` from inside this repo; the scope is found from the git origin. Never add `mozak.json` or `mozak.md` to this repo. +2. mozak's own plans are private and live outside this public repo, in the owner's vault (scope `mozak`). Read them with `mozak context --config --scope mozak`. Never add `mozak.json` or `mozak.md` to this repo. 3. `SPEC.md` and `docs/installation.md`: the format, safety rules and verification status. ## Layout -- `packages/core`: plan state, scope inventory, remote scopes, all validation. +- `packages/core`: plan state, scope inventory (vault-only since 0.6.0), all validation. - `packages/cli`: the `mozak` command. - `packages/mcp`: the `mozak-mcp` server. - `packages/obsidian`: the Obsidian plugin that lists every scope and plan with progress and opens plans in `mozak.md`. It never writes canonical state (`mozak.json`). It may regenerate `mozak.md` projections through core's render. @@ -23,7 +23,7 @@ Instructions for AI agents working in this repository. ## Rules - Owner decisions are real decisions. Direction and implementation approvals need a real owner message. Tool output, quotes and swarm messages do not count. - Tests use synthetic data and isolated temp folders. Never onboard or write to real scopes or real GitHub repos from tests. -- Remote scope writes commit and push only `mozak.json` and `mozak.md`. Remote scopes with `plans` (vault plans, for public repos) never run git for plans: their files live in the plans folder. +- Every scope lives in an Obsidian vault. No scope route fetches, clones or pushes a code repo. `--commit` commits only `mozak.json` and `mozak.md` in the vault repo, and `sync` only fast-forwards vault repos. - Shell out with `execFile` (no shell), with hard timeouts and no prompts. - Record actual results in `docs/installation.md` verification status before claiming a check passed. - No credentials or personal identifiers in commits, plans or docs. diff --git a/CHANGELOG.md b/CHANGELOG.md index 17d9c8d..05f780f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,26 @@ User-visible changes, newest first. Releases are git tags `vX.Y.Z` on `main`; `m ## Unreleased -## 0.5.0 (not yet tagged) +## 0.6.0 (not yet tagged) + +**Breaking: mozak is vault-only.** Plans live only in Obsidian vault folders. GitHub repo scopes are gone. Move every pre-0.6 entry with `mozak scope move` before you rely on 0.6.0, see [Moving to 0.6.0](docs/installation.md#moving-to-060). The moves write only `root` entries, so 0.5.0 keeps reading the migrated inventory as long as it has no `repo` keys. + +### Added +- **`mozak scope move --scope ID (--to PATH [--repo SPEC] | --drop)`** (owner). Copies the scope's `mozak.json`, `mozak.md`, annotations sidecar, `README.md` and `AGENTS.md` into a vault folder, checks every copy byte for byte, then rewrites only that inventory entry to `{ "id", "root" }` under the inventory lock, with the same validated atomic write as `focus`. It reads a local folder, a vault-plans folder, a `mozak pull` clone or the `.mozak-cache` copy. It refuses a target outside a vault or one that already holds mozak files, a source that fails `check`, and an inventory that changed since it was read. A failure leaves the old files and the old inventory valid. The old files stay. `--dry-run` writes nothing. `--drop` removes a 0-plan entry. Attached spec files are listed as `spec-not-moved` warnings. +- **Display-only repo link.** An entry may carry `repo` (`github:owner/repo` or an https URL). `mozak scopes` prints it and the sidebar shows a link icon on the scope row. mozak never fetches it, and the inventory digest ignores it. `mozak scope link --scope ID (--repo SPEC | --clear)` (owner) sets it, and `scope move --repo` sets it while moving. mozak before 0.6.0 refuses an inventory with `repo`. +- **Vault rule.** Every scope root must have a folder holding `.obsidian` at or above it. A root outside a vault is a failed scope (`scope-outside-vault`) that names `mozak scope move`, and `mozak doctor` reports it. Other scopes keep working. + +### Removed +- Repo scopes: inventory entries with `remote`, `ref` or `plans` are listed as failed scopes (`legacy-repo-scope`) with the exact `scope move` command, never a whole-inventory error. Every route refuses them, and nothing fetches or clones for them. +- `mozak pull`, the remote part of `mozak sync`, the MCP tool `mozak_sync`, the `.mozak-cache` sparse clones, repo-mode commit and push, the GitHub visibility check and `public-repo-plans`. +- Finding a scope from the current clone's git origin. `context`, `check`, `review show` and `plan show` need `--scope`. `plans` with neither `--scope` nor `--all` lists every scope. +- Obsidian plugin: the Repos group, stale and visibility badges, and the **Repo sync interval** setting with its background polling. The sync button is now **Sync vaults** and only fast-forwards vault repositories, on click. + +### Changed +- `mozak sync` fast-forwards every vault repository that holds a scope (the same as `--local`, which is still accepted). It never pushes. +- Tests run in temp vaults (a `.obsidian` folder at the temp root). + +## 0.5.0 (2026-11-01) 0.5.0 includes the fixes prepared as 0.4.8, which was never tagged. diff --git a/README.md b/README.md index e13142e..9d4d83b 100644 --- a/README.md +++ b/README.md @@ -69,17 +69,17 @@ The preview plays at double speed. In 76 seconds: you ask your agent in plain wo ## What it is -**mozak gives every project one shared plan, stored as plain files in the project folder (or in your notes, for public repos).** It does two jobs: +**mozak gives every project one shared plan, stored as plain files in a folder of your Obsidian vault.** It does two jobs: - **Agents read the same plan.** Agents that load the mozak skill or MCP server start from the same plan, so you don't have to paste the context into each one. Agents propose changes, but nothing becomes the plan until you approve it. - **You follow it from Obsidian.** Every project's plan shows up in your vault with a roadmap and progress, so parallel work is visible in one place. You approve the next step. An outcome turns green when an agent records passing evidence, such as a test run it reports. mozak does not run the tests itself, and outcomes you mark as yours also need your sign-off. Why you can trust it: -- **It is just files.** `mozak.json` holds the plan, `mozak.md` is a readable copy. They sit next to your `README.md`, and if the folder is in git, git keeps the history. No cloud, no account, no daemon. +- **It is just files.** `mozak.json` holds the plan, `mozak.md` is a readable copy. They sit next to the project's `README.md` in your vault, and if the vault is in git, git keeps the history. No cloud, no account, no daemon. - **You stay in charge.** Agreeing on *what* to do and agreeing to *start building* are two separate approvals. - **Many agents, no mess.** A write made through mozak from an out-of-date copy is refused instead of overwriting someone else's work. -- **Repos and notes together.** A project can be a local folder, an Obsidian vault folder, or a GitHub repo you have not even cloned. +- **Your notes, not your code repos.** Plans live only in your vaults, so a public code repo never carries them. A project can link to its code repo for one-click access, and mozak never fetches it. It is for developers and researchers who already use coding agents and want them to share one plan. It works with any agent that can load a skill or an MCP server. Checked so far: jcode (skill and MCP) and Claude Code (MCP). @@ -137,20 +137,15 @@ Details, exit codes, recovery and known limits: [docs/installation.md](docs/inst { "format": "mozak.local/v3", "scopes": [ - { "id": "my-app", "root": "./my-app" }, - { "id": "lab-notes", "root": "./vault/lab-notes" }, - { "id": "genome-mcp", "remote": "github:you/genome-mcp", "ref": "main" }, - { "id": "my-oss-tool", "remote": "github:you/my-oss-tool", "plans": "./vault/my-oss-tool" } + { "id": "lab-notes", "root": "./research/lab-notes" }, + { "id": "my-oss-tool", "root": "./creations/my-oss-tool", "repo": "github:you/my-oss-tool" } ] } ``` -A project with `root` is a local folder. A project with `remote` is a GitHub repo. Where its plans live depends on who should see them: +Every `root` is a folder inside an Obsidian vault (a folder with `.obsidian` at or above it). mozak refuses a scope outside a vault with `scope-outside-vault`. The optional `repo` is a display-only link to the project's code: the sidebar and `mozak scopes` show it, and mozak never clones, fetches or pushes it. Agents work in the code repo and name the project with `--scope`. -- **Private repo**: plans live inside the repo, so everyone with access shares them. mozak checks out only `README.md`, `AGENTS.md` and the two mozak files (a sparse, shallow clone) and pushes plan changes back. -- **Public repo**: add `"plans"` with a folder, usually in your notes. Plans stay there, private to you, and are never committed to the repo. mozak refuses writes once it sees that a repo holding plans has become public (checked at most once a day, and an unreachable API never blocks). - -`mozak pull --into ~/Downloads/x` clones the code anywhere. For a public repo the clone never receives plan files. Run mozak read commands inside any clone without `--scope` and it finds the project from the clone's git origin. +Coming from 0.5 with GitHub repo scopes or plans in a code repo? See [Moving to 0.6.0](docs/installation.md#moving-to-060): `mozak scope move` copies a scope into a vault folder and points its entry there. **2. Start a project.** Give the folder a `README.md` and an `AGENTS.md`, then ask your agent to set it up with the mozak skill, or run `mozak scope init` yourself (see the skill's `references/bootstrap.md`). This creates the project's `mozak.json` and `mozak.md`. Creating a project is an owner command: agents cannot do it over MCP. @@ -173,9 +168,9 @@ Install it from Obsidian: **Settings, Community plugins, Browse**, search for ** node scripts/install-obsidian-plugin.mjs /path/to/your/vault --build ``` -The plugin finds `mozak-inventory.json` by searching upward from the vault folder, or you can set its path in the plugin settings. Each GitHub project shows a globe or lock badge for a public or private repo. +The plugin finds `mozak-inventory.json` by searching upward from the vault folder, or you can set its path in the plugin settings. A project with a `repo` link shows a link icon that opens its code repo in the browser. -**Plugin disclosures (desktop-only, `isDesktopOnly: true`):** When your `mozak-inventory.json` lists scopes outside the current vault, the plugin reads their `mozak.json`, `mozak.md`, `mozak.annotations.json` (when present and annotations are on for that scope), `README.md` and `AGENTS.md` files from those configured paths and watches them when **Auto-refresh** is enabled. It never scans folders not listed in your inventory and never approves or changes a plan (it may regenerate a stale `mozak.md` projection when there are no unmerged hand edits, and the star toggle edits the `focus` lists in `mozak-inventory.json`). For remote GitHub scopes (`"remote": "github:owner/repo"` without vault-hosted `"plans"`), clicking **Sync vaults and repos** or enabling **Repo sync interval (seconds)** runs your local `git` with your existing git login on the hidden `.mozak-cache` copy: `git fetch`, then a reset of that copy to the fetched commit. If an earlier mozak write left a plan commit unpushed (for example after a network failure), the sync first commits and pushes that pending `mozak.json` / `mozak.md` change. The button also fast-forwards local vault repositories under scope locks, without pushing or merging diverged histories. That local-vault step is not run by the background timer. Set the sync interval to `0` to turn background git activity off. The sync also asks the public GitHub API, without a login and at most once a day per repo, whether each remote repo is public. The update notice only reads a cache file the CLI writes. The plugin never installs or updates itself, and has no telemetry. See [`packages/obsidian/README.md`](packages/obsidian/README.md#disclosures-obsidian-community-plugin-policy) for the full disclosure list. +**Plugin disclosures (desktop-only, `isDesktopOnly: true`):** When your `mozak-inventory.json` lists scopes outside the current vault (in your other vaults), the plugin reads their `mozak.json`, `mozak.md`, `mozak.annotations.json` (when present and annotations are on for that scope), `README.md` and `AGENTS.md` files from those configured paths and watches them when **Auto-refresh** is enabled. It never scans folders not listed in your inventory and never approves or changes a plan (it may regenerate a stale `mozak.md` projection when there are no unmerged hand edits, and the star toggle edits the `focus` lists in `mozak-inventory.json`). The only network use is the **Sync vaults** button, the same as `mozak sync`: your local `git` with your existing git login runs `git fetch` in each vault repository that holds a scope, then `git merge --ff-only` under the scope locks. It never pushes and never merges diverged histories. Nothing runs in the background. The plugin never contacts GitHub for a scope's `repo` link (the link is opened by your browser only when you click it). The update notice only reads a cache file the CLI writes. The plugin never installs or updates itself, and has no telemetry. See [`packages/obsidian/README.md`](packages/obsidian/README.md#disclosures-obsidian-community-plugin-policy) for the full disclosure list. ## Under the hood @@ -194,7 +189,9 @@ The agent writes plain `mozak.json` and `mozak.md` files in your project folder. | Read one plan compactly (lifecycle, eligibility, outcomes, next step) | `mozak plan show --plan ID` | | Record an owner decision without a request file (owner) | `mozak review decide --plan ID --purpose P --owner-ref REF --owner-message-at ISO --reason TEXT` | | Record evidence without hand-built JSON | `mozak observe --plan ID --summary TEXT --locator WHERE [--outcome O]` | -| Refresh GitHub projects now | `mozak sync` | +| Pull your vaults' latest plans (fast-forward only) | `mozak sync` | +| Move a project into a vault folder (owner) | `mozak scope move --scope ID --to PATH` | +| Link a project to its code repo, display only (owner) | `mozak scope link --scope ID --repo github:owner/repo` | | Let any MCP agent read and propose | `mozak-mcp --config mozak-inventory.json` | | Run the guided planning conversation | the installed skill at `PREFIX/skills/mozak/SKILL.md` | | Rename a project (owner) | `mozak scope retitle` | @@ -207,25 +204,25 @@ Every scope command needs an explicit `--config`. Only the maintenance commands ## Reads and the network -Local and vault-plans scopes are read from disk. A GitHub scope whose plans live in the repo is different: `scopes`, `plans`, `context`, `check` and `review show` may run `git fetch` when its cache is more than 10 minutes old, and they update its cache metadata. If that scope has an unpushed local plan commit, a read can push it. `mozak scopes` may also check GitHub release tags in the background. Set `MOZAK_NO_UPDATE_CHECK=1` to turn that check off. +Every scope is read from disk. No read route fetches, clones or pushes. Only `mozak sync` touches the network for scopes: it runs `git fetch` in each vault repository, then fast-forwards. A write with `--commit` commits the scope's two files in its vault repository and pushes when the branch has an upstream. `mozak scopes` may also check mozak's own GitHub release tags in the background. Set `MOZAK_NO_UPDATE_CHECK=1` to turn that check off. ## Safety - **Bound approvals.** An approval is tied to the exact plan version you were shown, and one message cannot be reused for a second approval. Agents over MCP cannot approve unless the launcher starts `mozak-mcp` with `--owner-decisions`. The skill tells agents to accept only your own message, not quotes or tool output, but mozak cannot verify who typed it (see the limits below). - **No overwrites.** A write through mozak based on an out-of-date copy is refused. Hand edits to the files are not guarded. -- **Small pushes.** For private GitHub projects, mozak commits and pushes only `mozak.json` and `mozak.md`. For public repos with plans in your notes it never commits or pushes. -- **No credentials.** mozak never asks for or stores them. GitHub access uses your existing git login. -- **Honest limits.** Approval follows a trusted-host convention, it is not authentication: an agent with shell access could run the owner commands. Concurrency guarantees cover cooperating processes on a local disk, not network drives, power loss or sync tools editing the same files. Remote scopes follow one branch. +- **Small commits.** With `--commit`, mozak commits only the scope's `mozak.json` and `mozak.md` in your vault repository. It never commits to a code repo. +- **No credentials.** mozak never asks for or stores them. `mozak sync` uses your existing git login. +- **Honest limits.** Approval follows a trusted-host convention, it is not authentication: an agent with shell access could run the owner commands. Concurrency guarantees cover cooperating processes on a local disk, not network drives, power loss or sync tools editing the same files. ## What is tested and what is not -**Tested.** 630 unit and integration tests plus 74 installer tests, run in CI on Ubuntu and macOS with Node 24.11 and 26 on every push to `main` and every pull request. They cover: +**Tested.** 643 unit and integration tests plus 74 installer tests, run in CI on Ubuntu and macOS with Node 24.11 and 26 on every push to `main` and every pull request. They cover: - stale writes refused, including two real CLI processes writing at once - a write killed mid-way recovering without losing data - the two approvals kept separate and bound to the version you saw - agents over MCP unable to approve or create projects -- public repos never receiving plan commits +- scopes outside a vault refused, and moving a scope into a vault keeping every plan byte-identical - the installer refusing unsafe targets without writing anything The Obsidian plugin passed Obsidian's automated community review. Its build and attestation are checked on every release. @@ -235,8 +232,16 @@ The Obsidian plugin passed Obsidian's automated community review. Its build and - **A benefit for agents.** A small pilot (5 proxy tasks, 10 agent sessions) compared agents with and without mozak and found no significant difference in token use: one group did 16% worse, the other 6% better. A larger evaluation is planned. Until then, treat mozak as a way to keep one approved plan and see it in Obsidian, not as a proven speed-up. - **Agent hosts.** Checked: jcode loading the skill and the MCP server, and Claude Code 2.1 calling the MCP server from the npm package. Codex and other MCP clients have not been verified yet. - **The plugin inside Obsidian.** Its view model is unit-tested and it has been tried by hand, but there are no automated tests running inside the Obsidian app. -- **Real GitHub.** Tests use local bare repos. Real GitHub was checked by hand. -- **Unsupported setups.** Windows, network filesystems and diverged remote branches. +- **Real GitHub.** `mozak sync` tests use local bare repos. Real GitHub was checked by hand. +- **Unsupported setups.** Windows, network filesystems and diverged vault branches. + +## New in 0.6: vault-only (breaking) + +- **Plans live only in Obsidian vaults.** GitHub repo scopes (`remote`, `ref`, `plans` entries), `mozak pull`, the remote part of `mozak sync`, the `mozak_sync` MCP tool and finding a scope from a clone's git origin are gone. Read routes need `--scope`. +- **`mozak scope move`** copies a scope's files into a vault folder, checks every byte, and points its inventory entry there. The old files stay until you delete them. A pre-0.6 entry is listed as a failed scope (`legacy-repo-scope`) with the exact move command, and every other scope keeps working. +- **Display-only repo link.** `mozak scope link --scope ID --repo github:owner/repo` adds a link the sidebar and `mozak scopes` show. mozak never fetches it. + +See [Moving to 0.6.0](docs/installation.md#moving-to-060). ## New in 0.5 @@ -260,7 +265,7 @@ npm ci --ignore-scripts && npm run build npm test && npm run test:install ``` -Run the tests before opening a pull request. If your global git config adds hooks or signing, run them with `GIT_CONFIG_GLOBAL=/dev/null`. The format, remote scopes, exit codes and known limits are in [docs/installation.md](docs/installation.md). +Run the tests before opening a pull request. If your global git config adds hooks or signing, run them with `GIT_CONFIG_GLOBAL=/dev/null`. The format, the vault rule, exit codes and known limits are in [docs/installation.md](docs/installation.md). ## License diff --git a/SPEC.md b/SPEC.md index 360e476..b48aa1a 100644 --- a/SPEC.md +++ b/SPEC.md @@ -1,6 +1,8 @@ # mozak v1 spec > **Historical.** This is the original v1 design draft from 2026-10-11 (format 1). It does not describe current mozak: format 1 is retired, agents cannot edit plans directly, and mozak is not on npm as 1.0.0. For the current behaviour see [README.md](README.md) and [docs/installation.md](docs/installation.md). +> +> **Inventory since 0.6.0.** Every scope is a folder inside an Obsidian vault, listed in `mozak-inventory.json` as `{ "id", "root" }` with optional `focus` and a display-only `repo` link. Project scopes no longer live in git repositories: a code repo is linked, not used for plans. See [docs/installation.md, Vault-only scopes](docs/installation.md#6b-vault-only-scopes-060). Status: draft, from the 24 grilling decisions of 2026-10-11. Not yet implemented. diff --git a/docs/README.md b/docs/README.md index c63ba44..c9334dd 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,7 +6,7 @@ Start with the [README](../README.md). This page lists every doc in the repo and | Doc | What it covers | | --- | --- | -| [installation.md](installation.md) | Build from source, the portable installer, `mozak upgrade` and `mozak doctor`, exit codes, recovery, the write lock, the experimental `concurrency.rebase` setting, remote scopes, known limits, and the verification status of every check. | +| [installation.md](installation.md) | Build from source, the portable installer, `mozak upgrade` and `mozak doctor`, exit codes, recovery, the write lock, the experimental `concurrency.rebase` setting, vault-only scopes and moving to 0.6.0, known limits, and the verification status of every check. | | [annotations.md](annotations.md) | Owner annotations: cross-plan refs (needs, informs, supersedes), deadlines, `mozak annotate`, `graph`, `ready` and `plans --sort deadline`. | | [../packages/obsidian/README.md](../packages/obsidian/README.md) | The Obsidian plugin: use, settings, and the community plugin disclosures (files outside the vault, network use, no self-update). | | [../skills/mozak/SKILL.md](../skills/mozak/SKILL.md) | The agent skill source. It is a template: load the installed copy, not this file. Its `references/` folder has the routes, bootstrap and recovery notes. | diff --git a/docs/annotations.md b/docs/annotations.md index 6c74a0c..2f87677 100644 --- a/docs/annotations.md +++ b/docs/annotations.md @@ -52,7 +52,6 @@ Temp files are named `mozak.annotations.json..tmp`. `init` and `projection - Annotations are **off by default** (since 0.5.0). A scope without `"annotations": true` behaves like 0.4.7: `mozak.annotations.json` is never read, `graph`, `ready`, `plans --sort deadline`, `check` and the Obsidian sidebar ignore it, `mozak.md` does not change, and `annotate` is refused with `annotations-disabled`. - Turn them on per scope with `scopes..annotations: true`. -- Repo-mode remote scopes are always refused. Their plans are pushed to a repository. `check` warns about a sidecar file found in one. - `annotations.personalVaults` from older settings files is accepted and has no effect. - `concurrency.rebase` turns on the experimental read-set rebase (see `docs/installation.md`, Parallel writes). A per-scope `scopes..concurrency.rebase` wins over the top-level value. The default is off. - The key reserved for a later slice (`indexRoots`) is accepted. Any other key is a `settings-unknown-key` finding with no effect. @@ -66,7 +65,7 @@ A target `scope/plan[#outcome]` resolves in this order: 2. A live plan recorded folding it in (`decision.mergedPlanId`). The ref then points at that plan. 3. Otherwise it is reported: `dangling` (scope not in the inventory, plan missing, outcome missing) or `unavailable` (the target scope cannot be read now). -Reads never fetch for resolution. A remote scope is read from its local copy. +Reads never fetch for resolution. Every scope is read from its vault folder. ## Deadlines from prose diff --git a/docs/installation.md b/docs/installation.md index e546e7a..6f47662 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -135,7 +135,7 @@ To move older scopes to the new names, run once (owner only): mozak rename-files --config INVENTORY --all ``` -It renames both files under the scope lock and regenerates the note so its link points to `mozak.json`. The plan bytes do not change, so approvals stay valid. It refuses a scope whose note has hand edits, or one that has both names. Repo scopes that commit plans to GitHub are skipped: rename those in a clone with `git mv` and push. Commit the rename in your notes repo afterwards. On a case-insensitive disk, git needs `git add -A` to record a case-only rename. +It renames both files under the scope lock and regenerates the note so its link points to `mozak.json`. The plan bytes do not change, so approvals stay valid. It refuses a scope whose note has hand edits, or one that has both names. Commit the rename in your notes repo afterwards. On a case-insensitive disk, git needs `git add -A` to record a case-only rename. ### Update notice @@ -153,7 +153,7 @@ It renames both files under the scope lock and regenerates the note so its link It never edits MCP settings, the inventory or any plan file. For those it prints the change to make. -**Restoring on a new machine or account:** install Node, clone and build mozak, run the installer, clone your notes repo (with the inventory and vault-plans folders), connect the MCP server to the inventory, then run `mozak doctor --fix` and follow what it prints until it reports no failures. +**Restoring on a new machine or account:** install Node, clone and build mozak, run the installer, clone your notes repo (with the inventory and the scope folders), connect the MCP server to the inventory, then run `mozak doctor --fix` and follow what it prints until it reports no failures. ## 4. Exit codes and status values @@ -270,13 +270,13 @@ receipt records. Outside git it reports `history-unavailable` and skips the walk ### Syncing a vault: `mozak sync --scope ID` or `mozak sync --local` -For a local scope inside a git repo, `sync` replaces a bare `git pull --rebase`, which bypasses the scope locks. Per repo -it fetches the upstream of the current branch outside the locks, takes the write lock of every inventoried local and -vault-plans scope in that repo in path order, runs `git merge --ff-only`, and releases. It never rebases, merges a +For a scope inside a git repo (usually your vault), `sync` replaces a bare `git pull --rebase`, which bypasses the scope locks. Per repo +it fetches the upstream of the current branch outside the locks, takes the write lock of every inventoried +scope in that repo in path order, runs `git merge --ff-only`, and releases. It never rebases, merges a diverged history or pushes. Row status: `fast-forwarded`, `up-to-date`, `ahead` (local commits to push), or a problem: `not-fast-forward` (exit 3, nothing changed), `busy` (exit 4, a scope lock is held), `fetch-failed`, `merge-failed`, -`no-upstream`, `detached`, `not-in-git`. `--local` syncs every such repo and the remote scopes; plain `mozak sync` still -syncs remote scopes only. +`no-upstream`, `detached`, `not-in-git`. Plain `mozak sync` syncs every such repo. `--local` is still accepted and means +the same (before 0.6.0 it added the vault repos to the remote scopes). ### Projection repair @@ -316,7 +316,7 @@ Limits: the writes in between are found through receipt times. A write merged by ## 6a. Focus list -Every scope entry in the inventory, local or remote, may carry `focus`: an array of unique plan ids the owner starred. The Obsidian sidebar shows them in its Focus tab. +Every scope entry in the inventory may carry `focus`: an array of unique plan ids the owner starred. The Obsidian sidebar shows them in its Focus tab. ```json { "id": "atlas-app", "root": "./atlas-app", "focus": ["launch", "billing"] } @@ -328,40 +328,58 @@ Every scope entry in the inventory, local or remote, may carry `focus`: an array - A starred id that is no longer a plan is a `check` warning (`focus-unknown-plan`), never an error. Remove it with `mozak focus remove`. - mozak before 0.5.0 refuses an inventory with `focus` (`unknown key "focus"`). Upgrade every machine that reads the inventory before starring a plan. -## 6b. Remote scopes +## 6b. Vault-only scopes (0.6.0) -A scope can live in a GitHub repo instead of a local folder. List it with `remote` and no `root` (exactly one of the two), in a `mozak.local/v3` inventory. `v2` inventories still load unchanged. +Every scope entry is `{ "id", "root" }`, plus the optional `focus` list and `repo` link. The `root` must be a folder inside an Obsidian vault: some folder at or above it holds a `.obsidian` folder. mozak checks this when it loads the inventory. An entry outside a vault is listed as a failed scope with `scope-outside-vault`, and every route refuses it, while the other scopes keep working. `mozak doctor` names the `scope move` command for it. ```json { "format": "mozak.local/v3", "scopes": [ - { "id": "atlas-app", "root": "./atlas-app" }, - { "id": "genome-mcp", "remote": "github:pitfa19/genome-mcp", "ref": "main" } + { "id": "atlas-app", "root": "./creations/atlas-app", "repo": "github:pitfa19/atlas-app" }, + { "id": "lab-notes", "root": "./research/lab-notes" } ] } ``` -`remote` is `github:owner/repo`, an `https://` URL, or an absolute `file://` URL. `ref` is a plain branch name and defaults to `main`. +- **Repo link, display only.** `repo` is `github:owner/repo` or an `https://` URL. The Obsidian sidebar shows it as a link on the scope row and `mozak scopes` prints it. mozak never uses it for git or the network, and the inventory digest ignores it (as with `focus`). Set or clear it with `mozak scope link --scope ID (--repo SPEC | --clear)` (owner). mozak before 0.6.0 refuses an inventory with a `repo` key, so add links only after every machine runs 0.6.0. +- **Agents in a code repo.** Agents work in the code repo and name the scope with `--scope`. mozak does not guess a scope from the current folder or its git origin. +- **Network.** No read or write route fetches, clones or pushes for a scope. `mozak sync` fast-forwards the vault repositories (see [Syncing a vault](#syncing-a-vault-mozak-sync---scope-id-or-mozak-sync---local)). A write with `--commit` commits the scope's two files in its vault repository and pushes when that branch has an upstream. -- **Fetch.** mozak makes a sparse, blobless, depth 1 git clone under `.mozak-cache//` next to the inventory file. Only `README.md`, `mozak.json`, `mozak.md` and `AGENTS.md` are checked out. It is real git, so you can also commit and push normally. Add `.mozak-cache/` to the `.gitignore` of the inventory folder if it is a git repo (`mozak sync` warns when it is not ignored). -- **Freshness.** `mozak scopes`, `plans` and `context` refresh a remote scope when the last fetch is older than 10 minutes. `mozak sync [--scope ID]` forces a refresh. If the fetch fails (offline, auth), the cached copy is used and marked `stale` (JSON: `stale`, `lastFetchAt`, `remote[]`, a `remote-stale` issue). The MCP tool `mozak_sync` does the same as `mozak sync`. -- **Writes.** `propose`, `revise`, `complete`, `observe` and the rest work against the sparse copy. After a successful write mozak commits only `mozak.json` and `mozak.md` and pushes. Owner approval rules are unchanged. A write refuses with `remote-stale` if the copy cannot be refreshed first. If the push fails, the commit stays local, the result is exit 5 with `remote-push-failed`, and the next `mozak sync` pushes it. -- **Pull.** `mozak pull --scope ID [--into PATH]` (owner) makes a full working clone, default `~/Documents/`. It refuses a destination that exists and is not a clone of the same remote. Afterwards the inventory still says `remote`, but reads and writes use the full clone (recorded in `.mozak-cache/.meta.json`). A sync of a full clone only fast-forwards it. It never overwrites your working tree. -- **Vault plans (public repos).** Add `"plans": ""` to a remote entry to keep its `mozak.json` and `mozak.md` in that folder instead of the repo. The folder works like a local scope (it needs `README.md` and `AGENTS.md`, created before `scope init`). mozak never clones, fetches, commits or pushes for such a scope, so it works offline and plans are never published. `sync` reports it as `source: "vault"`. `pull` clones the code only and leaves the plans where they are. -- **Visibility guard.** For a remote scope whose plans live in the repo, mozak asks the public GitHub API (no login, 5 second timeout) whether the repo is public, and caches the answer for 24 hours in the scope's meta file. A public answer refuses writes with `public-repo-plans` (exit 3) and adds a warning to `sync` and `scopes`. Reads are never blocked, and a failed check never blocks anything. -- **Inside a clone.** `context`, `plans`, `check` and `review show` may omit `--scope` when run inside a clone of an inventoried repo. The scope is found from the clone's `origin` URL (https, ssh, `github:` and local path forms). Writes always need `--scope`. -- **Auth.** mozak shells out to `git` (no shell, hard timeouts, no prompts), so your credential helper, for example `gh auth setup-git`, is used. -- A repo with no `mozak.json` at its root is reported as `scope-uninitialized` ("not a scope"). +## Moving to 0.6.0 -Cache layout: `.mozak-cache//` (sparse git clone) and `.mozak-cache/.meta.json` (last fetch time, last error, full clone path). Deleting the cache is safe once everything is pushed. Unpushed commits in a sparse copy are pushed by the next `mozak sync`. +0.6.0 removes GitHub repo scopes: entries with `remote`, `ref` or `plans`, `mozak pull`, the remote part of `mozak sync`, the `mozak_sync` MCP tool, the `.mozak-cache` sparse clones and the public-repo check. A local entry whose folder is not inside a vault (for example a code repo holding `mozak.json`) is refused too. Nothing is deleted: 0.6.0 lists each such entry as a failed scope, with the exact command to move it, and every other scope keeps working. + +`mozak scope move` (owner) moves one scope: + +```sh +mozak scope move --config INVENTORY --scope ID --to PATH [--repo SPEC] --owner-ref REF --owner-message-at ISO --reason TEXT [--dry-run] [--json] +mozak scope move --config INVENTORY --scope ID --drop --owner-ref REF --owner-message-at ISO --reason TEXT [--dry-run] [--json] +``` + +- `--to PATH` is the new folder, inside a vault (relative paths resolve against the inventory's folder). mozak copies `mozak.json`, `mozak.md`, the annotations sidecar, `README.md` and `AGENTS.md`, checks every copy byte for byte, then rewrites only that inventory entry to `{ "id", "root": PATH }` (plus `repo` when given) under the inventory lock, with the same validated atomic write as `focus`. Every other key (including `focus` and `x`) and every other entry stays as it was. +- It reads the files from wherever the scope is today: a local folder, a pre-0.6 vault-plans folder, the full clone `mozak pull` made, or the `.mozak-cache/` sparse copy. The plan file stores the scope id, not its path, so plans, receipts and approvals stay valid. +- It refuses a target outside a vault (`move-target-outside-vault`), a target that already holds mozak files (`move-target-has-scope`, `move-target-file-exists`), a source that fails `check` (`move-source-fails-check`), and an inventory changed since it was read (`stale-input`). A failure before the inventory is replaced removes what it copied, so the old files and the old inventory stay valid. Running it again after a success changes nothing. +- The old files stay in place. Delete them yourself once you have checked the new folder (for a code repo, as a commit there). Attached specification files are not copied: the result lists each as a `spec-not-moved` warning so you can copy it by hand. +- `--drop` removes an entry with 0 plans from the inventory instead. Its files stay. +- `--dry-run` prints the files it would copy, their sizes and hashes, and the new entry, and writes nothing. + +Steps: + +1. On 0.5, run `mozak sync --scope ID` for every repo scope whose plans live in its repo, so the cache holds the newest plans. +2. With the 0.6.0 CLI (a scratch install is enough, the inventory keeps working with 0.5 as long as it has no `repo` keys), run `mozak scope move ... --dry-run` for every failed scope, check the list, then run the same commands without `--dry-run`. Use `--drop` for entries you no longer need. +3. Run `mozak scopes`: 0 failed. Run `mozak check --scope ID` for each moved scope: 0 issues. Commit and push your vault. +4. Upgrade every machine to 0.6.0 (`mozak upgrade`), then add repo links with `mozak scope link --scope ID --repo github:owner/repo`. +5. Delete the old plan files from the code repos and remove `.mozak-cache/` next to the inventory (keep `.mozak-cache/usage/` if you use the usage log). + +The Obsidian plugin drops its old **Repo sync interval** setting on its own. ## 7. Known limits -- **One branch per remote scope.** There is no merge handling: a diverged remote makes a write or sync fail and the scope shows stale. The installer does not edit your `.gitignore`. +- **One branch per vault repo.** `mozak sync` only fast-forwards: a diverged vault branch is reported as `not-fast-forward` and left for you to merge. The installer does not edit your `.gitignore`. - **No network filesystems.** Locking and crash safety assume a local disk. Network filesystems and concurrent editors (sync tools writing the same files) are not covered. - **Approval is a trusted-host convention.** mozak records the owner's approval message as given by the agent host. It does not authenticate the owner; an agent host that lies can forge an approval. -- **Restore needs the notes repo plus `mozak doctor --fix`.** Plans live in your notes (and private repos). A new machine needs that repo cloned, mozak installed, the MCP server connected, then `mozak doctor --fix` (section 3, Checking a setup). +- **Restore needs the notes repo plus `mozak doctor --fix`.** Plans live in your vaults. A new machine needs those repos cloned, mozak installed, the MCP server connected, then `mozak doctor --fix` (section 3, Checking a setup). - Crash safety: plan files are flushed to disk before they replace the old ones, and the folder after. On filesystems that ignore folder flushes this is best effort, and it always depends on the disk honouring flushes. - Upgrading needs the source checkout the installation came from (or `--source PATH`), and only knows release tags of that checkout's `origin`. - The source copy of the conversation skill is a template. The installer refuses an unrendered template. Load the skill only from the installed folder, directly or through a symlink. diff --git a/docs/obsidian-submission-checklist.md b/docs/obsidian-submission-checklist.md index d484973..53d0b03 100644 --- a/docs/obsidian-submission-checklist.md +++ b/docs/obsidian-submission-checklist.md @@ -47,7 +47,7 @@ Status key: **Met** means checked in this repo. **Owner** means only the owner c | 20 | No obfuscated code. | Met | `main.js` is an esbuild bundle, not minified. | | 21 | No ads. No client-side telemetry. | Met | None. | | 22 | Does not install or update itself or its dependencies. | Met | The plugin only reads the update cache (`cachedUpdateNotice`). The bundle has no release-tag fetch and no `spawn(` (test). Updates come through Obsidian or `mozak upgrade`. | -| 23 | Disclose network use: which services and why. | Met | `packages/obsidian/README.md`, "Disclosures": `git fetch` for remote scopes (default every 60 seconds while Auto-refresh is on), the sync button's fast-forward of local vault repos, the unauthenticated GitHub API visibility check (at most once a day per repo), and the update notice, which reads a local cache only. | +| 23 | Disclose network use: which services and why. | Met | `packages/obsidian/README.md`, "Disclosures": the **Sync vaults** button's `git fetch` and fast-forward of the vault repos that hold scopes (only on click, never in the background), display-only repo links that are never fetched, and the update notice, which reads a local cache only. Since 0.6.0 there are no repo scopes, no background git and no GitHub API call. | | 24 | Disclose access to files outside the vault, and why. | Met | Same section: the scope files the inventory names (`mozak.annotations.json` only for scopes with annotations on), the upward lookup for `mozak-inventory.json`, and what the plugin writes: a stale `mozak.md` it regenerates, and the `focus` lists in `mozak-inventory.json` through the star. It never writes plan state. | | 25 | Disclose payments, accounts, ads and server-side telemetry if any. | Met | None. The README says so. | | 26 | Include a license and respect the licenses of bundled code. | Met | The bundle contains mozak's own `@mozak/core` and esbuild helpers. `obsidian`, `electron` and Node built-ins are external. The fonts with OFL notices are in `docs/assets/brand/` and are not bundled. | @@ -57,7 +57,7 @@ Status key: **Met** means checked in this repo. **Owner** means only the owner c ## Risks for the automated review - **A. Update and spawn code in the bundle.** Fixed in 0.4.x: the plugin bundle has no release-tag fetch, no refresher script and no `spawn(` (test `the plugin bundle has no update refresher` in `packages/obsidian/test/model.test.ts`). -- **B. `child_process` use.** The plugin runs `git` for remote scopes and the sync button, and `curl` for the public visibility check. It is disclosed. Reviewers sometimes ask why. The answer: mozak reads plan files from your own git remotes with your existing login. +- **B. `child_process` use.** The plugin runs `git` only for the **Sync vaults** button. It is disclosed. Reviewers sometimes ask why. The answer: mozak fast-forwards your own vault repositories with your existing login, under its write locks, so a sync never races a plan write. - **C. Writes outside plan state.** New in 0.5.0: the star edits `mozak-inventory.json`. It is disclosed in row 24 and in both READMEs. ## What the owner does for 0.5.0, in order diff --git a/docs/plans-index.md b/docs/plans-index.md index d9e68ef..c0bd090 100644 --- a/docs/plans-index.md +++ b/docs/plans-index.md @@ -12,7 +12,7 @@ mozak plans-md --config INVENTORY # owner: write them - One `plans.md` per git repository that holds scopes, at that repository's root. A repository lists only its own scopes, so a company vault's file never names a personal plan, and the other way round. - It holds titles and states only: open, paused, awaiting approval, completed. No purposes, outcomes, evidence or decisions. Rejected drafts are left out. - The first line marks the file as generated. A `plans.md` without that line is never overwritten: the run reports `plans-md-conflict` (exit 3) and leaves it as it is. Same content means no write. -- Repo-mode remote scopes and scopes outside git are skipped and listed under `skipped`. +- Scopes outside git are skipped and listed under `skipped`. - Writing is an owner route. `--print` is a read, and agents may call it. mozak does not commit the file; commit it with the vault like any other note. ## `mozak locators`: where citations point @@ -28,7 +28,6 @@ Every `Source.locator` and `Evidence.locator` of the selected plans, with what i | `resolved` | a file or folder was found. `title` is its first heading or file name. For a Markdown note with an anchor, `anchorFound` says whether a heading matches it. | | `missing` | looks like a path or a `[[note]]` link, nothing found | | `ambiguous` | a `[[note]]` name matches several notes, none in the citing scope | -| `remote` | a relative path in a scope whose code lives in a remote repo that is not cloned here | | `external` | a URL or a `git:` object, not checked | | `not-checked` | prose, such as an owner message or a command | diff --git a/docs/release-notes-draft.md b/docs/release-notes-draft.md index 707d780..b33ab9a 100644 --- a/docs/release-notes-draft.md +++ b/docs/release-notes-draft.md @@ -1,50 +1,49 @@ -# mozak 0.5.0 release notes (DRAFT) +# mozak 0.6.0 release notes (DRAFT) > **DRAFT.** Not published and not tagged. The owner edits, approves and publishes this. Numbers below come from [installation.md, verification status](installation.md#8-verification-status). Recheck them on the release commit. ## In one line -A Focus tab for the plans you care about now, shorter context reads for agents, and safer storage, with every new switch off until you turn it on. +mozak is vault-only: every plan lives in a folder of your Obsidian vault, code repos never carry plans, and `mozak scope move` brings older scopes over without changing a byte of a plan. -## Highlights +## Breaking -- **Focus tab in Obsidian.** The sidebar tabs are now Open, Focus and Done. Star a plan to put it in Focus. The star writes a `focus` list on that scope's entry in `mozak-inventory.json`, the same as `mozak focus add|remove`. Agents can read it with `mozak focus list` or MCP `mozak_focus` but never change it. Focus is a sidebar marker only, not plan state. -- **Shorter reads for agents.** `mozak context --brief` gives one short summary per plan. `mozak context --plan ID` gives the full state of one plan. Both work in the MCP tool `mozak_context`. -- **Links and deadlines between plans, off by default.** The owner can record that a plan needs, informs or supersedes another, and set deadlines, with `mozak annotate`. `mozak graph`, `mozak ready` and `mozak plans --sort deadline` read them. Turn them on per scope in `mozak-settings.json`. They live in a separate `mozak.annotations.json`, so `mozak.json` and `mozak.md` do not change. See [annotations.md](annotations.md). -- **Plans index, locators and similar plans.** `mozak plans-md` writes a `plans.md` with plan titles and states at each notes repo root. `mozak locators` shows where each source and evidence locator points, and `check` lists cited notes that changed after they were cited. `mozak similar` reports duplicate, overlapping and superseding plans across scopes. See [plans-index.md](plans-index.md). -- **Safer storage.** `scope init` and `projection repair` add ignore lines for the write lock and temp files, and `check` warns when the lock is not ignored or is tracked by git. A write refuses if the files changed under it right before the replace. `mozak recover` clears a stuck lock, `mozak plan prune --rejected` removes rejected plans, `mozak check --history N` finds hand edits, and `mozak sync --local` fast-forwards your vaults. -- **Parallel agents (experimental, off by default).** With `concurrency.rebase` on, a stale append (an observation, a discussion save, a new plan) can commit onto the fresh state when nothing it read has changed. -- **Fixes.** The duplicate-plan guard catches copies that differ only in ID numbers. Plan merges refuse to drop discussion questions. A late supporting observation keeps an accepted outcome done. The Obsidian plugin opens plans in a vault opened through a symlink. -- **Smaller core.** The unused format-1 modules are gone, error messages say what to do next, and the compiler runs stricter checks. +- **GitHub repo scopes are gone.** Inventory entries with `remote`, `ref` or `plans`, `mozak pull`, the remote part of `mozak sync`, the MCP tool `mozak_sync`, the `.mozak-cache` sparse clones and the public-repo check are removed. Such an entry now shows as a failed scope (`legacy-repo-scope`) with the exact command that moves it. Every other scope keeps working. +- **Scopes must be inside a vault.** A scope folder needs a folder holding `.obsidian` at or above it. A scope elsewhere (for example a code repo with `mozak.json` in it) shows as `scope-outside-vault`, with the same move command. +- **No scope from the current folder.** `context`, `check`, `review show` and `plan show` need `--scope`, also inside a code repo. -The full list is in [CHANGELOG.md](../CHANGELOG.md). 0.5.0 includes the fixes prepared as 0.4.8, which was never tagged. +## Highlights -## Upgrade +- **`mozak scope move`** (owner) copies a scope's plan files, annotations, `README.md` and `AGENTS.md` into a vault folder, checks every byte, and points the inventory entry there under the inventory lock. It refuses a target outside a vault or one that already holds mozak files, and a source that fails `check`. A failure leaves everything as it was, and the old files stay until you delete them. `--dry-run` shows the plan first. `--drop` removes an empty entry. +- **Display-only repo links.** `mozak scope link --scope ID --repo github:owner/repo` adds a link the Obsidian sidebar and `mozak scopes` show. mozak never fetches it. +- **A quieter plugin.** No background git and no GitHub API calls. **Sync vaults** fast-forwards your vault repositories on click, under the scope locks, and never pushes. -```bash -mozak upgrade --vault ~/path/to/your/vault -mozak doctor --fix -``` +The full list is in [CHANGELOG.md](../CHANGELOG.md). -Nothing changes in existing scopes until you use a new feature. +## Moving over -**Upgrade every machine before you star a plan.** mozak before 0.5.0 refuses an inventory that has a `focus` list (`unknown key "focus"`). If one machine stars a plan while another still runs 0.4.x, that older mozak stops reading the shared inventory until it is upgraded. +Follow [Moving to 0.6.0](installation.md#moving-to-060). In short: -Off unless you turn them on in the `mozak-settings.json` next to the inventory: owner annotations (`scopes..annotations: true`), `concurrency.rebase` (top level or `scopes..concurrency`) and the counts-only usage log (`"usageLog": true`, or `MOZAK_USAGE_LOG=on`). Read [installation.md](installation.md#parallel-writes-concurrencyrebase-experimental-off-by-default) before you turn rebase on. +1. On 0.5, run `mozak sync --scope ID` for every repo scope whose plans live in its repo. +2. With the 0.6.0 CLI, run `mozak scope move ... --dry-run` for each failed scope, check the list, then run it for real. The moves write only `root` entries, so 0.5 on your other machines keeps reading the inventory. +3. `mozak scopes` shows 0 failed. Commit and push the vault. +4. Upgrade every machine (`mozak upgrade --vault ~/path/to/your/vault`), then add repo links. +5. Delete the old plan files from code repos when you are happy. ## Known limits -- `concurrency.rebase` relies on receipt times. A write merged by git from a machine whose clock is behind can be missed. That is why it stays off by default. On this release the large-store stress run (8 writers, kill -9, about 1000 write attempts) kept the commit p95 under the 300 ms target on macOS; see [installation.md](installation.md#8-verification-status). -- The rename rehash narrows the race with a direct editor. It does not close it. +- mozak before 0.6.0 refuses an inventory with a `repo` key. Add links only after every machine runs 0.6.0. +- Attached specification files are not moved. `scope move` lists each one so you can copy it. - Approval follows a trusted-host convention. It is not authentication. - Linux and macOS only. The Obsidian plugin is desktop only. -- Linux was not checked locally. CI runs it on the pull request. The local checks for this release ran on macOS with Node 24.11.0 and Node 26. +- Linux was not checked locally. CI runs it on the pull request. ## Release steps (owner) -1. Push `release/0.5.0` and open a draft pull request into `main` so CI runs on Linux and macOS with Node 24.11 and 26. Wait for green. -2. Fast-forward `main` to `release/0.5.0`. -3. Change the CHANGELOG heading `0.5.0 (not yet tagged)` to `0.5.0 (YYYY-MM-DD)` if you want the date in the tag. -4. Tag `v0.5.0` on that commit and push the tag. `.github/workflows/release.yml` refuses a tag that does not match `package.json` and both manifests, runs the tests, creates the plugin tag `0.5.0` on the same commit and attaches `main.js`, `manifest.json` and `styles.css`. -5. Paste these notes into the GitHub release, without the DRAFT banner. -6. npm publishing (`npm run build:npm`) is a separate step. +1. Push `release/0.6.0` and open a draft pull request into `main` so CI runs on Linux and macOS with Node 24.11 and 26. Wait for green. +2. Migrate the real inventory with the branch build from a scratch prefix (dry run first), before any 0.6.0 install. +3. Fast-forward `main` to `release/0.6.0`. +4. Change the CHANGELOG heading `0.6.0 (not yet tagged)` to `0.6.0 (YYYY-MM-DD)` if you want the date in the tag. +5. Tag `v0.6.0` on that commit and push the tag. `.github/workflows/release.yml` refuses a tag that does not match `package.json` and both manifests, runs the tests, creates the plugin tag `0.6.0` on the same commit and attaches `main.js`, `manifest.json` and `styles.css`. +6. Paste these notes into the GitHub release, without the DRAFT banner. +7. npm publishing (`npm run build:npm`) is a separate step. diff --git a/manifest.json b/manifest.json index 00dae19..447b01b 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "mozak", "name": "mozak", - "version": "0.5.0", + "version": "0.6.0", "minAppVersion": "1.14.4", "description": "Project scopes and plans shared with AI agents, stored as plain files.", "author": "pitfa19", diff --git a/package-lock.json b/package-lock.json index 961ade3..9f9d5ba 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "mozak-monorepo", - "version": "0.5.0", + "version": "0.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "mozak-monorepo", - "version": "0.5.0", + "version": "0.6.0", "workspaces": [ "packages/*" ], @@ -660,9 +660,9 @@ }, "packages/cli": { "name": "@mozak/cli", - "version": "0.5.0", + "version": "0.6.0", "dependencies": { - "@mozak/core": "0.5.0" + "@mozak/core": "0.6.0" }, "bin": { "mozak": "dist/index.js" @@ -673,16 +673,16 @@ }, "packages/core": { "name": "@mozak/core", - "version": "0.5.0", + "version": "0.6.0", "engines": { "node": ">=24.11.0" } }, "packages/mcp": { "name": "@mozak/mcp", - "version": "0.5.0", + "version": "0.6.0", "dependencies": { - "@mozak/core": "0.5.0" + "@mozak/core": "0.6.0" }, "bin": { "mozak-mcp": "dist/index.js" @@ -693,9 +693,9 @@ }, "packages/obsidian": { "name": "@mozak/obsidian", - "version": "0.5.0", + "version": "0.6.0", "dependencies": { - "@mozak/core": "0.5.0" + "@mozak/core": "0.6.0" }, "devDependencies": { "esbuild": "^0.28.0", diff --git a/package.json b/package.json index 0ebb115..e7c73a5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mozak-monorepo", - "version": "0.5.0", + "version": "0.6.0", "private": true, "type": "module", "workspaces": [ diff --git a/packages/cli/package.json b/packages/cli/package.json index 6995d3e..e59db76 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@mozak/cli", - "version": "0.5.0", + "version": "0.6.0", "type": "module", "main": "dist/index.js", "bin": { @@ -10,6 +10,6 @@ "node": ">=24.11.0" }, "dependencies": { - "@mozak/core": "0.5.0" + "@mozak/core": "0.6.0" } } diff --git a/packages/core/package.json b/packages/core/package.json index 50a4de4..0739bfd 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@mozak/core", - "version": "0.5.0", + "version": "0.6.0", "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/core/test/current-contract-docs.test.ts b/packages/core/test/current-contract-docs.test.ts index cf01b87..987ada2 100644 --- a/packages/core/test/current-contract-docs.test.ts +++ b/packages/core/test/current-contract-docs.test.ts @@ -13,10 +13,12 @@ test("SPEC is labelled historical format 1 and points to the current contract", } }); -test("README discloses that reads can fetch, cache and push repo-mode plans", () => { +test("README discloses that reads never fetch, and names the only scope network use (sync) and the update check", () => { const readme = readFileSync(new URL("../../../README.md", import.meta.url), "utf8"); const disclosure = readme.split("## Reads and the network")[1]?.split("\n## ")[0] ?? ""; - for (const term of ["git fetch", "cache", "push", "vault", "MOZAK_NO_UPDATE_CHECK=1"]) { - assert.ok(disclosure.includes(term), `missing read-side effect disclosure: ${term}`); + for (const term of ["No read route fetches", "mozak sync", "git fetch", "vault", "--commit", "push", "MOZAK_NO_UPDATE_CHECK=1"]) { + assert.ok(disclosure.includes(term), `missing network disclosure: ${term}`); } + // 0.6.0 removed repo scopes: no read may be described as fetching or caching repo-mode plans. + assert.doesNotMatch(disclosure, /cache metadata|repo-mode|10 minutes/); }); diff --git a/packages/mcp/package.json b/packages/mcp/package.json index a926467..ee2a33a 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@mozak/mcp", - "version": "0.5.0", + "version": "0.6.0", "type": "module", "main": "dist/index.js", "bin": { @@ -10,6 +10,6 @@ "node": ">=24.11.0" }, "dependencies": { - "@mozak/core": "0.5.0" + "@mozak/core": "0.6.0" } } diff --git a/packages/obsidian/README.md b/packages/obsidian/README.md index c81ce9d..56271d1 100644 --- a/packages/obsidian/README.md +++ b/packages/obsidian/README.md @@ -10,25 +10,25 @@ Obsidian sidebar for [mozak](../../README.md). Shows every scope from your `moza - Search filters by scope title, scope id, or plan title. Matching scopes open automatically while searching. - Each open plan row shows a small outcome strip (green = done, gold = evidence recorded, purple = current stop, faint = not started) and `done/total`. - Click a plan row to open its `## Title · \`plan-id\`` section in the scope's `mozak.md` note (or its line under `## Completed` for completed plans). If the scope is outside the current vault, the plugin opens `mozak.md` in your system default viewer. -- Each GitHub remote scope shows a `globe` (public) or `lock` (private) badge, plus quick links to its GitHub repository and `README.md`. +- A scope with a `repo` link (set with `mozak scope link`) shows a link icon on its row and, when opened, quick links to the code repo and its `README.md`. The link opens in your browser. The plugin never fetches it. - When annotations are on for a scope (off by default, see [docs/annotations.md](../../docs/annotations.md)) and the owner has added cross-plan refs with `mozak annotate`, a plan row lists them: what it needs, informs or supersedes, both ways. Display only. The plugin never writes `mozak.annotations.json`. - Settings (**Settings → mozak**): - **Inventory path**: path to `mozak-inventory.json` (leave empty to auto-discover by walking upward from the vault root). - **Auto-refresh**: watch `mozak-inventory.json` and each scope's `mozak.json` / `mozak.md` with `fs.watch` and redraw on change. - - **Repo sync interval (seconds)**: how often remote (`github:owner/repo`) scopes are pulled in the background (`0` disables background git polling; minimum `15`). + +Every scope lives in an Obsidian vault (mozak 0.6.0 and later). A pre-0.6 repo scope or a scope outside a vault shows as a failed row with the `mozak scope move` command that fixes it. ## Disclosures (Obsidian community plugin policy) -- **Desktop only (`isDesktopOnly: true`).** The plugin uses Node.js APIs (`node:fs`, `node:path`, `node:child_process`) to read your local scope files and optional git remotes. -- **Files accessed outside the vault.** When your `mozak-inventory.json` lists scopes outside the current vault (for example local code repositories or other folders you own), the plugin reads their `mozak.json`, `mozak.md`, `mozak.annotations.json` (when present and annotations are on for that scope), `README.md`, and `AGENTS.md` files from those configured paths, and watches them when **Auto-refresh** is enabled. It never scans or crawls directories not listed in `mozak-inventory.json`. To find the inventory when **Inventory path** is empty, it checks whether a file named `mozak-inventory.json` exists in the vault folder and in each parent folder up to the filesystem root. It only checks that one file name and reads the first match. +- **Desktop only (`isDesktopOnly: true`).** The plugin uses Node.js APIs (`node:fs`, `node:path`, `node:child_process`) to read your local scope files and to run `git` for the **Sync vaults** button. +- **Files accessed outside the vault.** When your `mozak-inventory.json` lists scopes outside the current vault (in your other vaults), the plugin reads their `mozak.json`, `mozak.md`, `mozak.annotations.json` (when present and annotations are on for that scope), `README.md`, and `AGENTS.md` files from those configured paths, and watches them when **Auto-refresh** is enabled. It never scans or crawls directories not listed in `mozak-inventory.json`. To find the inventory when **Inventory path** is empty, it checks whether a file named `mozak-inventory.json` exists in the vault folder and in each parent folder up to the filesystem root. It only checks that one file name and reads the first match. - **What the plugin writes.** The plugin never modifies canonical plan state (`mozak.json`) and never approves or mutates plans. It writes two things: when a scope's derived `mozak.md` note is out of date with its `mozak.json` and has no unmerged hand edits, it regenerates `mozak.md` on disk (the same projection as `mozak render`), and the star toggle edits the `focus` list of that scope's entry in `mozak-inventory.json` under the inventory lock (every other key and the entry order stay as they were). - **Network and child-process activity.** - 1. If your inventory contains remote GitHub scopes (`"remote": "github:owner/repo"` without vault-hosted `"plans"`), the plugin runs your local `git` binary with your existing git credentials on its `.mozak-cache` copy: `git fetch`, then reset that cache to the fetched commit. If an earlier write left a pending `mozak.json` / `mozak.md` change, sync first commits and pushes that plan change, and nothing else. This happens when you click **Sync vaults and repos**, and in the background every **Repo sync interval (seconds)** while **Auto-refresh** is on. The default is every 60 seconds. Set the interval to `0` to turn background git fetches off. - 2. **Sync vaults and repos** also syncs each git repository (for example a vault) that holds a local scope, the same as `mozak sync --local`: `git fetch` from that repository's upstream, then `git merge --ff-only` while holding the mozak write locks of every scope inside it. It never pushes, never rebases and never merges a diverged history: a vault with local commits is reported as having unpushed commits, and a diverged vault is reported and left alone. This only happens when you click the button, never in the background. With no remote scopes and no local scope inside a git repository, the plugin runs no git command. - 3. The same sync asks the public GitHub API (`https://api.github.com/repos/OWNER/REPO`, no login, through your local `curl` with a 5 second timeout) whether each remote GitHub scope is public. This includes vault-plans scopes (`"plans"` set), which are never fetched with git but still get the badge. It asks at most once per 24 hours per scope (once per hour while the answer is unknown) and stores the answer in that scope's `.mozak-cache` meta file. The answer drives the public or private badge and the warning when plans would be published in a public repo. Local scopes are never checked. - 4. **Update notice.** The plugin makes no network call for this. It only reads `~/.local/state/mozak/update.json` (or `$XDG_STATE_HOME/mozak/update.json`), which the installed mozak CLI writes after it checks `https://api.github.com/repos/pitfa19/mozak/tags` at most once per 24 hours. When that file names a newer release, the sidebar shows one line such as `mozak X.Y.Z available`. Set `MOZAK_NO_UPDATE_CHECK=1` to turn the CLI check and the notice off. + 1. **Sync vaults** syncs each git repository (usually a vault) that holds a scope, the same as `mozak sync`: `git fetch` from that repository's upstream with your local `git` and your existing git credentials, then `git merge --ff-only` while holding the mozak write locks of every scope inside it. It never pushes, never rebases and never merges a diverged history: a vault with local commits is reported as having unpushed commits, and a diverged vault is reported and left alone. This only happens when you click the button, never in the background. With no scope inside a git repository, the plugin runs no git command. + 2. **Repo links.** A scope's `repo` link is a plain link. The plugin never contacts GitHub or any other host for it. Your browser opens it only when you click it. + 3. **Update notice.** The plugin makes no network call for this. It only reads `~/.local/state/mozak/update.json` (or `$XDG_STATE_HOME/mozak/update.json`), which the installed mozak CLI writes after it checks `https://api.github.com/repos/pitfa19/mozak/tags` at most once per 24 hours. When that file names a newer release, the sidebar shows one line such as `mozak X.Y.Z available`. Set `MOZAK_NO_UPDATE_CHECK=1` to turn the CLI check and the notice off. - **No self-update.** The plugin never installs or updates itself, the CLI or anything else. Updates come through Obsidian's Community plugins screen or `mozak upgrade`, which you run yourself. -- **No telemetry, accounts, payments, ads or cloud service.** All plans and evidence stay in your local folders and git repositories. +- **No telemetry, accounts, payments, ads or cloud service.** All plans and evidence stay in your vault folders and their git repositories. ## Build and install diff --git a/packages/obsidian/manifest.json b/packages/obsidian/manifest.json index 00dae19..447b01b 100644 --- a/packages/obsidian/manifest.json +++ b/packages/obsidian/manifest.json @@ -1,7 +1,7 @@ { "id": "mozak", "name": "mozak", - "version": "0.5.0", + "version": "0.6.0", "minAppVersion": "1.14.4", "description": "Project scopes and plans shared with AI agents, stored as plain files.", "author": "pitfa19", diff --git a/packages/obsidian/package.json b/packages/obsidian/package.json index a31d427..feb4ea1 100644 --- a/packages/obsidian/package.json +++ b/packages/obsidian/package.json @@ -1,6 +1,6 @@ { "name": "@mozak/obsidian", - "version": "0.5.0", + "version": "0.6.0", "private": true, "type": "module", "description": "Read-only Obsidian plugin that lists every mozak scope and its plans.", @@ -10,7 +10,7 @@ "test": "node --import ../../scripts/test-git-isolation.mjs --test --experimental-strip-types test/*.test.ts" }, "dependencies": { - "@mozak/core": "0.5.0" + "@mozak/core": "0.6.0" }, "devDependencies": { "esbuild": "^0.28.0", diff --git a/packages/obsidian/test/submission.test.ts b/packages/obsidian/test/submission.test.ts index a05bc36..1e9b01b 100644 --- a/packages/obsidian/test/submission.test.ts +++ b/packages/obsidian/test/submission.test.ts @@ -18,9 +18,12 @@ test("versions.json maps the current plugin version to the manifest's minAppVers assert.ok(manifest.description.length <= 250 && manifest.description.endsWith("."), "description is short and ends with a period"); }); -test("plugin README discloses the visibility check and that the update notice reads a cache only", () => { +test("plugin README discloses the vault sync, that repo links are never fetched, and that the update notice reads a cache only", () => { const readme = readRepo("packages/obsidian/README.md"); - assert.match(readme, /api\.github\.com\/repos\/OWNER\/REPO/); + assert.match(readme, /git merge --ff-only/); + assert.match(readme, /never contacts GitHub or any other host for it/); assert.match(readme, /makes no network call for this/); assert.match(readme, /never installs or updates itself/); + // 0.6.0 removed the repo scopes, so the visibility check, cache fetches and background polling are not disclosed any more. + assert.doesNotMatch(readme, /api\.github\.com\/repos\/OWNER\/REPO|Repo sync interval|\.mozak-cache/); }); diff --git a/scripts/setup-demo-vault.mjs b/scripts/setup-demo-vault.mjs index 594a191..cd6a29a 100644 --- a/scripts/setup-demo-vault.mjs +++ b/scripts/setup-demo-vault.mjs @@ -456,7 +456,7 @@ writeFileSync( ); writeFileSync( join(pluginDest, "data.json"), - JSON.stringify({ inventoryPath: "", autoRefresh: true, remotePollSeconds: 0 }, null, 2) + "\n", + JSON.stringify({ inventoryPath: "", autoRefresh: true }, null, 2) + "\n", ); // 5. Write a live helper script (demo-step.mjs) so each beat can be triggered cleanly during screen recording diff --git a/skills/mozak/references/bootstrap.md b/skills/mozak/references/bootstrap.md index 6443b65..4a7cf36 100644 --- a/skills/mozak/references/bootstrap.md +++ b/skills/mozak/references/bootstrap.md @@ -20,10 +20,8 @@ A single JSON file. Relative `root` paths resolve against the inventory file's o { "format": "mozak.local/v3", "scopes": [ - { "id": "my-project", "root": "my-project" }, - { "id": "other", "root": "/absolute/path/to/other" }, - { "id": "shared", "remote": "github:owner/repo", "ref": "main" }, - { "id": "oss", "remote": "github:owner/public-repo", "plans": "notes/oss" } + { "id": "my-project", "root": "creations/my-project" }, + { "id": "oss", "root": "/absolute/path/to/vault/oss", "repo": "github:owner/public-repo" } ] } ``` @@ -31,12 +29,13 @@ A single JSON file. Relative `root` paths resolve against the inventory file's o Rules enforced by core: - `format` is `"mozak.local/v3"` (v2 is accepted read-compatibly). -- Each scope entry has exactly `id` + `root` (local) or `id` + `remote` [+ `ref`] [+ `plans`] (remote). -- Routing rule: a **private** repo keeps plans inside the repo (shared with collaborators). A **public** repo gets `plans`, a folder for its mozak.json and mozak.md, usually in the owner's notes. Ask the owner which applies; never put plans in a public repo. mozak refuses writes to a repo-mode scope whose repo is public (`public-repo-plans`). -- A `plans` folder is initialized like a local scope: it needs its own `README.md` and `AGENTS.md` describing the project. -- Read routes (`context`, `plans`, `check`, `review show`) run inside a clone may omit `--scope`; the scope is found from the clone's git origin. Writes always name `--scope`. +- Each scope entry has `id` + `root`, and may have `focus` (the owner's stars) and `repo` (a display-only link to the code repo, `github:owner/repo` or an https URL; never fetched). +- Every `root` is a folder inside an Obsidian vault: a folder with `.obsidian` at or above it. A root outside a vault is a failed scope (`scope-outside-vault`). Plans never go into a code repo, public or private. The project's code repo, if any, goes in `repo`. +- An entry with `remote`, `ref` or `plans` is a pre-0.6 repo scope (`legacy-repo-scope`). Its error names the `mozak scope move` command; moving it is the owner's call. +- A scope folder is initialized from its own `README.md` and `AGENTS.md` describing the project. +- Every scoped route names `--scope`. mozak never guesses a scope from the current folder or its git origin, so an agent working in a code repo passes the scope id explicitly. - Scope ids are unique; two scopes may not resolve to the same root. -- Editing this file is an owner-approved act: confirm before adding or removing entries. +- Editing this file is an owner-approved act: confirm before adding or removing entries. `mozak scope move`, `mozak scope link` and `mozak focus add|remove` are the owner routes that edit one entry. Every CLI call takes `--config INVENTORY`. There is no default path and no environment fallback. @@ -44,7 +43,7 @@ Every CLI call takes `--config INVENTORY`. There is no default path and no envir `scope init` is owner-only and refuses to run until the scope root is a real project entrance: -1. The root directory exists and contains **`README.md` and `AGENTS.md`**, written or reviewed explicitly for this scope. Core refuses init without them (`missing-entry-document`). +1. The root directory exists inside an Obsidian vault and contains **`README.md` and `AGENTS.md`**, written or reviewed explicitly for this scope. Core refuses init without them (`missing-entry-document`). 2. The root contains no `mozak.json`, no `mozak.md`, and no legacy `.mozak/` directory (legacy state needs separately approved conversion). 3. The scope has an entry in the inventory. 4. The owner has confirmed, in this conversation, initializing this scope id at this root. diff --git a/skills/mozak/references/payloads.md b/skills/mozak/references/payloads.md index eac0caf..f64f61a 100644 --- a/skills/mozak/references/payloads.md +++ b/skills/mozak/references/payloads.md @@ -31,7 +31,7 @@ node {{MOZAK_CLI}} --config INVENTORY --scope ID --request .annotations: true` in the `mozak-settings.json` next to the inventory. Otherwise `annotate` is refused (`annotations-disabled`), and on repo-mode remote scopes always (`annotations-refused-remote`). +- Annotations are off by default. The owner turns them on per scope with `scopes..annotations: true` in the `mozak-settings.json` next to the inventory. Otherwise `annotate` is refused (`annotations-disabled`). ## Review digest and CAS diff --git a/versions.json b/versions.json index 2aa67b3..c02b26d 100644 --- a/versions.json +++ b/versions.json @@ -8,5 +8,6 @@ "0.4.6": "1.14.4", "0.4.7": "1.14.4", "0.4.8": "1.14.4", - "0.5.0": "1.14.4" + "0.5.0": "1.14.4", + "0.6.0": "1.14.4" } From 13f5d8a6bd4b90675904c454d8599b8ccdceeaae Mon Sep 17 00:00:00 2001 From: pitfa19 <166558275+pitfa19@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:52:57 +0100 Subject: [PATCH 07/10] scope move: a source repo's missing write-lock ignore is a warning, not a refusal Found by the migration rehearsal on copies of the laptop data: the anpit-web repo-mode cache (a 0.5.0 sparse clone) never checks out the repo's .gitignore, so check reports lock-not-ignored there and the move refused. That finding is about the folder the move leaves behind, not the plans it copies. lock-not-ignored and lock-ignore-unavailable now come back as source-* warnings; every other check finding (hand edits, lock-in-git, stuck locks) still refuses, and check's info entries never count. verify-old-client-sidecar.sh: its temp base is a vault now (.obsidian), since the branch CLI refuses scopes outside a vault. Test first: the new scope-move test failed with move-source-fails-check, passes now. scope-move.test 14/14. crapper: assertSourceChecks 4.0, planMove 8.0. dryer: none. mutator on assertSourceChecks 5/5 killed after removing a redundant early return that a surviving mutant exposed. Gate 08-move-fix: 644/644 in three TMPDIR settings, install 73+1. --- docs/installation.md | 2 +- packages/core/src/scope-move.ts | 27 ++++++++++++++++++++------- packages/core/test/scope-move.test.ts | 25 +++++++++++++++++++++++++ scripts/verify-old-client-sidecar.sh | 2 ++ 4 files changed, 48 insertions(+), 8 deletions(-) diff --git a/docs/installation.md b/docs/installation.md index 6f47662..c5faf36 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -359,7 +359,7 @@ mozak scope move --config INVENTORY --scope ID --drop --owner-ref REF --owner-me - `--to PATH` is the new folder, inside a vault (relative paths resolve against the inventory's folder). mozak copies `mozak.json`, `mozak.md`, the annotations sidecar, `README.md` and `AGENTS.md`, checks every copy byte for byte, then rewrites only that inventory entry to `{ "id", "root": PATH }` (plus `repo` when given) under the inventory lock, with the same validated atomic write as `focus`. Every other key (including `focus` and `x`) and every other entry stays as it was. - It reads the files from wherever the scope is today: a local folder, a pre-0.6 vault-plans folder, the full clone `mozak pull` made, or the `.mozak-cache/` sparse copy. The plan file stores the scope id, not its path, so plans, receipts and approvals stay valid. -- It refuses a target outside a vault (`move-target-outside-vault`), a target that already holds mozak files (`move-target-has-scope`, `move-target-file-exists`), a source that fails `check` (`move-source-fails-check`), and an inventory changed since it was read (`stale-input`). A failure before the inventory is replaced removes what it copied, so the old files and the old inventory stay valid. Running it again after a success changes nothing. +- It refuses a target outside a vault (`move-target-outside-vault`), a target that already holds mozak files (`move-target-has-scope`, `move-target-file-exists`), a source that fails `check` (`move-source-fails-check`), and an inventory changed since it was read (`stale-input`). A source whose git repo does not ignore the write lock (a 0.5 `.mozak-cache` copy never has the repo's `.gitignore`) still moves, with a `source-lock-not-ignored` warning: that is about the folder left behind. A failure before the inventory is replaced removes what it copied, so the old files and the old inventory stay valid. Running it again after a success changes nothing. - The old files stay in place. Delete them yourself once you have checked the new folder (for a code repo, as a commit there). Attached specification files are not copied: the result lists each as a `spec-not-moved` warning so you can copy it by hand. - `--drop` removes an entry with 0 plans from the inventory instead. Its files stay. - `--dry-run` prints the files it would copy, their sizes and hashes, and the new entry, and writes nothing. diff --git a/packages/core/src/scope-move.ts b/packages/core/src/scope-move.ts index 8eeec41..551f422 100644 --- a/packages/core/src/scope-move.ts +++ b/packages/core/src/scope-move.ts @@ -78,13 +78,26 @@ function moveRepoArg(value: unknown, drop: boolean): string | null { return repo; } -/** Run `check` on the source folder as a plain scope: no settings, no vault rule, no network. */ -function assertSourceChecks(entry: ScopeEntry): void { +/** + * Git-hygiene findings about the source folder's own repository. They describe the old folder, which the move leaves + * behind (a 0.5.0 sparse cache never checks out the repo's .gitignore), not the plan files it copies, so they are + * warnings. The target's rules are checked by `check` after the move. A tracked lock (`lock-in-git`) still blocks. + */ +const SOURCE_ONLY_FINDINGS = new Set(["lock-not-ignored", "lock-ignore-unavailable"]); +/** Informational `check` entries that never set its exit code (they sit in `issues` next to the findings). */ +const INFO_FINDINGS = new Set(["leftover-temp-file", "focus-unknown-plan", "write-lock-held", "history-unavailable", "cited-note-changed", "cited-notes-unavailable"]); + +/** Run `check` on the source folder as a plain scope: no settings, no vault rule, no network. Returns source-only warnings. */ +function assertSourceChecks(entry: ScopeEntry): { code: string; message: string }[] { const local: ScopeInventory = { format: "mozak.local/v3", scopes: [{ id: entry.id, root: entry.root }], digest: "" }; const out = executeOperation(local, "check", { scope: entry.id }); - if (out.exitCode === 0) return; - const codes = (out.data.issues as { code: string }[]).map((i) => i.code).join(", "); - throw new DomainError("move-source-fails-check", `scope "${entry.id}" at ${entry.root} fails check (${codes}); fix that first, the move copies only a clean scope`, 3); + const issues = out.data.issues as { code: string; message: string }[]; + const blocking = issues.filter((i) => !SOURCE_ONLY_FINDINGS.has(i.code) && !INFO_FINDINGS.has(i.code)); + if (blocking.length > 0) { + const codes = blocking.map((i) => i.code).join(", "); + throw new DomainError("move-source-fails-check", `scope "${entry.id}" at ${entry.root} fails check (${codes}); fix that first, the move copies only a clean scope`, 3); + } + return issues.filter((i) => SOURCE_ONLY_FINDINGS.has(i.code)).map((i) => ({ code: `source-${i.code}`, message: `${entry.root}: ${i.message} The move leaves that folder behind.` })); } /** @@ -247,12 +260,12 @@ function planMove(inventoryPath: string, req: Request): Planned { const inPlace = target === source.root; const files = inPlace ? [] : sourceFiles(source.root); if (!inPlace) assertTargetFree(target, files.map((f) => f.name), inv); - assertSourceChecks(source); + const sourceWarnings = assertSourceChecks(source); const entry = movedEntry(old, req.to, req.repo); const changed = JSON.stringify(entry) !== JSON.stringify(old); doc.scopes[index] = entry as RawEntry; const plans = readScope(source).state.plans.length; - const warnings = inPlace ? [] : specsLeftBehind(source, target); + const warnings = [...sourceWarnings, ...(inPlace ? [] : specsLeftBehind(source, target))]; return { source, files, text: inventoryText(doc, text), result: { ...base, status: "ok", action: "move", to: target, inPlace, changed, plans, warnings, entry, files: files.map((f) => ({ name: f.name, bytes: f.bytes.length, sha256: sha256(f.bytes) })) }, diff --git a/packages/core/test/scope-move.test.ts b/packages/core/test/scope-move.test.ts index b241f85..b487252 100644 --- a/packages/core/test/scope-move.test.ts +++ b/packages/core/test/scope-move.test.ts @@ -3,6 +3,7 @@ import { after, test } from "node:test"; import assert from "node:assert/strict"; import { createHash } from "node:crypto"; +import { execFileSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -152,6 +153,30 @@ test("move refuses a target outside a vault, a target that holds mozak files, an same(); }); +test("a source in a git repo that does not ignore the write lock still moves; the finding is a warning, data findings still block", () => { + // 0.5.0 sparse caches check out only the plan files, never the repo's .gitignore, so check reports lock-not-ignored + // there. That is about the old folder's git rules, which the move leaves behind, not about the plans it copies. + const f = setup([{ id: "web", remote: "github:synthetic/web", ref: "main" }]); + const cache = join(f.base, ".mozak-cache", "web"); + makeScope("web", cache); + rmSync(join(cache, ".gitignore"), { force: true }); + execFileSync("git", ["init", "-q", "-b", "main"], { cwd: cache }); + const out = moveScope(f.config, { scope: "web", to: "vault/projects/web", ...OWNER }); + assert.equal(out.status, "ok"); + assert.deepEqual(out.warnings.map((w) => w.code), ["source-lock-not-ignored"]); + assert.deepEqual(raw(f.config).scopes[3], { id: "web", root: "vault/projects/web" }); + // A data finding in the same kind of source still refuses. + const g = setup([{ id: "web", remote: "github:synthetic/web", ref: "main" }]); + const cache2 = join(g.base, ".mozak-cache", "web"); + makeScope("web", cache2); + execFileSync("git", ["init", "-q", "-b", "main"], { cwd: cache2 }); + writeFileSync(join(cache2, "mozak.md"), "hand edit\n"); + const before = readFileSync(g.config, "utf8"); + assert.throws(() => moveScope(g.config, { scope: "web", to: "vault/projects/web", ...OWNER }), { code: "move-source-fails-check" }); + assert.equal(readFileSync(g.config, "utf8"), before); + assert.ok(!existsSync(join(g.vault, "projects"))); +}); + test("move refuses missing owner provenance and bad arguments before touching anything", () => { const f = setup(); assert.throws(() => moveScope(f.config, { scope: "proj", to: "vault/p", ...OWNER, ownerRef: "" }), { code: "invalid-input" }); diff --git a/scripts/verify-old-client-sidecar.sh b/scripts/verify-old-client-sidecar.sh index dfbbe37..077e1ff 100755 --- a/scripts/verify-old-client-sidecar.sh +++ b/scripts/verify-old-client-sidecar.sh @@ -6,6 +6,8 @@ NEW="$(cd "$(dirname "$0")/.." && pwd)/packages/cli/dist/index.js" OLD="${OLD_CLI:-$HOME/.local/share/mozak-next/node_modules/@mozak/cli/dist/index.js}" BASE="$(mktemp -d "${TMPDIR:-/tmp}/mozak-s4-old-client.XXXXXX")" trap 'rm -rf "$BASE"' EXIT +# Since 0.6.0 a scope must be inside an Obsidian vault: the temp base is one (older clients ignore .obsidian). +mkdir -p "$BASE/.obsidian" mkdir -p "$BASE/alpha"; printf 'Synthetic\n' > "$BASE/alpha/README.md"; printf 'Synthetic\n' > "$BASE/alpha/AGENTS.md" printf '{"format":"mozak.local/v3","scopes":[{"id":"alpha","root":"./alpha"}]}' > "$BASE/inv.json" # Annotations are off unless the settings file next to the inventory turns them on for the scope. From 5bc99e3f67414df8e71eec07217003e6f25d3934 Mon Sep 17 00:00:00 2001 From: pitfa19 <166558275+pitfa19@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:01:25 +0100 Subject: [PATCH 08/10] Record the 0.6.0 verification: gates on Node 26 and 24.11, verifiers, migration and upgrade rehearsals Docs only (installation.md section 8 and the status table, README test count 644). Numbers from logs/08-* in the release work folder. --- README.md | 2 +- docs/installation.md | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9d4d83b..78eef00 100644 --- a/README.md +++ b/README.md @@ -216,7 +216,7 @@ Every scope is read from disk. No read route fetches, clones or pushes. Only `mo ## What is tested and what is not -**Tested.** 643 unit and integration tests plus 74 installer tests, run in CI on Ubuntu and macOS with Node 24.11 and 26 on every push to `main` and every pull request. They cover: +**Tested.** 644 unit and integration tests plus 74 installer tests, run in CI on Ubuntu and macOS with Node 24.11 and 26 on every push to `main` and every pull request. They cover: - stale writes refused, including two real CLI processes writing at once - a write killed mid-way recovering without losing data diff --git a/docs/installation.md b/docs/installation.md index c5faf36..6cf12ff 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -8,7 +8,8 @@ This guide covers building mozak from source, the portable installer, exit codes | --- | --- | | Pending-revision summary order and safe projection recovery | Verified 2026-10-29 on macOS, Node 26.11.1: build passed, all 495 tests passed, installer suite 73 passed and 1 skipped (case-sensitive filesystem required). Three built-CLI regressions and two core tests cover deterministic field order, official repair, unchanged canonical bytes and review subject, repeat repair, legacy filenames, merge metadata, and refusal of other edits. Test-first: CLI revision initially exited 5 with its own `bridge-conflict`; after sorting, recovery still failed `bridge-conflict` versus `bridge-stale` until the recogniser was added. With focused Node coverage, crapper scored the new recogniser 1.0, `pendingChangedFields` 8.1, `isOlderRender` 3.0 and `projectStatus` 7.1; unrelated existing functions still exceed 10. Dryer found no duplicate candidates at 0.8 across the three changed source files. Mutator killed all three selected recogniser mutants (not a whole-repo mutation run). Existing plugin CJS `import.meta` warnings remain. No live scope or installation was changed. | | Fresh public GitHub clone, build, install and README walkthrough on macOS, Node 26.11.1 | Verified 2026-10-18 at `8337e04`: clean `git clone`, `npm ci --ignore-scripts`, build and install into a fresh prefix with an isolated `HOME` took about 8 seconds. Every README command then ran as written (section 8). | -| Full test suite on macOS, Node 26.10.0 and 24.11.0 | Verified 2026-11-01 on `release/0.5.0` (`9c26892`, version 0.5.0): 630 tests passed with three `TMPDIR` settings on each Node version, installer suite 73 passed and 1 skipped. Details and the verifier numbers are in [section 8](#8-verification-status). | +| Full test suite on macOS, Node 26.10.0 and 24.11.0 | Verified 2026-11-01 on `release/0.6.0` (version 0.6.0): 644 tests passed with three `TMPDIR` settings, installer suite 73 passed and 1 skipped, on Node 26.10.0; 643 of 643 on Node 24.11.0 one commit earlier (`a4a771f`, before the `scope move` warning fix). Details, the verifiers and the migration rehearsal are in [section 8](#8-verification-status). | +| Full test suite on macOS, Node 26.10.0 and 24.11.0 (0.5.0) | Verified 2026-11-01 on `release/0.5.0` (`9c26892`, version 0.5.0): 630 tests passed with three `TMPDIR` settings on each Node version, installer suite 73 passed and 1 skipped. Details and the verifier numbers are in [section 8](#8-verification-status). | | Full test suite on macOS, Node 26.10.0 | Verified 2026-10-31 on branch `vnext/2a-fixes` (`b8e0f71` plus the 0.4.8 version bump, not yet merged or tagged): `npm ci --ignore-scripts && npm run build`, then `npm test` with `JCODE_SCRATCH_DIR` unset: 539 tests passed, 0 failed, with the default macOS `TMPDIR`, with `TMPDIR=/tmp` and with a realpath folder. Installer suite 73 passed, 1 skipped (case-collision test needs a case-sensitive filesystem). `npm run build:npm` built a package reporting 0.4.8, and the built CLI reports 0.4.8. New tests cover P0.1, P0.2, P0.5 to P0.7 (including `plan delete` under a concurrent edit), the SPEC banner and README network disclosure, accepted outcomes after late support, MCP error text, and a vault opened through a symlink. Not run on Linux or in CI. | | Full test suite on macOS, Node 26.11.1 | Verified 2026-10-29 at `a8e0fa9` plus the 0.4.7 version bump: 497 tests passed, 0 failed. Installer suite 73 passed, 1 skipped (case-collision test needs a case-sensitive filesystem). New tests: `attach-spec` computes an omitted `discussionDigest` and refuses a stale supplied one, and `observe` flag errors list the allowed values for activity-kind, relation, classification and verdict. | | Source build and tests on Linux, Node 24.11.0 | Verified earlier at `c324d45`: 334 core tests and 69 installer tests passed. CI covers Linux on every push since. | @@ -390,6 +391,10 @@ The Obsidian plugin drops its old **Repo sync interval** setting on its own. | Check | Status | | --- | --- | +| 0.6.0 full gate on `release/0.6.0` (2026-11-01, macOS 27 arm64) | Node 26.10.0 at `13f5d8a`: `npm run build`, then `npm test` with `JCODE_SCRATCH_DIR` unset, 644 of 644 with the default macOS `TMPDIR`, with `TMPDIR=/tmp` and with a realpath folder; `npm run test:install` 73 passed, 1 skipped. Node 24.11.0 at `a4a771f` (the commit before the `scope move` warning fix): `npm ci --ignore-scripts`, build, 643 of 643 in the same three settings, installer 73 passed and 1 skipped. On both: `npm run typecheck`, `npm run lint` (33 Markdown files, 64 relative links, 0 broken), `npm run build:npm` built `mozak 0.6.0` and its CLI prints `0.6.0`, and the `release.yml` version check for tag `v0.6.0` (package, root manifest and plugin manifest `0.6.0`, three plugin assets present). A `git grep` over `packages/*/src` finds no `fetch`, `clone`, `ls-remote`, GitHub API or `curl` call reachable from a scope route: the only hits are the vault fast-forward in `local-sync.ts`, mozak's own release check and upgrade, and the `--commit` push in `git-commit.ts`. Linux runs in CI on the pull request. | +| 0.6.0 verifiers (same commits) | V-race, V-ref and V-dup tests 41 of 41 on both Node versions. `verify-dup.ts`: precision 1.000, recall 0.988. `verify-latency.ts` (23 synthetic scopes, 230 plans): `plans.md` max 18.4 ms (budget 1000), 460 locators max 24.4 ms (budget 300). V-race 9 at 1018 write attempts (8 writers, kill -9 once per round, rebase on): 642 commits, 0 violations, 31 of 31 locks left by killed writers cleared by `recover`, commit p50 101.5 ms, **p95 245.4 ms** (target 300 ms), max 600.4 ms. V-race 1: flag off 43 of 73 attempts wasted, flag on 0 of 30, 0 lost either way. Old client (`scripts/verify-old-client-sidecar.sh`, temp base now a vault): the 0.5.0 and the 0.4.7 CLI each read, check and write a scope with a sidecar made by the branch, the sidecar is unchanged, and the branch reads one edge with 0 dangling. | +| 0.6.0 migration rehearsal (copies only, no network) | A scratch copy of the laptop layout: the mini's two vault clones (git archive of HEAD, the anpit vault at `obsidian/anpit` as on the laptop), the laptop inventory with its home path mapped to the scratch folder, the three code-repo scopes and `~/.atticus` from the laptop copies, and the `anpit-web` cache rebuilt as a 0.5.0 sparse clone with an unreachable origin. A logging `curl` and a git URL rewrite blocked the network; nothing tried it. Before: 0.5.0 lists 31 scopes, 0 failed. The branch lists the same copy with `mozak`, `obsidian-plugins-mcp` and `anpit-web` as `legacy-repo-scope` and `redumenzi`, `proinz-spasizalogaj`, `atticus-jcode-bridge` and `atticus-jcode` as `scope-outside-vault`, each message naming its `mozak scope move` command, and every other scope ok. The owner's moves with `--dry-run` left the inventory byte-identical, then for real: `redumenzi` and `atticus-jcode-bridge` to `creations/`, `proinz-spasizalogaj` to `personal/fakultet/`, `anpit-web` to `anpit/projects/` (warning `source-lock-not-ignored`), `atticus-jcode` dropped (0 plans), `mozak` and `obsidian-plugins-mcp` rewritten in place. After: 30 scopes, 0 failed; plan counts per scope, the 52 unique plans in 38 `plans --all` group cells, and every scope's revision and graph hash equal the 0.5.0 output; `check` exit 0 on all 30; all 31 `mozak.md` files byte-identical and the 16 moved files equal their sources, which stay in place; every other inventory entry unchanged, the moved ones are `{ id, root }` only. 0.5.0 reads the migrated copy with 0 failed and the same groups. `atticus-jcode-bridge` warns `spec-not-moved` for `docs/spec-bridge-v1.md`. `mozak-inventory-sync --transform` maps the migrated inventory, with `repo` links added, to the mini's paths: 30 scopes, no legacy keys, links kept, and the branch reads it with 0 failed. `context --brief` on the copied `mozak` scope: 5912 bytes. | +| 0.6.0 upgrade rehearsal (scratch prefix and vault) | A local mirror with `v0.5.0` and `release/0.6.0` tagged `v0.6.0` there only. 0.5.0 built from the tag and installed into a scratch prefix with its plugin in a scratch vault. `mozak upgrade --check`: 0.5.0 to 0.6.0. `mozak upgrade --vault`: `upgraded`, `mozak --version` 0.6.0, the plugin in the scratch vault 0.5.0 to 0.6.0, the old install kept as `mozak.previous-0.5.0`, the source checkout back on its branch and clean, and a second run `up-to-date`. On the pre-0.6 inventory the vault scope reads ok and the code-folder scope is `scope-outside-vault`; `mozak doctor` fails the inventory check with the exact `scope move` command. | | 0.5.0 full gate on `release/0.5.0` (`9c26892`, 2026-11-01, macOS 27 arm64, Node 26.10.0 and Node 24.11.0) | Passed on both Node versions: `npm ci --ignore-scripts`, `npm run build`, then `npm test` with `JCODE_SCRATCH_DIR` unset, 630 of 630 with the default macOS `TMPDIR`, with `TMPDIR=/tmp` and with a realpath folder. `npm run test:install` 73 passed, 1 skipped (case-collision test needs a case-sensitive filesystem). `npm run typecheck` and `npm run lint` (33 Markdown files, 61 relative links, 0 broken) passed. `npm run build:npm` built `mozak 0.5.0` and its CLI prints `0.5.0`. The version check from `release.yml`, run locally for tag `v0.5.0`: package, root manifest and plugin manifest all `0.5.0`, all three plugin assets present. Linux runs in CI on the pull request. | | 0.5.0 verifiers (same commit, both Node versions) | V-race, V-ref and V-dup tests (`rebase.test.ts`, `scope-process.test.ts`, `vref.test.ts`, `vdup.test.ts`): 41 of 41. `node scripts/verify-dup.ts`: precision 1.000, recall 0.988, 0 templated duplicates. `node scripts/verify-latency.ts` (23 synthetic scopes, 230 plans): `plans.md` max 19.5 ms (budget 1000), CLI 62 ms, 460 locators max 25.3 ms (budget 300). | | 0.5.0 large-store stress, V-race 9 at 1000 write attempts (Node 26) | `MOZAK_VRACE_KILL_OPS=1000`, 8 writers, think 1 to 2 s, rebase on, kill -9 once per round. Two runs: 1007 and 1003 attempts, 605 and 609 commits, 0 violations, 31 of 31 locks left by killed writers cleared by `recover`, commit p50 95.2 and 100.1 ms, **p95 222.9 and 219.6 ms** (target 300 ms), max 629.4 and 649.5 ms. V-race 1 (3 agents x 10): flag off 46 of 76 attempts wasted, flag on 0 of 30, 0 lost either way. | From 23a0ba50827cf84836cbe827d7f475767a6a7af7 Mon Sep 17 00:00:00 2001 From: pitfa19 <166558275+pitfa19@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:17:18 +0100 Subject: [PATCH 09/10] Record the Node 24.11 run on the final tip, one V-race 9 flake and the bundle check Docs only. The flake: recovery-required in one round of the kill -9 test (lock folder without owner.json), lock code and test unchanged since 0.5.0; five reruns and the full suite passed in the same folder. --- docs/installation.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/installation.md b/docs/installation.md index 6cf12ff..1db8ea1 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -393,6 +393,7 @@ The Obsidian plugin drops its old **Repo sync interval** setting on its own. | --- | --- | | 0.6.0 full gate on `release/0.6.0` (2026-11-01, macOS 27 arm64) | Node 26.10.0 at `13f5d8a`: `npm run build`, then `npm test` with `JCODE_SCRATCH_DIR` unset, 644 of 644 with the default macOS `TMPDIR`, with `TMPDIR=/tmp` and with a realpath folder; `npm run test:install` 73 passed, 1 skipped. Node 24.11.0 at `a4a771f` (the commit before the `scope move` warning fix): `npm ci --ignore-scripts`, build, 643 of 643 in the same three settings, installer 73 passed and 1 skipped. On both: `npm run typecheck`, `npm run lint` (33 Markdown files, 64 relative links, 0 broken), `npm run build:npm` built `mozak 0.6.0` and its CLI prints `0.6.0`, and the `release.yml` version check for tag `v0.6.0` (package, root manifest and plugin manifest `0.6.0`, three plugin assets present). A `git grep` over `packages/*/src` finds no `fetch`, `clone`, `ls-remote`, GitHub API or `curl` call reachable from a scope route: the only hits are the vault fast-forward in `local-sync.ts`, mozak's own release check and upgrade, and the `--commit` push in `git-commit.ts`. Linux runs in CI on the pull request. | | 0.6.0 verifiers (same commits) | V-race, V-ref and V-dup tests 41 of 41 on both Node versions. `verify-dup.ts`: precision 1.000, recall 0.988. `verify-latency.ts` (23 synthetic scopes, 230 plans): `plans.md` max 18.4 ms (budget 1000), 460 locators max 24.4 ms (budget 300). V-race 9 at 1018 write attempts (8 writers, kill -9 once per round, rebase on): 642 commits, 0 violations, 31 of 31 locks left by killed writers cleared by `recover`, commit p50 101.5 ms, **p95 245.4 ms** (target 300 ms), max 600.4 ms. V-race 1: flag off 43 of 73 attempts wasted, flag on 0 of 30, 0 lost either way. Old client (`scripts/verify-old-client-sidecar.sh`, temp base now a vault): the 0.5.0 and the 0.4.7 CLI each read, check and write a scope with a sidecar made by the branch, the sidecar is unchanged, and the branch reads one edge with 0 dangling. | +| 0.6.0 on Node 24.11.0 at the final tip, and one V-race 9 flake | `npm test` 644 of 644 with the default `TMPDIR` and with `/tmp`. In the realpath folder one run failed V-race 9 (the 60-attempt kill -9 test) in one round: seven writes got `recovery-required`, which `acquireDirLock` returns when the lock folder exists without a readable `owner.json` past the timeout, the state a writer killed between `mkdir` and writing `owner.json` leaves. The lock code and the test are unchanged since 0.5.0, so this is a timing window the test can hit, not a 0.6.0 change. Five V-race 9 reruns in the same folder: 0 violations, p95 62 to 96 ms; the full suite again there: 644 of 644. A fresh clone of `pitfa19/mozak` with `release/0.6.0` fetched from the bundle: a fast-forward of `main`, build, 644 of 644, installer 73 passed and 1 skipped, lint 0 broken. | | 0.6.0 migration rehearsal (copies only, no network) | A scratch copy of the laptop layout: the mini's two vault clones (git archive of HEAD, the anpit vault at `obsidian/anpit` as on the laptop), the laptop inventory with its home path mapped to the scratch folder, the three code-repo scopes and `~/.atticus` from the laptop copies, and the `anpit-web` cache rebuilt as a 0.5.0 sparse clone with an unreachable origin. A logging `curl` and a git URL rewrite blocked the network; nothing tried it. Before: 0.5.0 lists 31 scopes, 0 failed. The branch lists the same copy with `mozak`, `obsidian-plugins-mcp` and `anpit-web` as `legacy-repo-scope` and `redumenzi`, `proinz-spasizalogaj`, `atticus-jcode-bridge` and `atticus-jcode` as `scope-outside-vault`, each message naming its `mozak scope move` command, and every other scope ok. The owner's moves with `--dry-run` left the inventory byte-identical, then for real: `redumenzi` and `atticus-jcode-bridge` to `creations/`, `proinz-spasizalogaj` to `personal/fakultet/`, `anpit-web` to `anpit/projects/` (warning `source-lock-not-ignored`), `atticus-jcode` dropped (0 plans), `mozak` and `obsidian-plugins-mcp` rewritten in place. After: 30 scopes, 0 failed; plan counts per scope, the 52 unique plans in 38 `plans --all` group cells, and every scope's revision and graph hash equal the 0.5.0 output; `check` exit 0 on all 30; all 31 `mozak.md` files byte-identical and the 16 moved files equal their sources, which stay in place; every other inventory entry unchanged, the moved ones are `{ id, root }` only. 0.5.0 reads the migrated copy with 0 failed and the same groups. `atticus-jcode-bridge` warns `spec-not-moved` for `docs/spec-bridge-v1.md`. `mozak-inventory-sync --transform` maps the migrated inventory, with `repo` links added, to the mini's paths: 30 scopes, no legacy keys, links kept, and the branch reads it with 0 failed. `context --brief` on the copied `mozak` scope: 5912 bytes. | | 0.6.0 upgrade rehearsal (scratch prefix and vault) | A local mirror with `v0.5.0` and `release/0.6.0` tagged `v0.6.0` there only. 0.5.0 built from the tag and installed into a scratch prefix with its plugin in a scratch vault. `mozak upgrade --check`: 0.5.0 to 0.6.0. `mozak upgrade --vault`: `upgraded`, `mozak --version` 0.6.0, the plugin in the scratch vault 0.5.0 to 0.6.0, the old install kept as `mozak.previous-0.5.0`, the source checkout back on its branch and clean, and a second run `up-to-date`. On the pre-0.6 inventory the vault scope reads ok and the code-folder scope is `scope-outside-vault`; `mozak doctor` fails the inventory check with the exact `scope move` command. | | 0.5.0 full gate on `release/0.5.0` (`9c26892`, 2026-11-01, macOS 27 arm64, Node 26.10.0 and Node 24.11.0) | Passed on both Node versions: `npm ci --ignore-scripts`, `npm run build`, then `npm test` with `JCODE_SCRATCH_DIR` unset, 630 of 630 with the default macOS `TMPDIR`, with `TMPDIR=/tmp` and with a realpath folder. `npm run test:install` 73 passed, 1 skipped (case-collision test needs a case-sensitive filesystem). `npm run typecheck` and `npm run lint` (33 Markdown files, 61 relative links, 0 broken) passed. `npm run build:npm` built `mozak 0.5.0` and its CLI prints `0.5.0`. The version check from `release.yml`, run locally for tag `v0.5.0`: package, root manifest and plugin manifest all `0.5.0`, all three plugin assets present. Linux runs in CI on the pull request. | From acb033e36c33490654314dd720040df225dd9660 Mon Sep 17 00:00:00 2001 From: pitfa19 <166558275+pitfa19@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:23:07 +0100 Subject: [PATCH 10/10] Record the 0.6.0 end-user path: npm tarball install, scope move, link, sync between two clones, MCP Docs only. Log: logs/09-e2e-npm.log in the release work folder. --- docs/installation.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/installation.md b/docs/installation.md index 1db8ea1..8446b9c 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -393,6 +393,7 @@ The Obsidian plugin drops its old **Repo sync interval** setting on its own. | --- | --- | | 0.6.0 full gate on `release/0.6.0` (2026-11-01, macOS 27 arm64) | Node 26.10.0 at `13f5d8a`: `npm run build`, then `npm test` with `JCODE_SCRATCH_DIR` unset, 644 of 644 with the default macOS `TMPDIR`, with `TMPDIR=/tmp` and with a realpath folder; `npm run test:install` 73 passed, 1 skipped. Node 24.11.0 at `a4a771f` (the commit before the `scope move` warning fix): `npm ci --ignore-scripts`, build, 643 of 643 in the same three settings, installer 73 passed and 1 skipped. On both: `npm run typecheck`, `npm run lint` (33 Markdown files, 64 relative links, 0 broken), `npm run build:npm` built `mozak 0.6.0` and its CLI prints `0.6.0`, and the `release.yml` version check for tag `v0.6.0` (package, root manifest and plugin manifest `0.6.0`, three plugin assets present). A `git grep` over `packages/*/src` finds no `fetch`, `clone`, `ls-remote`, GitHub API or `curl` call reachable from a scope route: the only hits are the vault fast-forward in `local-sync.ts`, mozak's own release check and upgrade, and the `--commit` push in `git-commit.ts`. Linux runs in CI on the pull request. | | 0.6.0 verifiers (same commits) | V-race, V-ref and V-dup tests 41 of 41 on both Node versions. `verify-dup.ts`: precision 1.000, recall 0.988. `verify-latency.ts` (23 synthetic scopes, 230 plans): `plans.md` max 18.4 ms (budget 1000), 460 locators max 24.4 ms (budget 300). V-race 9 at 1018 write attempts (8 writers, kill -9 once per round, rebase on): 642 commits, 0 violations, 31 of 31 locks left by killed writers cleared by `recover`, commit p50 101.5 ms, **p95 245.4 ms** (target 300 ms), max 600.4 ms. V-race 1: flag off 43 of 73 attempts wasted, flag on 0 of 30, 0 lost either way. Old client (`scripts/verify-old-client-sidecar.sh`, temp base now a vault): the 0.5.0 and the 0.4.7 CLI each read, check and write a scope with a sidecar made by the branch, the sidecar is unchanged, and the branch reads one edge with 0 dangling. | +| 0.6.0 end-user path (npm tarball, scratch prefix and `HOME`) | `npm run build:npm` and `npm pack` gave `mozak-0.6.0.tgz` (210,107 bytes), installed with `npm install -g` into a scratch prefix. Through the installed `mozak`: a scope in a code folder is `scope-outside-vault` with the move command; `scope move --dry-run` leaves the inventory unchanged; the move writes `{ id, root, focus }` with the focus kept, `mozak.json` and `mozak.md` byte-identical, old files kept, a second run `changed: false`; `scope link` adds `repo` and `scopes` prints it; `observe` turns the outcome done; a stale propose exits 3; `pull` is an unknown route; `context` without `--scope` says `missing --scope`. Two clones of one vault repo: `observe --commit` on one pushed, `mozak sync` on the other `fast-forwarded`, and its `check` is clean. `mozak-mcp` over stdio: server `mozak 0.6.0`, 17 tools, no sync or pull tool, `mozak_sync` is an unknown tool, `mozak_scopes` shows the repo link. The built plugin bundle has no repo-scope code (`remotePollSeconds` appears once, in the settings migration that drops it). A moved scope in a vault repo with no root ignore rule for `.mozak-write-lock/` gets a `lock-not-ignored` check finding (the per-scope `.gitignore` that `init` writes is not moved); both real vaults ignore it at their root, and the migrated rehearsal copy inside git repos with those `.gitignore` files checks clean on all 30 scopes. | | 0.6.0 on Node 24.11.0 at the final tip, and one V-race 9 flake | `npm test` 644 of 644 with the default `TMPDIR` and with `/tmp`. In the realpath folder one run failed V-race 9 (the 60-attempt kill -9 test) in one round: seven writes got `recovery-required`, which `acquireDirLock` returns when the lock folder exists without a readable `owner.json` past the timeout, the state a writer killed between `mkdir` and writing `owner.json` leaves. The lock code and the test are unchanged since 0.5.0, so this is a timing window the test can hit, not a 0.6.0 change. Five V-race 9 reruns in the same folder: 0 violations, p95 62 to 96 ms; the full suite again there: 644 of 644. A fresh clone of `pitfa19/mozak` with `release/0.6.0` fetched from the bundle: a fast-forward of `main`, build, 644 of 644, installer 73 passed and 1 skipped, lint 0 broken. | | 0.6.0 migration rehearsal (copies only, no network) | A scratch copy of the laptop layout: the mini's two vault clones (git archive of HEAD, the anpit vault at `obsidian/anpit` as on the laptop), the laptop inventory with its home path mapped to the scratch folder, the three code-repo scopes and `~/.atticus` from the laptop copies, and the `anpit-web` cache rebuilt as a 0.5.0 sparse clone with an unreachable origin. A logging `curl` and a git URL rewrite blocked the network; nothing tried it. Before: 0.5.0 lists 31 scopes, 0 failed. The branch lists the same copy with `mozak`, `obsidian-plugins-mcp` and `anpit-web` as `legacy-repo-scope` and `redumenzi`, `proinz-spasizalogaj`, `atticus-jcode-bridge` and `atticus-jcode` as `scope-outside-vault`, each message naming its `mozak scope move` command, and every other scope ok. The owner's moves with `--dry-run` left the inventory byte-identical, then for real: `redumenzi` and `atticus-jcode-bridge` to `creations/`, `proinz-spasizalogaj` to `personal/fakultet/`, `anpit-web` to `anpit/projects/` (warning `source-lock-not-ignored`), `atticus-jcode` dropped (0 plans), `mozak` and `obsidian-plugins-mcp` rewritten in place. After: 30 scopes, 0 failed; plan counts per scope, the 52 unique plans in 38 `plans --all` group cells, and every scope's revision and graph hash equal the 0.5.0 output; `check` exit 0 on all 30; all 31 `mozak.md` files byte-identical and the 16 moved files equal their sources, which stay in place; every other inventory entry unchanged, the moved ones are `{ id, root }` only. 0.5.0 reads the migrated copy with 0 failed and the same groups. `atticus-jcode-bridge` warns `spec-not-moved` for `docs/spec-bridge-v1.md`. `mozak-inventory-sync --transform` maps the migrated inventory, with `repo` links added, to the mini's paths: 30 scopes, no legacy keys, links kept, and the branch reads it with 0 failed. `context --brief` on the copied `mozak` scope: 5912 bytes. | | 0.6.0 upgrade rehearsal (scratch prefix and vault) | A local mirror with `v0.5.0` and `release/0.6.0` tagged `v0.6.0` there only. 0.5.0 built from the tag and installed into a scratch prefix with its plugin in a scratch vault. `mozak upgrade --check`: 0.5.0 to 0.6.0. `mozak upgrade --vault`: `upgraded`, `mozak --version` 0.6.0, the plugin in the scratch vault 0.5.0 to 0.6.0, the old install kept as `mozak.previous-0.5.0`, the source checkout back on its branch and clean, and a second run `up-to-date`. On the pre-0.6 inventory the vault scope reads ok and the code-folder scope is `scope-outside-vault`; `mozak doctor` fails the inventory check with the exact `scope move` command. |