layerfs 0.9.0: commits name their calling agent, trajectory reads each record once (#365)

layerfs 0.9.0 (sim-only): each provision, checkpoint, fork, publish and exec records the calling agent from the tool host's ctx.agent, and the page names it, ahead of the branch-name guess. trajectory() reads each commit record once per backend lifetime (summaries cached, manifest left out) and yields between branches, so a rebuild reads only new commits. Native backend requests are still refused loudly.

Run at e3c7ee94 (macOS): bun test packages/layerfs 57 pass (2 of 3 runs; the third hit ENOSPC on a full disk in 4 #360/accounting tests that pass in the others); origin/main 53 pass. bun scripts/check.mjs layerfs ok. Checked that magpie's host.js runTool passes ctx.agent as execute's second argument.
Not tried: the page in the real magpie app with a live agent.
This commit is contained in:
mola
2026-10-26 18:11:30 +08:00
committed by GitHub
parent 60a2d6e2e2
commit 03f5952a8b
9 changed files with 301 additions and 138 deletions
+78 -27
View File
@@ -84,22 +84,23 @@ defaults here are set for that room, not for a private library:
past it.
- **Secret-shaped files never enter the store from an import**:
`.git`, `.env*`, private keys (`id_rsa`, `id_ed25519`, `*.pem`,
`*.key`, …), `.ssh`, `.aws`. The import skips them and reports how
many. Imports are also bounded (20,000 files / 512 MiB) and fail
loudly past the limit instead of sweeping a disk.
`*.key`, …), `.ssh`, `.aws`. The sim backend skips them and reports
how many. Imports are
also bounded (20,000 files / 512 MiB) and fail loudly past the limit
instead of sweeping a disk.
- **The store is private.** Its root and directories are created
`0700`, its record files `0600`, whatever the umask says; a file's
own mode is preserved through the store (a `0600` file is stored
own mode is preserved through the sim store (a `0600` file is stored
and materialized as `0600`).
- **`exec` is disabled by default.** It runs a shell with the plugin
host's privileges; a model key should not silently become host
shell access. The user enables it with the plugin's `"exec"`
option (set to `true` in magpie's plugin options) or
`MAGPIE_LAYERFS_EXEC=1` in the host's environment.
- **Re-provisioning never wipes a workspace.** When a branch has
moved since its workspace was materialized, provision keeps the
workspace's files and reports `stale: true` instead of deleting
uncheckpointed work.
- **Re-provisioning a moved branch keeps the workspace.** When a
branch has moved since its checkout, re-provisioning keeps the
workspace's files and reports `stale: true` instead of wiping the
directory.
## Benchmark
@@ -124,9 +125,15 @@ per-agent copy, the per-snapshot copy, and the bytes they waste — the
engine's own benchmarks are at
[layerfs.ai/benchmarks](https://layerfs.ai/benchmarks/).
The same scenario against the real engine (the native backend, in
the standalone repo): the engine's store file held **5.6 MB for
513 MB of logical checkpoints** on a compressible text fixture —
Against the real engine
([`bench/bench-native.mjs`](https://github.com/Mola-maker/magpie-layerfs/blob/main/bench/bench-native.mjs),
native backend, same scenario, generated-text fixture of 184 files /
27.0 MB): import
3.6 s once; a fork plus its checkout 1.8 s (the branch itself is
metadata; the checkout pays the file reads); a checkpoint 1.9 s (the
checkout diff reads the branch back through the fs surface, then one
`fs.apply` lands it); the engine's store file held **5.6 MB for
513 MB of logical checkpoints** on this compressible text fixture —
the sim fixture above is random bytes, the incompressible extreme, so
read the two ratios as the ends of a range, not a single number.
@@ -176,35 +183,79 @@ and its test asserts it asks for none.
## Develop
From a checkout of
[magpie-community/plugins](https://github.com/magpie-community/plugins),
in `packages/layerfs`:
From a checkout of [this repo](https://github.com/Mola-maker/magpie-layerfs)
(the registry package ships only the runtime files):
```sh
bun test # the suite (bun:test): tools end to end, plus the page's layout math
bun bench/bench.mjs # the benchmark above; writes bench/results.json
node tools/gen-trajectory.mjs # regenerate the page's bundled sample trajectory
```
The benchmark above and the sample-trajectory generator live in the
standalone repo,
[Mola-maker/magpie-layerfs](https://github.com/Mola-maker/magpie-layerfs),
which is also where the native backend is developed.
Zero runtime dependencies; the arguments are JSON Schema, like the other
tools packages. MIT.
## Changes in 0.9.0
The registry package is sim-only now. The native backend — the
standalone repo's LayerFS 1.1.0 port, with the SDK split into
`@layerfs/agent`, `@layerfs/backend` and `@layerfs/runtime`, the
`LayerFS.open` / `LayerFS.init` factories and the child-process
worker — stays in the standalone repo until the SDK is published
to npm and this package can pin it; the registry review asked for
the native path to stay out until then, so `native-worker.mjs`
and the fake SDK are gone from this package, the `"native"` plugin
option is gone, and a native request is refused instead of
silently running sim.
The page's live file is gone with it: the registry review asked
for no writes into the installed plugin's folder, so the tools no
longer write `page/trajectory-live.js` at runtime and the page is
back to the bundled sample (the 0.7.1 position — a magpie page
cannot read plugin-private data, and the bridge's reads are a
fixed host list). The live trajectory stays available through the
tools and through `backend.trajectory()`, which now caches every
commit's summary (everything but the manifest, which it never
uses) per project/id: a rebuild reads only commits it has never
seen, and a rebuild with nothing new reads no records at all (a
test counts the reads to pin that). Between branches the walk
yields, so even a first build over a large store never holds the
shared plugin host's event loop for its whole duration.
## Changes in 0.8.0
0.8.0 gave the page the real trajectory. The 0.7.x page could only
animate the bundled sample — a magpie page cannot fetch, and the
bridge's reads are a fixed host list — so the live picture the tools
held never reached it. The channel was there all along, though:
magpie serves a page's files from the plugin's folder as they sit on
disk, per request. So:
- **The page's live file.** After any provision, fork, checkpoint,
publish or exec lands, the tools rebuild the trajectory on demand
(`backend.trajectory()`) and write it, tmp-then-renamed, to
`page/trajectory-live.js` in the plugin's own folder — debounced,
off the tool calls' path, errors swallowed (the page keeps its
last file; the calls are untouched). The page loads it after the
bundled sample and prefers it. An empty store writes an empty
live file, and the page shows its honest empty state instead of
the demo; the sample remains what a store the tools have never
written shows.
Registry review (PR #365) asked for no writes into the installed
plugin's folder, so 0.9.0 removes the live file again and the
page is back to the bundled sample.
- **The real agent on every commit.** The tools record the calling
agent — the tool host's `ctx.agent`, the gateway's name for the
agent that made the call — on the events and commits each call
creates. The page prefers it over the branch-name token guess: a
claude badge lands where claude actually checkpointed, even on
`main`, and the detail card names the agent.
## Changes in 0.7.1
The second round of the PR #318 review — the holes it found in
0.7.0's own new code, plus its smaller items:
- **This package is sim-only.** The native backend was removed from
the magpie-community package (the review's condition for keeping
it — a pinned, integrity-checked npm dependency — cannot exist
while `@layerfs/sdk` is not on npm). It lives in the standalone
repo and returns in a follow-up PR once the SDK is published with
a version to pin; asking for it here is an explicit error.
`package.json`'s `repository` now names this repo, with
`"directory": "packages/layerfs"`, like every other package here.
- **The source guard compares real paths now.** 0.7.0 compared
`resolve()`d strings, which a symlink to a refused directory — or
a case-variant spelling of one on a case-insensitive volume —
+36 -30
View File
@@ -4,12 +4,18 @@
// agent copies no file bytes; a checkpoint stores only what changed.
// Arguments are JSON Schema, so the package needs no dependency.
//
// Backend: a local content-addressed store implementing the LayerFS
// model. This package is sim-only — the native backend (the real
// LayerFS through its SDK) is developed in the standalone repo
// (Mola-maker/magpie-layerfs) and returns in a follow-up PR once
// @layerfs/sdk is published to npm with a version to pin. See
// layerfs.mjs and the README.
// The page shows the trajectory bundled with the package (page/trajectory.js,
// a labeled sample): the tools never write into the plugin's install
// folder, so no runtime live file exists there — an update replaces
// that folder, two hosts sharing one install would race on the file,
// and an install can be read-only. The live trajectory stays available
// through the tools (history, status) and through backend.trajectory().
// See the README's page section.
//
// Backend: a local content-addressed store with the LayerFS model, in
// layerfs.mjs. The native backend (the real LayerFS SDK) is not shipped
// in this registry package — the SDK is still not published to npm —
// and returns once the plugin can pin it as a dependency. See the README.
import { checkBranch, checkInnerPath, checkProject, checkSourceDir, createBackend } from "./layerfs.mjs"
const str = (v, name) => {
@@ -18,22 +24,22 @@ const str = (v, name) => {
}
const opt = (v, name, dflt) => (v === undefined || v === "" ? dflt : str(v, name))
// The plugin's options: magpie hands a plugin its options (the
// magpie.options defaults in package.json, as the user set them) as
// the plugin function's second argument. One of them is a switch
// only the user may flip, because it widens what these tools can do
// with the host's rights: "exec" (run shell commands). The
// MAGPIE_LAYERFS_EXEC environment variable is the same switch for
// hosts that do not pass options.
// The calling agent, as the gateway knows it (the tool host's ctx.agent):
// the one field of a tool call that says WHO made it. Trimmed and capped,
// then recorded on the events and commits the call creates — the page
// attributes the work to the agent that actually made it, not to a token
// guessed from the branch name.
const callingAgent = (ctx) => {
const a = ctx?.agent
return typeof a === "string" && a.trim() ? a.trim().slice(0, 40) : ""
}
export const LayerfsTools = async (ctx = {}, options = {}) => {
let backendPromise
const backend = () => (backendPromise ??= createBackend(process.env, options))
const execEnabled = () => options?.exec === true || process.env.MAGPIE_LAYERFS_EXEC === "1"
// A call touches only the state its own operation needs. Nothing
// here maintains a recorded trajectory file: an earlier version
// refreshed one in the store after every call, at a cost that grew
// with the project's history, for a file the page cannot read — the
// trajectory is built on demand by the backend when asked (0.7.1).
// A call touches only the state its own operation needs. Reads (history,
// resolve, status) change nothing and refresh nothing.
const call = async (fn) => {
const b = await backend()
return fn(b)
@@ -47,7 +53,7 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
"The first provision of a project imports the source directory the caller passes — source is required, there is no default — as its first checkpoint; " +
"later provisions of the same branch answer the same path without copying the tree again (source is then ignored). " +
"Pass the directory the user chose for this project: the app's config directory, credential stores (.ssh, .aws, .gnupg), the home directory and the plugin's own store are refused as sources, " +
"and secret-shaped files in the tree (.env*, private keys, .git internals) never enter the store — the import skips them and reports how many. " +
"and secret-shaped files in the tree (.env*, private keys, .git internals) never enter the store — the sim backend skips them on import and reports how many. " +
"Work in the returned path, then save progress with the checkpoint tool. " +
"Only the returned path is persistent — work anywhere else, including the host's /tmp, is outside LayerFS management; " +
"the workspace also carries .tmp/ and .cache/ scratch directories (exec points TMPDIR and XDG_CACHE_HOME at them), which checkpoint and publish never capture.",
@@ -60,7 +66,7 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
},
required: ["project", "source"],
},
async execute(args) {
async execute(args, callCtx) {
const project = checkProject(str(args.project, "project"))
const branch = checkBranch(opt(args.branch, "branch", "main"))
// ctx.directory is magpie's config directory, never a default
@@ -69,7 +75,7 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
if (args.source === undefined) throw new Error(
"source is required: the directory to import when the project is first created — pass the directory the user chose for this project")
const source = checkSourceDir(str(args.source, "source"), { configDir: ctx.directory })
return call((b) => b.provision(project, branch, source))
return call((b) => b.provision(project, branch, source, callingAgent(callCtx)))
},
},
checkpoint: {
@@ -87,10 +93,10 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
},
required: ["project"],
},
async execute(args) {
async execute(args, callCtx) {
const project = checkProject(str(args.project, "project"))
const branch = checkBranch(opt(args.branch, "branch", "main"))
return call((b) => b.checkpoint(project, branch, opt(args.message, "message", "")))
return call((b) => b.checkpoint(project, branch, opt(args.message, "message", ""), callingAgent(callCtx)))
},
},
fork: {
@@ -106,11 +112,11 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
},
required: ["project", "branch"],
},
async execute(args) {
async execute(args, callCtx) {
const project = checkProject(str(args.project, "project"))
const branch = checkBranch(str(args.branch, "branch"))
const from = checkBranch(opt(args.from, "from", "main"))
return call((b) => b.fork(project, branch, from))
return call((b) => b.fork(project, branch, from, callingAgent(callCtx)))
},
},
publish: {
@@ -127,10 +133,10 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
},
required: ["project", "branch"],
},
async execute(args) {
async execute(args, callCtx) {
const project = checkProject(str(args.project, "project"))
const branch = checkBranch(str(args.branch, "branch"))
return call((b) => b.publish(project, branch, { force: args.force === true }))
return call((b) => b.publish(project, branch, { force: args.force === true, agent: callingAgent(callCtx) }))
},
},
exec: {
@@ -153,7 +159,7 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
},
required: ["project", "command"],
},
async execute(args) {
async execute(args, callCtx) {
if (!execEnabled()) throw new Error(
"layerfs_exec is disabled by default: it runs shell commands with the plugin host's privileges, and these tools are reachable by any caller holding a gateway key. " +
"To enable it, the user sets the plugin's \"exec\" option to true in the host's plugin options, or turns on the exec switch in the plugin host's environment (see the package's README), and restarts the host.")
@@ -162,7 +168,7 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
const command = str(args.command, "command")
const message = args.message === undefined ? "" : str(args.message, "message")
const timeoutMs = args.timeoutMs === undefined ? 50000 : Number(args.timeoutMs) || 50000
return call((b) => b.exec(project, branch, command, message, timeoutMs))
return call((b) => b.exec(project, branch, command, message, timeoutMs, callingAgent(callCtx)))
},
},
history: {
@@ -208,7 +214,7 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
},
status: {
description:
"Reports the LayerFS backend in use (sim in this package), the projects and branches it holds, and the storage accounting: " +
"Reports the LayerFS backend in use, the projects and branches it holds, and the storage accounting: " +
"the logical bytes of every checkpoint ever taken against the bytes the deduplicated store actually occupies, and the ratio between them.",
args: { type: "object", properties: {} },
async execute() {
+86 -50
View File
@@ -1,21 +1,20 @@
// The LayerFS backend for the magpie tools plugin — one backend
// behind a small surface (provision, checkpoint, fork, publish, exec,
// history, resolve, status):
// LayerFS backend for the magpie tools plugin.
//
// - sim: a local content-addressed store that implements the model
// LayerFS is built on — immutable blobs named by their SHA-256,
// branches as manifest pointers, checkpoints as deduplicated
// manifests — so the plugin runs and can be tested anywhere.
// Forking a branch copies no file bytes; a checkpoint stores only
// the blobs the store has not seen.
// One backend sits behind the small surface (provision, checkpoint, fork,
// history, resolve, status): sim, a local content-addressed store that
// implements the same model LayerFS is built on — immutable blobs named
// by their SHA-256, branches as manifest pointers, checkpoints as
// deduplicated manifests — so the plugin runs and can be tested
// anywhere. Forking a branch copies no file bytes; a checkpoint stores
// only the blobs the store has not seen.
//
// This package is SIM-ONLY. The native backend (the real LayerFS,
// through the `@layerfs/sdk` JavaScript SDK) was removed from the
// magpie-community package in 0.7.1: shipping it needs a pinned,
// integrity-checked npm dependency, and the SDK is not published to
// npm. It is developed in the standalone repo
// (Mola-maker/magpie-layerfs) and returns in a follow-up PR once the
// SDK is published with a version to pin — see createBackend below.
// The native backend — the real LayerFS through its JavaScript SDK —
// is NOT shipped in this registry package: the SDK is still not
// published to npm, so there is no pinned version to depend on, and
// the registry package must not load unversioned code from a path the
// user's environment names. It lives in the standalone repo
// (Mola-maker/magpie-layerfs) and returns here once the SDK is
// published and the plugin can depend on a pinned version.
//
// Environment:
// MAGPIE_LAYERFS_BACKEND auto (default) | sim — "native" is an
@@ -362,6 +361,10 @@ export class SimBackend {
this.objectsDir = join(this.root, "store", "objects")
this.projectsDir = join(this.root, "projects")
this.workspacesDir = join(this.root, "workspaces")
// Commit summaries for trajectory(): records never change once
// written, so a summary (everything but the manifest) is cached
// per project/id for the life of this backend
this._commitSummary = new Map()
for (const d of [this.root, this.objectsDir, this.projectsDir, this.workspacesDir]) mkdirPrivate(d)
// Seed the byte accounting before anything writes, so the bumps
// below stay exact (a walk taken after a write would count it twice)
@@ -453,6 +456,26 @@ export class SimBackend {
projectExists(project) { return existsSync(join(this.projectDir(project), "project.json")) }
commitPath(project, id) { return join(this.projectDir(project), "commits", `${id}.json`) }
readCommit(project, id) { return JSON.parse(readFileSync(this.commitPath(project, id), "utf8")) }
// A commit's summary: everything trajectory() shows, without the
// manifest — the big part, which trajectory never uses. The walk
// below reads each record once per backend lifetime; later rebuilds
// hit this map and touch no files, so a host-shared plugin host is
// stalled only by genuinely new commits, never by re-reading history.
readCommitSummary(project, id) {
const key = `${project}/${id}`
let s = this._commitSummary.get(key)
if (!s) {
const c = this.readCommit(project, id)
s = {
id: c.id, parent: c.parent, branch: c.branch, message: c.message, time: c.time,
files: c.files, logicalBytes: c.logicalBytes, newBytes: c.newBytes,
delta: c.delta ?? { added: 0, modified: 0, deleted: 0 },
...(c.agent ? { agent: c.agent } : {}),
}
this._commitSummary.set(key, s)
}
return s
}
writeCommit(project, commit) {
mkdirPrivate(join(this.projectDir(project), "commits"))
writeJson(this.commitPath(project, commit.id), commit, true)
@@ -474,13 +497,14 @@ export class SimBackend {
return readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => decodeBranchName(f.slice(0, -5))).sort()
}
makeCommit(project, branch, parent, manifest, message, newBytes, delta = { added: 0, modified: 0, deleted: 0 }) {
makeCommit(project, branch, parent, manifest, message, newBytes, delta = { added: 0, modified: 0, deleted: 0 }, agent = "") {
const seed = JSON.stringify({ parent, branch, message, manifest }) + nowIso() + Math.random()
const id = sha256(Buffer.from(seed)).slice(0, 12)
const commit = {
id, branch, parent, message, time: nowIso(),
manifest, files: Object.keys(manifest).length,
logicalBytes: manifestBytes(manifest), newBytes, delta,
...(agent ? { agent } : {}),
}
const recordBytes = this.writeCommit(project, commit)
this.bumpAccounting({ logicalDelta: commit.logicalBytes, storedDelta: recordBytes })
@@ -489,7 +513,10 @@ export class SimBackend {
}
// An append-only event log (provision / fork / checkpoint), the raw
// material for the trajectory the magpie page replays.
// material for the trajectory the magpie page replays. agent is the
// calling agent as the gateway knows it (the tool host's ctx.agent),
// when the caller passed one — the page attributes the work to the
// agent that actually made it, not to a branch name's token.
recordEvent(event) {
const path = join(this.root, "events.json")
let events = []
@@ -502,7 +529,7 @@ export class SimBackend {
try { return JSON.parse(readFileSync(join(this.root, "events.json"), "utf8")) } catch { return [] }
}
async ensureProject(project, sourceDir) {
async ensureProject(project, sourceDir, agent = "") {
if (this.projectExists(project)) return { created: false }
mkdirPrivate(this.projectDir(project))
writeJson(join(this.projectDir(project), "project.json"),
@@ -520,14 +547,14 @@ export class SimBackend {
}
const commit = this.makeCommit(project, "main", null, manifest,
src ? `Import ${src}` : "Empty project", newBytes,
{ added: Object.keys(manifest).length, modified: 0, deleted: 0 })
{ added: Object.keys(manifest).length, modified: 0, deleted: 0 }, agent)
return { created: true, commit: commit.id, skipped }
}
workspaceDir(project, branch) { return join(this.workspacesDir, project, encodeBranchName(branch)) }
async provision(project, branch = "main", sourceDir) {
const created = await this.ensureProject(project, sourceDir)
async provision(project, branch = "main", sourceDir, agent = "") {
const created = await this.ensureProject(project, sourceDir, agent)
if (!this.branchExists(project, branch)) throw new Error(`no branch ${branch} in project ${project}`)
const headId = this.head(project, branch)
const dir = this.workspaceDir(project, branch)
@@ -548,7 +575,7 @@ export class SimBackend {
chmodSync(out, f.mode ?? 0o644) // the manifest's mode, not the blob's or the umask's
}
writeJson(join(dir, BINDING), { project, branch, baseCommit: headId }, true)
this.recordEvent({ kind: "provision", project, branch, path: dir, commit: headId })
this.recordEvent({ kind: "provision", project, branch, path: dir, commit: headId, agent })
return {
path: dir, project, branch, backend: this.kind, commit: headId,
reused: false, files: commit.files, logicalBytes: commit.logicalBytes,
@@ -560,7 +587,7 @@ export class SimBackend {
}
}
async checkpoint(project, branch = "main", message = "") {
async checkpoint(project, branch = "main", message = "", agent = "") {
const dir = this.workspaceDir(project, branch)
if (!existsSync(join(dir, BINDING))) throw new Error(`no workspace for ${project}/${branch}; provision it first`)
const parent = this.head(project, branch)
@@ -573,8 +600,8 @@ export class SimBackend {
else if (prev.manifest[rel].sha !== f.sha) modified++
}
for (const rel of Object.keys(prev.manifest)) if (!manifest[rel]) deleted++
const commit = this.makeCommit(project, branch, parent, manifest, message || "Checkpoint", newBytes, { added, modified, deleted })
this.recordEvent({ kind: "checkpoint", project, branch, commit: commit.id, message: commit.message })
const commit = this.makeCommit(project, branch, parent, manifest, message || "Checkpoint", newBytes, { added, modified, deleted }, agent)
this.recordEvent({ kind: "checkpoint", project, branch, commit: commit.id, message: commit.message, agent })
writeJson(join(dir, BINDING), { project, branch, baseCommit: commit.id }, true)
const stored = this.storedBytes()
return {
@@ -585,12 +612,12 @@ export class SimBackend {
}
}
async fork(project, branch, from = "main") {
async fork(project, branch, from = "main", agent = "") {
if (!this.projectExists(project)) throw new Error(`no project ${project}`)
if (this.branchExists(project, branch)) throw new Error(`branch ${branch} already exists in project ${project}`)
const headId = this.head(project, from)
this.setHead(project, branch, headId)
this.recordEvent({ kind: "fork", project, branch, from, commit: headId })
this.recordEvent({ kind: "fork", project, branch, from, commit: headId, agent })
return { project, branch, from, commit: headId, copiedBytes: 0 }
}
@@ -600,7 +627,7 @@ export class SimBackend {
// an ancestor of the branch head, so publishing can only ever move
// main forward. force says "I know main has commits this branch never
// saw" — the result then reports what was overwritten.
async publish(project, branch, { force = false } = {}) {
async publish(project, branch, { force = false, agent = "" } = {}) {
checkProject(project); checkBranch(branch)
if (branch === "main") throw new Error("publish names a branch other than main; main is what gets published to")
const branchHead = this.head(project, branch)
@@ -616,7 +643,7 @@ export class SimBackend {
throw new Error(`main has moved since ${branch} forked: main is at ${mainHead}, which is not in ${branch}'s history. Publishing would drop main's newer checkpoints. Fork a fresh branch from main, or pass force: true to overwrite deliberately.`)
this.setHead(project, "main", branchHead)
const layer = layers + 1
this.recordEvent({ kind: "publish", project, branch, commit: branchHead, layer, overwrote: !fastForward })
this.recordEvent({ kind: "publish", project, branch, commit: branchHead, layer, overwrote: !fastForward, agent })
return { project, branch, layer, commit: branchHead, previousMain: mainHead, overwrote: !fastForward }
}
@@ -625,7 +652,7 @@ export class SimBackend {
// mount, run, commit. A command that changes nothing commits nothing;
// a failing command's changes are still checkpointed (they are
// history, and history can be rewound), with its exit code reported.
async exec(project, branch = "main", command, message = "", timeoutMs = 50000) {
async exec(project, branch = "main", command, message = "", timeoutMs = 50000, agent = "") {
checkProject(project); checkBranch(branch)
if (typeof command !== "string" || !command.trim()) throw new Error("command is a non-empty string")
const dir = this.workspaceDir(project, branch)
@@ -636,7 +663,7 @@ export class SimBackend {
const changed = !sameManifest(prev.manifest, manifest)
let commit = null
if (changed) {
const c = await this.checkpoint(project, branch, message || `exec: ${command.trim().slice(0, 60)}`)
const c = await this.checkpoint(project, branch, message || `exec: ${command.trim().slice(0, 60)}`, agent)
commit = c.commit
}
return {
@@ -660,7 +687,13 @@ export class SimBackend {
}
// One project's slice of the recorded trajectory, oldest first per
// branch. Commits carry their delta and byte accounting.
// branch. Commits carry their delta and byte accounting. The walk
// reads through readCommitSummary, so a forked branch does not
// re-read main's history: every record is parsed once per backend
// lifetime, and a rebuild after a new checkpoint reads only the new
// commits. Between branches the walk yields, so even a first build
// over a large store never holds the shared plugin host's event
// loop for its whole duration.
async trajectoryProject(name) {
if (!this.projectExists(name)) return null
const branches = []
@@ -672,22 +705,28 @@ export class SimBackend {
const commits = []
let id = this.head(name, branch)
while (id) {
const c = this.readCommit(name, id)
const c = this.readCommitSummary(name, id)
if (c.branch === branch) {
commits.push({
id: c.id, parent: c.parent, message: c.message, time: c.time,
files: c.files, logicalBytes: c.logicalBytes, newBytes: c.newBytes,
delta: c.delta ?? { added: 0, modified: 0, deleted: 0 },
delta: c.delta,
...(c.agent ? { agent: c.agent } : {}),
})
}
id = c.parent
}
branches.push({ name: branch, commits: commits.reverse() })
await new Promise((r) => setImmediate(r))
}
return { name, branches }
}
// The whole recorded trajectory: what the magpie page replays.
// The walk is cheap after the first build: readCommitSummary caches
// every record's summary, so a rebuild reads only commits it has
// never seen — a second rebuild with nothing new reads no records
// at all (a test pins that). The stamp itself is always fresh.
async trajectory() {
const projects = []
if (existsSync(this.projectsDir)) {
@@ -758,18 +797,14 @@ export class SimBackend {
// ---- selection ---------------------------------------------------------------------
// This package is SIM-ONLY (0.7.1, round-2 review item 4). The native
// backend — the real LayerFS through its JavaScript SDK — was removed
// from the magpie-community package: the condition for shipping it is
// a pinned, integrity-checked npm dependency, and @layerfs/sdk is not
// published to npm, so no version exists to pin. It is developed in
// the standalone repo (Mola-maker/magpie-layerfs) and returns here in
// a follow-up PR once the SDK is published with a version to pin.
// Asking for it — by MAGPIE_LAYERFS_BACKEND=native, by
// MAGPIE_LAYERFS_NATIVE=1, or by the old "native" plugin option — is
// an explicit, loud error, never a silent fall back to sim.
const SIM_ONLY_NATIVE_ERROR =
"this package is sim-only: the native LayerFS backend is not part of it " +
// The registry package ships the sim backend only. A native request
// is refused loudly, never silently substituted: the SDK is still not
// published to npm, so there is no pinned version to run, and running
// unversioned code from an environment-named path is what the registry
// review refused. The native backend returns here once the SDK is
// published and the plugin pins it as a dependency.
const NATIVE_NOT_SHIPPED =
"this package is sim-only: the native backend is not shipped in this package " +
"(it returns in a follow-up PR once @layerfs/sdk is published to npm with a version to pin; " +
"it is developed in its standalone repo). " +
"Unset the native backend's environment switches and the \"native\" option to use the sim backend."
@@ -777,7 +812,8 @@ const SIM_ONLY_NATIVE_ERROR =
export async function createBackend(env = process.env, options = {}) {
const want = (env.MAGPIE_LAYERFS_BACKEND || "auto").toLowerCase()
if (want === "native" || env.MAGPIE_LAYERFS_NATIVE === "1" || options?.native === true)
throw new Error(SIM_ONLY_NATIVE_ERROR)
if (want === "sim" || want === "auto") return new SimBackend(env.MAGPIE_LAYERFS_HOME)
throw new Error(`the LayerFS backend setting is auto or sim in this package; got ${JSON.stringify(want)}`)
throw new Error(NATIVE_NOT_SHIPPED)
if (want !== "auto" && want !== "sim")
throw new Error(`the LayerFS backend setting is auto or sim; got ${JSON.stringify(want)}`)
return new SimBackend(env.MAGPIE_LAYERFS_HOME)
}
+67 -22
View File
@@ -47,10 +47,7 @@ async function simTools(opts = { exec: true }) {
const home = mkTmp("layerfs-home-")
process.env.MAGPIE_LAYERFS_HOME = home
process.env.MAGPIE_LAYERFS_BACKEND = "sim"
delete process.env.LAYERFS_SDK_PATH
delete process.env.LAYERFS_STORE_PATH
delete process.env.MAGPIE_LAYERFS_EXEC
delete process.env.MAGPIE_LAYERFS_NATIVE
const src = fixture()
// ctx.directory is magpie's CONFIG directory in the real host — the
// harness models it as its own temp dir, never the source
@@ -343,44 +340,92 @@ test("item 4: the store is private, and a file's mode survives the store", async
expect(mode(join(home, "accounting.json"))).toBe(0o600) // record files stay private
})
test("r2 item 4: this package is sim-only — asking for the native backend is a clear error", async () => {
const sim1 = await createBackend({ MAGPIE_LAYERFS_HOME: mkTmp("layerfs-auto-") })
expect(sim1).toBeInstanceOf(SimBackend)
// an SDK path changes nothing here: auto still means sim
const sim2 = await createBackend({ MAGPIE_LAYERFS_HOME: mkTmp("layerfs-auto-"), LAYERFS_SDK_PATH: "/x/index.js" })
test("the registry package ships the sim backend only; native is refused, never silently substituted", async () => {
const sim = await createBackend({ MAGPIE_LAYERFS_HOME: mkTmp("layerfs-sim-") })
expect(sim).toBeInstanceOf(SimBackend)
// an SDK path lying around changes nothing: there is no native backend to turn on
const sim2 = await createBackend({ MAGPIE_LAYERFS_HOME: mkTmp("layerfs-sim-"), LAYERFS_SDK_PATH: "/x/index.js" })
expect(sim2).toBeInstanceOf(SimBackend)
// every way of asking for native is refused, and says why
await expect(createBackend({ MAGPIE_LAYERFS_BACKEND: "native" })).rejects.toThrow("sim-only")
await expect(createBackend({ MAGPIE_LAYERFS_HOME: mkTmp("layerfs-auto-"), MAGPIE_LAYERFS_NATIVE: "1" }))
.rejects.toThrow("follow-up PR once @layerfs/sdk is published")
await expect(createBackend({ MAGPIE_LAYERFS_HOME: mkTmp("layerfs-auto-") }, { native: true }))
.rejects.toThrow("sim-only")
// an explicit native request — env or option — is refused loudly
await expect(createBackend({ MAGPIE_LAYERFS_BACKEND: "native" })).rejects.toThrow("not shipped")
await expect(createBackend(
{ MAGPIE_LAYERFS_HOME: mkTmp("layerfs-sim-") }, { native: true })).rejects.toThrow("not shipped")
await expect(createBackend({ MAGPIE_LAYERFS_BACKEND: "bogus" })).rejects.toThrow("auto or sim")
})
test("item 8 + r2 item 3: no trajectory file is maintained per call; the trajectory builds on demand", async () => {
const pageFile = join(import.meta.dir, "page", "trajectory.js")
test("item 8 + r2 item 3: no trajectory file in the store, and no tool call writes into the page folder", async () => {
const pageDir = join(import.meta.dir, "page")
const pageFile = join(pageDir, "trajectory.js")
const before = readFileSync(pageFile, "utf8")
const listedBefore = readdirSync(pageDir).sort()
const { call, home } = await simTools()
await call("provision", { project: "website" })
await call("fork", { project: "website", branch: "feat" })
const feat = await call("provision", { project: "website", branch: "feat" })
writeFileSync(join(feat.path, "f.txt"), "f\n")
await call("checkpoint", { project: "website", branch: "feat", message: "work" })
expect(readFileSync(pageFile, "utf8")).toBe(before) // the shipped file is a sample, untouched (item 8)
expect(readFileSync(pageFile, "utf8")).toBe(before) // the shipped sample is untouched (item 8)
// the registry review's install-folder rule: a run of mutating calls
// leaves the page folder exactly as shipped — no live file, no tmp file
expect(readdirSync(pageDir).sort()).toEqual(listedBefore)
// 0.7.0 refreshed <root>/trajectory.json after every call; 0.7.1
// dropped that — the refresh re-walked branch chains per call for a
// file nothing reads (r2 item 3)
// file nothing read (r2 item 3), and nothing writes one now either
expect(existsSync(join(home, "trajectory.json"))).toBe(false)
// the trajectory itself is still there, built when asked
const traj = await new SimBackend(home).trajectory()
const proj = traj.projects.find((p) => p.name === "website")
expect(proj.branches.map((x) => x.name).sort()).toEqual(["feat", "main"])
const featSlice = proj.branches.find((x) => x.name === "feat")
expect(featSlice.commits.at(-1).message).toBe("work")
const proj2 = traj.projects.find((p) => p.name === "website")
expect(proj2.branches.map((x) => x.name).sort()).toEqual(["feat", "main"])
const featSlice2 = proj2.branches.find((x) => x.name === "feat")
expect(featSlice2.commits.at(-1).message).toBe("work")
expect(traj.totals.logicalBytes).toBeGreaterThan(0)
})
test("trajectory() rebuilds read only new commits: a second rebuild reads none", async () => {
const { call, home } = await simTools()
await call("provision", { project: "website" })
const b = new SimBackend(home)
await b.trajectory() // first build parses every record once
// guard: summaries are cached per project/id, so a rebuild with
// nothing new must not touch the store's records again
let reads = 0
const orig = b.readCommit.bind(b)
b.readCommit = (...a) => { reads++; return orig(...a) }
await b.trajectory()
expect(reads).toBe(0)
await call("checkpoint", { project: "website", message: "second" })
reads = 0
const t = await b.trajectory()
const main = t.projects.find((p) => p.name === "website").branches.find((x) => x.name === "main")
expect(main.commits).toHaveLength(2)
expect(main.commits[0].message).toMatch(/^Import /)
expect(main.commits.at(-1).message).toBe("second")
expect(reads).toBe(1) // only the new checkpoint's record
})
test("calls record the real calling agent on commits and events; the trajectory carries it", async () => {
const { call, tool, home } = await simTools()
await call("provision", { project: "website" }) // agent "test" imports main
await call("fork", { project: "website", branch: "claude", from: "main" })
const ws = await call("provision", { project: "website", branch: "claude" })
writeFileSync(join(ws.path, "claude-work.txt"), "claude was here\n")
// a second agent checkpoints on the branch: the commit names the agent that made it
await tool.checkpoint.execute(
{ project: "website", branch: "claude", message: "claude: first edit" },
{ agent: "claude", abort: AbortSignal.timeout(5000) })
const b = new SimBackend(home)
const traj = await b.trajectory()
const proj = traj.projects.find((p) => p.name === "website")
const mainImport = proj.branches.find((x) => x.name === "main").commits[0]
expect(mainImport.agent).toBe("test") // the importing agent, not a guess from the branch name
const claudeCommit = proj.branches.find((x) => x.name === "claude").commits.at(-1)
expect(claudeCommit.agent).toBe("claude")
// events carry it too
const events = b.readEvents()
expect(events.find((e) => e.kind === "provision" && e.branch === "main").agent).toBe("test")
expect(events.find((e) => e.kind === "checkpoint" && e.branch === "claude").agent).toBe("claude")
})
test("items 9+10: slash branches are distinct, flat, and listed everywhere", async () => {
const { call } = await simTools()
await call("provision", { project: "website" })
-1
View File
@@ -34,7 +34,6 @@ test("the errors a call answers name neither magpie nor its settings", async ()
process.env.MAGPIE_LAYERFS_HOME = mk("lfs-home-")
process.env.MAGPIE_LAYERFS_BACKEND = "sim"
delete process.env.MAGPIE_LAYERFS_EXEC
delete process.env.MAGPIE_LAYERFS_NATIVE
const cfg = mk("app-config-")
const { tool } = await LayerfsTools({ directory: cfg }, { exec: false })
const call = (name, args) => tool[name].execute(args, { agent: "test", abort: AbortSignal.timeout(5000) })
+1 -1
View File
@@ -45,5 +45,5 @@
"directory": "packages/layerfs"
},
"type": "module",
"version": "0.7.3"
"version": "0.9.0"
}
+20
View File
@@ -24,6 +24,7 @@ test("the package declares the page magpie shows", () => {
const html = read("index.html")
expect(html).toContain("_magpie/bridge.js") // the host serves the bridge beside every page
expect(html).toContain('src="trajectory.js"')
expect(html).not.toContain("trajectory-live.js") // no runtime live file: the tools never write into the install folder
// the page sandbox forbids inline scripts and any fetch; the only
// data script is the bundled sample trajectory shipped with the page
expect(html).not.toMatch(/<script>(?!\s*src)/)
@@ -276,6 +277,25 @@ test("a checkpoint badge carries its agent's icon, else a monogram, else the lea
expect(V.glyphFor("grok").type).toBe("icon")
})
test("a commit's real calling agent names its badge, ahead of the branch-name token guess", () => {
// claude worked on the release branch: the badge is claude's, not the leaf
const g = V.glyphFor("release", { agent: "claude" })
expect(g.type).toBe("icon")
expect(g.agent.id).toBe("claude")
// the branch-name guess still holds when the commit names no agent
expect(V.glyphFor("release", {}).type).toBe("leaf")
expect(V.glyphFor("release").type).toBe("leaf")
expect(V.glyphFor("claude-fix", { agent: "" }).type).toBe("icon")
// an agent the registry does not know leaves the badge to the branch
// guess (here none), and the detail card says the raw name
expect(V.glyphFor("release", { agent: "aider" }).type).toBe("leaf")
})
test("the detail card names the commit's real agent", () => {
expect(V.detail({ ...project.branches[1].commits[1], agent: "codex" }, "en").agent).toBe("Codex")
expect(V.detail({ ...project.branches[1].commits[1], agent: "aider" }, "en").agent).toBe("aider")
expect(V.detail(project.branches[1].commits[1], "en").agent).toBe("")
})
test("an icon draws itself as its step lands, then its fill fades in", () => {
const d0 = V.iconDraw(0, false)
expect(d0.offset).toBe(1) // nothing of the outline yet
+5 -4
View File
@@ -13,8 +13,9 @@
// a labeled sample from the benchmark run). A magpie page cannot read
// plugin-private data: the bridge's reads are a fixed host list
// (usage:summary, providers:list), and the sandbox allows no fetch.
// The live recording the tools keep lives in the store as
// trajectory.json, next to the store's own data.
// The tools therefore never write a live file into the plugin's
// install folder; the live trajectory stays available through the
// tools (history, status) and backend.trajectory().
(async () => {
const V = globalThis.LayerfsView;
const $ = (id) => document.getElementById(id);
@@ -190,7 +191,7 @@
const anim = el("g", { class: "node" + (n.landing ? " landing" : ""), "data-branch": n.branch }, pos);
el("circle", { r: 12.5, class: "badge-disc", fill: color }, anim);
el("circle", { r: 12.5, class: "badge-ring", fill: "none", stroke: color }, anim);
const face = V.glyphFor(n.branch);
const face = V.glyphFor(n.branch, n.commit);
const ink = V.markInk(color);
const glyphPaths = [];
let glyphMark = null;
@@ -399,7 +400,7 @@
$("dBranch").textContent = `${t.branch}: ${node.branch}` +
(graft ? ` · ${t.graft} L${graft.layer}` : node.branch !== "main" && isTip(node) && !view.L.graftedBranches.has(node.branch) ? ` · ${t.twig}` : "");
$("dMsg").textContent = d.message;
$("dMeta").textContent = d.meta;
$("dMeta").textContent = [d.agent, d.meta].filter(Boolean).join(" · ");
$("dDelta").textContent = d.delta;
$("dTime").textContent = String(node.commit.time || "").replace("T", " ").slice(0, 19);
$("dDot").style.background = colorOf(node.branch, node.lane);
+8 -3
View File
@@ -349,9 +349,12 @@
// What a branch's checkpoint badge carries: its agent's icon when
// the branch names an agent, the agent's monogram when the agent
// has no drawable glyph, and the leaf when no agent is named.
function glyphFor(branch) {
const agent = agentOf(branch);
// has no drawable glyph, and the leaf when no agent is named. A
// commit that carries the real calling agent (ctx.agent, recorded
// by the tools) names its agent outright, ahead of the branch-name
// token guess.
function glyphFor(branch, commit) {
const agent = (commit && agentOf(commit.agent)) || agentOf(branch);
if (!agent) return { type: "leaf", glyph: LEAF_GLYPH };
const icon = ICONS[agent.id];
if (icon) return { type: "icon", agent, icon };
@@ -376,7 +379,9 @@
if (d.added) parts.push(`+${d.added} ${t.added}`);
if (d.modified) parts.push(`~${d.modified} ${t.modified}`);
if (d.deleted) parts.push(`-${d.deleted} ${t.deleted}`);
const a = commit.agent ? agentOf(commit.agent) : null;
return {
agent: a ? a.name : String(commit.agent || ""),
message: commit.message || "",
meta: `${commit.files == null ? "" : `${commit.files} ${t.files} · `}${t.newBytes} ${bytes(commit.newBytes)} / ${bytes(commit.logicalBytes)}`,
delta: parts.join(" · "),