Add layerfs: LayerFS workspaces as tools for every agent (#318)
New community tools package @magpie-community/tools-layerfs 0.7.1 (Mola-maker): LayerFS workspaces as tools for every agent. It imports a source folder into a versioned workspace under MAGPIE_LAYERFS_HOME (default ~/.magpie-layerfs), with checkpoints, history and diffs. Running commands (exec) is off unless the user turns it on. No network access. registry.json gains its one entry.
Run at the reviewed head 4795df0 (merges cleanly onto origin/main 1ae89aa):
- bun scripts/check.mjs layerfs: ok
- bun test in the package under a temp HOME: 48 of 48 pass, worktree clean after
- the seven points from the last review, each re-run:
1. source guard: ~/.Config/Magpie, a symlink to ~/.config/magpie, ~/.AWS, ~/.CONFIG and a symlinked parent are all refused
2. names: project a / branch b--c and project a--b / branch c no longer share a workspace; Main and main are apart
3. layerfs_history {limit:1} at 200 checkpoints: 0.1 ms (151 ms before), no trajectory.json written
4. native backend and its SDK path removed; asking for it throws a clear error
5. repository points at this repo; README images pinned
6. runShell: cat returns in 32 ms (2005 before), a backgrounded sleep doesn't hold the call, a timeout kills the process
7. storedBytes equals stored content plus checkpoint records; the description says so
- read every line changed since 1c9e4c1: no path escape, no writes outside its home
Not tried: a real agent using the tools through magpie.
Known: something exec starts in the background keeps running after a successful call, like a normal shell, and can land in the next checkpoint.
This commit is contained in:
@@ -0,0 +1,285 @@
|
||||
# LayerFS for Magpie
|
||||
|
||||
[LayerFS](https://github.com/Ephemeral-AI-Lab/layerfs) workspaces for every
|
||||
agent [magpie](https://usemagpie.ai) connects: instead of each agent copying
|
||||
a project tree to work on it, agents share one durable, deduplicated history
|
||||
and work through **stable filesystem paths**. Forking a branch for a
|
||||
parallel agent copies **no file bytes**; a checkpoint stores **only what
|
||||
changed**; any agent can resolve, read and build on what the others
|
||||
committed.
|
||||
|
||||
给每个 agent 的 LayerFS 工作区:多个 agent 共享一份可去重的持久历史,而不是
|
||||
各自复制整棵项目树。给并行 agent 开分支不复制任何文件字节;存检查点只写
|
||||
变化的部分;路径稳定,任何 agent 都能定位、读取并接续其他 agent 的提交。
|
||||
|
||||
```sh
|
||||
magpie plugin add @magpie-community/tools-layerfs
|
||||
magpie plugin # lists layerfs_provision, layerfs_checkpoint, ...
|
||||
```
|
||||
|
||||
## Tools
|
||||
|
||||
Served on magpie's MCP server as `layerfs_<tool>`:
|
||||
|
||||
| Tool | What it does |
|
||||
|---|---|
|
||||
| `provision` | Gives the agent a workspace for a project branch and answers the path to work in. The first provision imports the source directory — a required argument, the directory the user chose for the project — as the project's first checkpoint; later provisions of the same branch answer the same path without copying the tree again. |
|
||||
| `checkpoint` | Saves the workspace's state on its branch, storing only the blobs the store has not seen; answers added / modified / deleted counts and the new-bytes vs saved-bytes accounting. |
|
||||
| `fork` | Forks a branch for a parallel agent: a pointer at an existing checkpoint, ready immediately, 0 bytes copied. |
|
||||
| `publish` | Publishes a branch's head as main's new Layer, so finished work becomes what new work forks from. Guarded: main's head must be in the branch's history, so a publish can only move main forward — if main moved on its own, the publish is refused (a real dsh run lost main's 238 tests to a stale publish; this is that lesson, encoded). `force: true` overwrites deliberately and reports what it replaced. |
|
||||
| `exec` | Runs a shell command in a branch's workspace and checkpoints whatever it changed as one commit — the dsh shape, where every bash call is mount, run, commit. A no-change command commits nothing; a failing command's changes are still checkpointed, with its exit code reported. **Disabled by default** (see Safety defaults): it runs only when the user has opted in. |
|
||||
| `history` | Lists a branch's checkpoints, newest first, with each one's logical tree size and the bytes it actually stored. |
|
||||
| `resolve` | Resolves a project / branch / file to a real filesystem path, its checkpoint and content hash — an O(1) lookup, no copying. |
|
||||
| `status` | Backend in use, projects and branches held, and the storage accounting: logical bytes of all checkpoints vs bytes the store occupies. |
|
||||
|
||||
Only the workspace path is persistent. Every workspace carries two
|
||||
scratch directories, `.tmp/` and `.cache/`, created at provision;
|
||||
`exec` runs commands with `TMPDIR` and `XDG_CACHE_HOME` redirected at
|
||||
them, so toolchains keep their temporary files and caches inside the
|
||||
workspace instead of the host's real `/tmp`. Both directories are
|
||||
workspace-local scratch: checkpoints and publishes never capture them,
|
||||
and they live and die with the workspace directory itself. Files a
|
||||
command writes to the host's real `/tmp` are likewise outside LayerFS
|
||||
management — if it matters, it belongs in the workspace.
|
||||
|
||||
## Backend
|
||||
|
||||
- **sim** — a local content-addressed store implementing the LayerFS
|
||||
model: immutable blobs named by SHA-256, branches as manifest
|
||||
pointers, checkpoints as deduplicated manifests, under
|
||||
`MAGPIE_LAYERFS_HOME` (default `~/.magpie-layerfs`). It runs
|
||||
anywhere, which is what the tests and the benchmark below use.
|
||||
|
||||
**This package is sim-only.** The native backend — the real LayerFS
|
||||
through its JavaScript SDK — is developed in the standalone repo,
|
||||
[Mola-maker/magpie-layerfs](https://github.com/Mola-maker/magpie-layerfs),
|
||||
and is not part of this package: shipping it here needs a pinned,
|
||||
integrity-checked npm dependency, and `@layerfs/sdk` is not
|
||||
published to npm, so there is no version to pin. It returns in a
|
||||
follow-up PR once the SDK is published. Asking for it
|
||||
(`MAGPIE_LAYERFS_BACKEND=native`, `MAGPIE_LAYERFS_NATIVE=1`, or the
|
||||
old `"native"` plugin option) is an explicit error that says so.
|
||||
|
||||
`MAGPIE_LAYERFS_BACKEND=auto|sim` selects explicitly; both mean sim
|
||||
here.
|
||||
|
||||
## Safety defaults
|
||||
|
||||
magpie serves plugin tools on its MCP server to any caller holding a
|
||||
gateway key, and the plugin host runs with the user's rights — so the
|
||||
defaults here are set for that room, not for a private library:
|
||||
|
||||
- **`provision`'s `source` is required.** There is no default: an
|
||||
earlier version defaulted it to the host's `directory`, which in
|
||||
magpie is the *config* directory (`~/.config/magpie`) — it holds
|
||||
`plugin-auth.json`, every signed-in plugin's token. The config
|
||||
directory, the credential stores (`~/.ssh`, `~/.aws`, `~/.gnupg`),
|
||||
the home directory, the filesystem root, and the plugin's own store
|
||||
are refused as a source — as the source, inside it, or containing
|
||||
it. The comparison runs on real paths (`realpathSync`, case-folded),
|
||||
so neither a symlink pointing at a refused directory nor a
|
||||
case-variant spelling of one (`~/.Config/Magpie`, `~/.AWS`) gets
|
||||
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.
|
||||
- **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
|
||||
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.
|
||||
|
||||
## Benchmark
|
||||
|
||||
[`bench/bench.mjs`](https://github.com/Mola-maker/magpie-layerfs/blob/main/bench/bench.mjs)
|
||||
(run from a checkout of this repo) — a 184-file, 26.8 MB project; 6
|
||||
parallel agents, each keeping 3 checkpoints (sim backend, this machine):
|
||||
|
||||
| | naive copies | this plugin |
|
||||
|---|---|---|
|
||||
| fork one more agent | 321 ms, 26.8 MB copied | **~1 ms, 0 bytes** |
|
||||
| keep 18 checkpoints | 482.6 MB of snapshots | **27.2 MB** of store for 509.4 MB of logical checkpoints (**18.7× dedup**) |
|
||||
| resolve a file path | walk the copy's tree | **138 µs**, with its checkpoint + SHA-256 |
|
||||
| total disk for the run | 643.5 MB | **188.1 MB** (store + the 6 live workspaces) |
|
||||
|
||||

|
||||

|
||||
|
||||
Honest limits: a first provision still materializes the tree once, and the
|
||||
sim backend rehashes the tree at each checkpoint (the native engine tracks
|
||||
changes through its daemons instead). What the plugin removes is the
|
||||
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 —
|
||||
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.
|
||||
|
||||
## The page: watch the trajectory
|
||||
|
||||
The package also declares a magpie page, **LayerFS trajectory**
|
||||
(轨迹), which replays how the agents' worktrees grew, drawn the way
|
||||
LayerFS's own History picture draws them: main is the green middle
|
||||
bough, each branch a bough of its own, a checkpoint a badge bearing
|
||||
its agent's own icon — the marks magpie itself ships for them, in
|
||||
that agent's colour — a fork a split, and a publish a graft back
|
||||
onto main that adds a Layer band (L0, L1, …). Two running totals
|
||||
carry the argument — what those checkpoints would have cost as
|
||||
plain copies against what the deduplicated store actually wrote,
|
||||
with a store.stats line in LayerFS's own accounting words. Play it,
|
||||
scrub it, click a badge for its checkpoint's message and byte
|
||||
split, or click a branch's name tag to focus that branch alone:
|
||||
that is what the plugin does for an agent's edits, made visible.
|
||||
|
||||
The page is drawn in magpie's own design language and built the way
|
||||
magpie builds pages — plain HTML, CSS and scripts, no build step and
|
||||
no dependencies, styled by the host's `--magpie-*` theme tokens with
|
||||
its tiles, seg controls and indigo accent. The replay runs on
|
||||
requestAnimationFrame through magpie's own `--ease` curve
|
||||
(cubic-bezier(.2,.8,.2,1)): the boughs draw themselves as the
|
||||
playhead passes, each badge lands with a pulse while its icon
|
||||
draws its own outline and fills in, a publish pops its Layer badge
|
||||
(L1, L2, …) onto main, and the stat tiles count up with the same
|
||||
easing; with reduced motion preferred, the page simply shows the
|
||||
finished picture, every icon fully drawn.
|
||||
|
||||
A magpie page cannot read plugin-private data: its sandbox forbids
|
||||
fetch, and the bridge's reads are a fixed host list (`usage:summary`,
|
||||
`providers:list`) with no entry a plugin can serve its own data
|
||||
through. So the page animates the sample bundled with it —
|
||||
`page/trajectory.js`, a labeled recording from the benchmark scenario
|
||||
(one project, six agents, three checkpoints each), a package asset
|
||||
that nothing rewrites at runtime. The trajectory itself is computed
|
||||
on demand from the store's records whenever it is asked for
|
||||
(`backend.trajectory()`; `tools/gen-trajectory.mjs` uses it to make
|
||||
the sample). No recording file is maintained per tool call: an
|
||||
earlier version refreshed one in the store after every call, which
|
||||
cost a branch-chain walk per call — growing with the project's
|
||||
history — for a file the page cannot read, so the refresh was
|
||||
removed in 0.7.1. The page declares no `magpie.read` permissions,
|
||||
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`:
|
||||
|
||||
```sh
|
||||
bun test # the suite (bun:test): tools end to end, plus the page's layout math
|
||||
```
|
||||
|
||||
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.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 —
|
||||
walked straight past (the review imported `plugin-auth.json`
|
||||
through `~/.Config/Magpie` and through a symlink). Both sides are
|
||||
canonicalized with `realpathSync` and case-folded; refused roots
|
||||
that do not exist are canonicalized through their nearest existing
|
||||
ancestor. Regression tests cover the symlink and the case variant,
|
||||
unit-level and end to end.
|
||||
- **Breaking on-disk change: workspaces moved, branch encoding
|
||||
widened.** Workspaces now live at `workspaces/<project>/<encoded
|
||||
branch>` — the flat `<project>--<branch>` name was not injective
|
||||
(project `a` branch `b--c` and project `a--b` branch `c` shared one
|
||||
directory, and a checkpoint crossed the projects). The branch
|
||||
encoder now percent-encodes every character outside `[a-z0-9._-]`,
|
||||
uppercase included, so `Main` and `main` no longer share a head
|
||||
file or a workspace on case-insensitive volumes either. Stores are
|
||||
**not migrated**: branch head files are unchanged for names the old
|
||||
encoder already spelled the same way (lowercase, `_`, `-`, `.`,
|
||||
and `/`→`%2F`); a branch whose name contains uppercase or `%`
|
||||
keeps its commits but its old head file (`branches/Main.json`)
|
||||
and old workspace (`workspaces/<project>--Main`) are not picked
|
||||
up — re-fork such branches, and remove the old workspace
|
||||
directories by hand.
|
||||
- **No per-call trajectory refresh.** The `trajectory.json` the
|
||||
tools maintained in the store after every call is gone: keeping it
|
||||
current cost a walk of the touched branch's whole chain per call,
|
||||
for a file the page cannot read. `trajectory()` still builds the
|
||||
same data on demand.
|
||||
- **`exec`'s plumbing**: stdin is closed (a command reading it gets
|
||||
EOF instead of waiting out the timeout), the child runs detached
|
||||
in its own process group and a timeout kills the group, and the
|
||||
call resolves on `exit` plus a short drain instead of `close` —
|
||||
a background child holding the stdout pipe can no longer hold the
|
||||
call open past its shell.
|
||||
- **Manifests are counted.** `storedBytes`/`dedupRatio` now include
|
||||
the commit records — each checkpoint's full manifest — which for
|
||||
a wide tree are a real share of the store (the review measured
|
||||
128 MB of manifests for 200 checkpoints of a 5,000-file tree,
|
||||
previously uncounted, under a description claiming history "costs
|
||||
little more than the changes themselves"; the description now
|
||||
states the real cost model). Stores written before 0.7.1 keep
|
||||
their incremental record, which undercounts by the records written
|
||||
before this version until the record is rebuilt (delete
|
||||
`accounting.json` to force the rebuild walk).
|
||||
- The page's README images are pinned to a commit instead of the
|
||||
moving `main`.
|
||||
|
||||
## Changes in 0.7.0
|
||||
|
||||
A safety pass over the whole package (prompted by the PR #318 review):
|
||||
|
||||
- `provision` requires `source` explicitly and refuses magpie's config
|
||||
directory and the credential stores as sources; imports skip
|
||||
secret-shaped files (sim) or refuse them (native), and are bounded.
|
||||
- `exec` is off by default; the user's `"exec"` plugin option or
|
||||
`MAGPIE_LAYERFS_EXEC=1` turns it on.
|
||||
- The native backend is off by default (the `"native"` option or
|
||||
`MAGPIE_LAYERFS_NATIVE=1`) and runs entirely in a child process
|
||||
(`native-worker.mjs`); the host process imports no SDK and shares no
|
||||
`LAYERFS_*` environment writes.
|
||||
- A native checkpoint no longer deletes binaries it skipped at
|
||||
checkout; re-provisioning a moved native branch reports `stale`
|
||||
instead of wiping the workspace; native publish refuses when the
|
||||
fork point or main's top Layer is unknown.
|
||||
- The store and workspaces are `0700`, record files `0600`, and file
|
||||
modes are preserved through the sim store.
|
||||
- The recorded trajectory lives in the store (`trajectory.json`),
|
||||
refreshed per affected project; the page's bundled file is a static
|
||||
sample, and running the test suite modifies no package file.
|
||||
- **Breaking on-disk change**: branch head files and workspace
|
||||
directories now percent-encode `/` (`feat/x` → `feat%2Fx`), so slash
|
||||
branches and `feat__x` no longer collide and slash branches list
|
||||
correctly. Stores written by 0.6.x keep working for non-slash
|
||||
branches; a slash branch's old head file (`branches/feat/x.json`)
|
||||
and workspace (`feat__x`) are not migrated — re-fork slash branches.
|
||||
- The page gained Japanese and Traditional Chinese string tables
|
||||
(matching its declared titles), a magpie-style project menu in
|
||||
place of the native `<select>`, and a branch-colour dot on the
|
||||
detail card in place of the coloured edge.
|
||||
@@ -0,0 +1,220 @@
|
||||
// LayerFS for every agent magpie connects: instead of each agent copying a
|
||||
// project tree to work on it, agents share one durable, deduplicated history
|
||||
// and work through stable workspace paths. Forking a branch for a parallel
|
||||
// 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.
|
||||
import { checkBranch, checkInnerPath, checkProject, checkSourceDir, createBackend } from "./layerfs.mjs"
|
||||
|
||||
const str = (v, name) => {
|
||||
if (typeof v !== "string" || !v) throw new Error(`${name} is a non-empty string`)
|
||||
return v
|
||||
}
|
||||
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.
|
||||
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).
|
||||
const call = async (fn) => {
|
||||
const b = await backend()
|
||||
return fn(b)
|
||||
}
|
||||
|
||||
return {
|
||||
tool: {
|
||||
provision: {
|
||||
description:
|
||||
"Gives the agent a LayerFS workspace for a project branch and answers the filesystem path to work in. " +
|
||||
"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: magpie'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. " +
|
||||
"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.",
|
||||
args: {
|
||||
type: "object",
|
||||
properties: {
|
||||
project: { type: "string", description: "LayerFS project name, e.g. website" },
|
||||
branch: { type: "string", description: "branch to work on (default main)" },
|
||||
source: { type: "string", description: "the directory the user chose for this project; imported when the project is first created, ignored afterwards" },
|
||||
},
|
||||
required: ["project", "source"],
|
||||
},
|
||||
async execute(args) {
|
||||
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
|
||||
// source: it holds plugin credentials. It is refused as a
|
||||
// source here (and in the backend) like the other blocked roots.
|
||||
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))
|
||||
},
|
||||
},
|
||||
checkpoint: {
|
||||
description:
|
||||
"Saves the workspace's current state as a deduplicated checkpoint on its branch: only blobs the store has not seen are written. " +
|
||||
"The real cost model: the changed blobs, plus one commit record per checkpoint holding the tree's full manifest — " +
|
||||
"for a wide tree the manifests are a real part of the store's bytes, and the storage accounting counts them. " +
|
||||
"Answers the commit id and the added / modified / deleted counts with the new-bytes and saved-bytes accounting.",
|
||||
args: {
|
||||
type: "object",
|
||||
properties: {
|
||||
project: { type: "string", description: "LayerFS project name" },
|
||||
branch: { type: "string", description: "branch the workspace belongs to (default main)" },
|
||||
message: { type: "string", description: "what this checkpoint did" },
|
||||
},
|
||||
required: ["project"],
|
||||
},
|
||||
async execute(args) {
|
||||
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", "")))
|
||||
},
|
||||
},
|
||||
fork: {
|
||||
description:
|
||||
"Forks a branch of a project for a parallel agent. A fork is a pointer at an existing checkpoint: it copies no file bytes and is ready immediately, " +
|
||||
"where copying the tree for another agent costs the whole tree's size and time. Provision the new branch to get its workspace path.",
|
||||
args: {
|
||||
type: "object",
|
||||
properties: {
|
||||
project: { type: "string", description: "LayerFS project name" },
|
||||
branch: { type: "string", description: "the new branch's name" },
|
||||
from: { type: "string", description: "branch to fork from (default main)" },
|
||||
},
|
||||
required: ["project", "branch"],
|
||||
},
|
||||
async execute(args) {
|
||||
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))
|
||||
},
|
||||
},
|
||||
publish: {
|
||||
description:
|
||||
"Publishes a branch's head as main's new state (a Layer), so the work every agent did on that branch becomes what new work forks from. " +
|
||||
"Guarded: main's current head must be in the branch's history, so a publish can only move main forward; if main has newer checkpoints the branch never saw, " +
|
||||
"the publish is refused and says so. Pass force: true only to overwrite deliberately; the result then reports overwrote and the previous main head.",
|
||||
args: {
|
||||
type: "object",
|
||||
properties: {
|
||||
project: { type: "string", description: "LayerFS project name" },
|
||||
branch: { type: "string", description: "branch to publish to main" },
|
||||
force: { type: "boolean", description: "overwrite main even if it has checkpoints the branch never saw (default false)" },
|
||||
},
|
||||
required: ["project", "branch"],
|
||||
},
|
||||
async execute(args) {
|
||||
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 }))
|
||||
},
|
||||
},
|
||||
exec: {
|
||||
description:
|
||||
"Runs a shell command inside a branch's provisioned workspace and checkpoints whatever it changed as one commit: run, test, fix, all captured in the branch's history. " +
|
||||
"DISABLED by default: the command runs with the plugin host's privileges, and magpie serves these tools to remote callers holding a gateway key, so a shell is not something a model key should silently become. " +
|
||||
"It runs only when the user has opted in — the plugin's \"exec\" option set to true, or MAGPIE_LAYERFS_EXEC=1 in the host's environment. " +
|
||||
"A command that changes nothing commits nothing. A failing command's changes are still checkpointed (history can be rewound), and its exit code, stdout and stderr are returned. " +
|
||||
"Only the workspace path is persistent: the command runs with TMPDIR and XDG_CACHE_HOME redirected into the workspace (.tmp/ and .cache/), " +
|
||||
"workspace-local scratch that checkpoint and publish never capture, and files written to the host's real /tmp are likewise outside LayerFS management. " +
|
||||
"The timeout is capped at 55 seconds, the tools budget.",
|
||||
args: {
|
||||
type: "object",
|
||||
properties: {
|
||||
project: { type: "string", description: "LayerFS project name" },
|
||||
branch: { type: "string", description: "branch whose workspace to run in (default main)" },
|
||||
command: { type: "string", description: "the shell command to run in the workspace" },
|
||||
message: { type: "string", description: "checkpoint message (default: the command itself)" },
|
||||
timeoutMs: { type: "number", description: "timeout in milliseconds (default 50000, capped at 55000)" },
|
||||
},
|
||||
required: ["project", "command"],
|
||||
},
|
||||
async execute(args) {
|
||||
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 magpie's plugin options, or sets MAGPIE_LAYERFS_EXEC=1 in the plugin host's environment, and restarts the host.")
|
||||
const project = checkProject(str(args.project, "project"))
|
||||
const branch = checkBranch(opt(args.branch, "branch", "main"))
|
||||
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))
|
||||
},
|
||||
},
|
||||
history: {
|
||||
description:
|
||||
"Lists a branch's checkpoints, newest first: commit id, message, time, file count and the logical size of the tree at that point, " +
|
||||
"plus how many new bytes that checkpoint actually stored. The history is shared and durable: any agent can read what every other agent committed.",
|
||||
args: {
|
||||
type: "object",
|
||||
properties: {
|
||||
project: { type: "string", description: "LayerFS project name" },
|
||||
branch: { type: "string", description: "branch to read (default main)" },
|
||||
limit: { type: "number", description: "how many checkpoints to return (default 20)" },
|
||||
},
|
||||
required: ["project"],
|
||||
},
|
||||
async execute(args) {
|
||||
const project = checkProject(str(args.project, "project"))
|
||||
const branch = checkBranch(opt(args.branch, "branch", "main"))
|
||||
const limit = args.limit === undefined ? 20 : Math.max(1, Math.min(200, Number(args.limit) || 20))
|
||||
return call((b) => b.history(project, branch, limit))
|
||||
},
|
||||
},
|
||||
resolve: {
|
||||
description:
|
||||
"Resolves a logical LayerFS location to a real filesystem path without copying anything: the workspace path for a project branch, " +
|
||||
"or one file inside it, with the checkpoint that path currently answers for and, for a file, its content hash and size. " +
|
||||
"Use it to find where a branch lives before reading or handing the path to another tool.",
|
||||
args: {
|
||||
type: "object",
|
||||
properties: {
|
||||
project: { type: "string", description: "LayerFS project name" },
|
||||
branch: { type: "string", description: "branch to resolve (default main)" },
|
||||
path: { type: "string", description: "a file path inside the workspace, relative to its root" },
|
||||
},
|
||||
required: ["project"],
|
||||
},
|
||||
async execute(args) {
|
||||
const project = checkProject(str(args.project, "project"))
|
||||
const branch = checkBranch(opt(args.branch, "branch", "main"))
|
||||
const inner = args.path === undefined || args.path === "" ? "" : checkInnerPath(str(args.path, "path"))
|
||||
return call((b) => b.resolve(project, branch, inner))
|
||||
},
|
||||
},
|
||||
status: {
|
||||
description:
|
||||
"Reports the LayerFS backend in use (sim in this package), 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() {
|
||||
return call((b) => b.status())
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,752 @@
|
||||
// The LayerFS backend for the magpie tools plugin — one backend
|
||||
// behind a small surface (provision, checkpoint, fork, publish, exec,
|
||||
// history, resolve, status):
|
||||
//
|
||||
// - 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.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// Environment:
|
||||
// MAGPIE_LAYERFS_BACKEND auto (default) | sim — "native" is an
|
||||
// explicit error in this package (above)
|
||||
// MAGPIE_LAYERFS_HOME state root (default ~/.magpie-layerfs)
|
||||
import { spawn } from "node:child_process"
|
||||
import { createHash } from "node:crypto"
|
||||
import {
|
||||
chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync,
|
||||
realpathSync, statSync, writeFileSync,
|
||||
} from "node:fs"
|
||||
import { homedir } from "node:os"
|
||||
import { dirname, join, parse, resolve, sep } from "node:path"
|
||||
|
||||
const BINDING = ".layerfs.json"
|
||||
|
||||
// Workspace-local scratch: two directories at the workspace root that
|
||||
// are never checkpointed and never published. provision creates them,
|
||||
// exec points TMPDIR and XDG_CACHE_HOME at them so toolchains keep
|
||||
// their temporary files and caches inside the workspace instead of
|
||||
// the host's real /tmp, and every checkpoint scan skips both names —
|
||||
// their content lives and dies with the workspace directory itself.
|
||||
const SCRATCH_DIRS = [".tmp", ".cache"]
|
||||
const scanSkip = () => new Set([BINDING, ...SCRATCH_DIRS])
|
||||
function ensureScratch(dir) {
|
||||
for (const name of SCRATCH_DIRS) mkdirPrivate(join(dir, name))
|
||||
}
|
||||
|
||||
// ---- names -------------------------------------------------------------------
|
||||
|
||||
// Project names follow the SDK's rule: 1-63 chars of lowercase ASCII letters,
|
||||
// digits, `_`, `-`, `.`, starting and ending alphanumeric.
|
||||
export function checkProject(name) {
|
||||
if (typeof name !== "string" || !/^[a-z0-9](?:[a-z0-9_.-]{0,61}[a-z0-9])?$/.test(name))
|
||||
throw new Error(`project is a LayerFS project name: 1-63 chars of a-z 0-9 _ - ., starting and ending with a letter or digit; got ${JSON.stringify(name)}`)
|
||||
return name
|
||||
}
|
||||
|
||||
export function checkBranch(name) {
|
||||
if (typeof name !== "string" || !name || name.length > 100 || name.split("/").some((s) => !s || s === "." || s === ".." || !/^[A-Za-z0-9_.-]+$/.test(s)))
|
||||
throw new Error(`branch is a name like main or feat/x; got ${JSON.stringify(name)}`)
|
||||
return name
|
||||
}
|
||||
|
||||
// A path inside a workspace: relative, and it must stay in.
|
||||
export function checkInnerPath(p) {
|
||||
if (typeof p !== "string" || !p) throw new Error("path is a non-empty relative path")
|
||||
const norm = p.replace(/\\/g, "/").replace(/^\.\//, "")
|
||||
if (norm.startsWith("/") || norm.split("/").some((s) => s === ".."))
|
||||
throw new Error(`path must stay inside the workspace; got ${JSON.stringify(p)}`)
|
||||
return norm
|
||||
}
|
||||
|
||||
const sha256 = (buf) => createHash("sha256").update(buf).digest("hex")
|
||||
const nowIso = () => new Date().toISOString()
|
||||
|
||||
// ---- on-disk names -------------------------------------------------------------
|
||||
// A branch name maps to ONE flat file (its head record) and one workspace
|
||||
// directory segment. Every character outside [a-z0-9._-] is percent-
|
||||
// encoded, so the mapping is injective AND case-injective: feat/x and
|
||||
// feat__x are different branches with different files (feat%2Fx.json vs
|
||||
// feat__x.json), and Main and main stay different on a case-insensitive
|
||||
// volume too (branches/%4Dain.json vs branches/main.json). Every branch
|
||||
// — slash branches included — sits at the top level, where listBranches
|
||||
// reads. (Pre-0.7.1 encoders left some collisions: 0.7.0 encoded only
|
||||
// "%" and "/", so uppercase branches shared files on case-insensitive
|
||||
// volumes; pre-0.7 layouts are not migrated — see the README's notes.)
|
||||
export function encodeBranchName(branch) {
|
||||
let out = ""
|
||||
for (const ch of branch)
|
||||
out += /[a-z0-9._-]/.test(ch)
|
||||
? ch
|
||||
: "%" + ch.codePointAt(0).toString(16).toUpperCase().padStart(2, "0")
|
||||
return out
|
||||
}
|
||||
export function decodeBranchName(stem) {
|
||||
return stem.replace(/%([0-9A-Fa-f]{2})/g, (_, h) => String.fromCodePoint(parseInt(h, 16)))
|
||||
}
|
||||
|
||||
// Workspaces live one directory per project — workspaces/<project>/
|
||||
// <encoded branch> — because a flat `${project}--${branch}` name is
|
||||
// not injective when both sides may contain "--" (project a branch
|
||||
// b--c vs project a--b branch c). Project names cannot contain "/",
|
||||
// so the per-project directory cannot collide. Counting workspaces
|
||||
// means summing the branch directories across the project ones.
|
||||
function countWorkspaces(workspacesDir) {
|
||||
if (!existsSync(workspacesDir)) return 0
|
||||
let n = 0
|
||||
for (const e of readdirSync(workspacesDir, { withFileTypes: true }))
|
||||
if (e.isDirectory()) n += readdirSync(join(workspacesDir, e.name)).length
|
||||
return n
|
||||
}
|
||||
|
||||
// ---- private writes --------------------------------------------------------------
|
||||
// The store can hold anything a source tree held, so it is created
|
||||
// private: directories 0700, record files 0600, whatever the umask
|
||||
// says. writeFileMode chmods after writing because writeFileSync's
|
||||
// mode only applies when a file is created and is umask-masked anyway.
|
||||
function writeFileMode(path, data, mode = 0o600) {
|
||||
writeFileSync(path, data, { mode })
|
||||
chmodSync(path, mode)
|
||||
}
|
||||
function writeJson(path, obj, pretty = false) {
|
||||
writeFileMode(path, pretty ? JSON.stringify(obj, null, 1) : JSON.stringify(obj))
|
||||
}
|
||||
function mkdirPrivate(dir) {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
||||
chmodSync(dir, 0o700)
|
||||
}
|
||||
|
||||
// ---- importing a source tree ------------------------------------------------------
|
||||
// An import sweeps a whole directory into the store, so it is the one
|
||||
// place a tree the user did not mean to share can leak. The caller must
|
||||
// pass the source explicitly (there is no default — magpie's
|
||||
// ctx.directory is its config directory, not a working directory, and
|
||||
// it holds plugin-auth.json: every signed-in plugin's token). The
|
||||
// config directory, the classic credential stores, the home directory
|
||||
// and the filesystem root are refused outright — as source, as a
|
||||
// parent of the source, or inside it.
|
||||
// The guard compares REAL paths, not spellings. A string comparison
|
||||
// of resolve()d paths is bypassed two ways (round-2 review, item 1):
|
||||
// a symlink pointing at a refused directory (readdirSync follows the
|
||||
// root link), and a case-variant spelling on a case-insensitive
|
||||
// volume ("~/.Config/Magpie", "~/.AWS"). So both sides are
|
||||
// canonicalized with realpathSync and case-folded before comparing.
|
||||
// A refused root that does not exist is canonicalized through its
|
||||
// nearest existing ancestor — it can still be named by a case
|
||||
// variant or reached through a symlinked parent, and canonicalizing
|
||||
// it must never be what throws.
|
||||
function canonicalForCompare(p) {
|
||||
let cur = resolve(p)
|
||||
const tail = []
|
||||
for (;;) {
|
||||
try { return join(realpathSync(cur), ...tail).toLowerCase() } catch { /* not there: walk up */ }
|
||||
const parent = dirname(cur)
|
||||
if (parent === cur) return resolve(p).toLowerCase()
|
||||
tail.unshift(cur.slice(parent.length + 1))
|
||||
cur = parent
|
||||
}
|
||||
}
|
||||
|
||||
export function checkSourceDir(sourceDir, { configDir, storeRoot } = {}) {
|
||||
if (typeof sourceDir !== "string" || !sourceDir)
|
||||
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 given = resolve(sourceDir)
|
||||
if (!existsSync(given) || !statSync(given).isDirectory())
|
||||
throw new Error(`source is not a directory: ${sourceDir}`)
|
||||
const src = canonicalForCompare(given) // real path, case-folded: the guard's currency
|
||||
const overlaps = (a, b) => a === b || a.startsWith(b + sep) || b.startsWith(a + sep)
|
||||
const refuses = [
|
||||
[join(homedir(), ".config", "magpie"), "magpie's config directory, which holds plugin credentials (plugin-auth.json)"],
|
||||
[join(homedir(), ".ssh"), "the SSH directory"],
|
||||
[join(homedir(), ".aws"), "the AWS directory"],
|
||||
[join(homedir(), ".gnupg"), "the GnuPG directory"],
|
||||
]
|
||||
if (configDir) refuses.unshift([configDir, "magpie's config directory, which holds plugin credentials (plugin-auth.json)"])
|
||||
for (const [dir, what] of refuses)
|
||||
if (overlaps(src, canonicalForCompare(dir)))
|
||||
throw new Error(`refusing to import ${given}: it is, contains, or sits inside ${what}`)
|
||||
if (src === canonicalForCompare(homedir()) || src === canonicalForCompare(parse(given).root))
|
||||
throw new Error(`refusing to import ${given}: importing a home directory or a filesystem root would sweep far more than one project into the store — pass the project's own directory`)
|
||||
if (storeRoot && overlaps(src, canonicalForCompare(storeRoot)))
|
||||
throw new Error(`refusing to import ${given}: it overlaps the plugin's own store`)
|
||||
return given
|
||||
}
|
||||
|
||||
// Secret-shaped paths never enter the store from an import: VCS
|
||||
// internals, env files, private keys, credential stores. Matching is
|
||||
// per path segment, so docs/.env.example is caught just like .env.
|
||||
const KEY_FILE = /^(id_rsa|id_ed25519|id_ecdsa|id_dsa)(\..*)?$/
|
||||
export function isSecretPath(rel) {
|
||||
return rel.split("/").some((seg) =>
|
||||
seg === ".git" || seg === ".ssh" || seg === ".aws" || seg === ".gnupg" ||
|
||||
seg === ".netrc" || seg === ".env" || seg.startsWith(".env.") ||
|
||||
KEY_FILE.test(seg) || /\.(pem|key)$/i.test(seg))
|
||||
}
|
||||
|
||||
// An import is bounded, so pointing it at the wrong tree fails loudly
|
||||
// instead of sweeping a disk into the store.
|
||||
export const IMPORT_MAX_FILES = 20000
|
||||
export const IMPORT_MAX_BYTES = 512 * 1024 * 1024
|
||||
function checkImportLimits(files) {
|
||||
let bytes = 0
|
||||
for (const f of files) bytes += f.size
|
||||
if (files.length > IMPORT_MAX_FILES)
|
||||
throw new Error(`source holds ${files.length} files, over the import limit of ${IMPORT_MAX_FILES} — pass the project's own directory, not a parent of it`)
|
||||
if (bytes > IMPORT_MAX_BYTES)
|
||||
throw new Error(`source holds ${bytes} bytes, over the import limit of ${IMPORT_MAX_BYTES} — pass the project's own directory, not a parent of it`)
|
||||
}
|
||||
|
||||
// Files of a source tree with the secret-shaped ones set aside.
|
||||
// Symlinks are not followed (scanTree's rule, kept): a link's target
|
||||
// stays outside the import.
|
||||
function walkSourceFiles(dir) {
|
||||
const files = [], skipped = []
|
||||
const walk = (d, rel) => {
|
||||
for (const e of readdirSync(d, { withFileTypes: true })) {
|
||||
const r = rel ? `${rel}/${e.name}` : e.name
|
||||
if (isSecretPath(r)) { skipped.push(r); continue }
|
||||
const full = join(d, e.name)
|
||||
if (e.isDirectory()) walk(full, r)
|
||||
else if (e.isFile()) {
|
||||
const st = statSync(full)
|
||||
files.push({ rel: r, full, size: st.size, mode: st.mode & 0o777 })
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(dir, "")
|
||||
return { files, skipped }
|
||||
}
|
||||
|
||||
// The sim backend's import scan: a manifest { rel: { sha, size, mode } }
|
||||
// plus the list of secret-shaped paths left out, reported to the caller.
|
||||
export function scanImportTree(dir) {
|
||||
const { files, skipped } = walkSourceFiles(dir)
|
||||
checkImportLimits(files)
|
||||
const manifest = {}
|
||||
for (const f of files) {
|
||||
const buf = readFileSync(f.full)
|
||||
manifest[f.rel] = { sha: sha256(buf), size: buf.length, mode: f.mode }
|
||||
}
|
||||
return { manifest, skipped }
|
||||
}
|
||||
|
||||
// Walk a directory into a manifest: { "rel/path": { sha, size, mode } }.
|
||||
// The mode rides along so a file keeps its permissions through the
|
||||
// store: a 0600 file is stored and materialized as 0600, never widened
|
||||
// to the umask's default.
|
||||
function scanTree(dir, skip = new Set()) {
|
||||
const out = {}
|
||||
const walk = (d, rel) => {
|
||||
for (const e of readdirSync(d, { withFileTypes: true })) {
|
||||
const r = rel ? `${rel}/${e.name}` : e.name
|
||||
if (skip.has(r)) continue
|
||||
const full = join(d, e.name)
|
||||
if (e.isDirectory()) walk(full, r)
|
||||
else if (e.isFile()) {
|
||||
const buf = readFileSync(full)
|
||||
out[r] = { sha: sha256(buf), size: buf.length, mode: statSync(full).mode & 0o777 }
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(dir, "")
|
||||
return out
|
||||
}
|
||||
|
||||
function manifestBytes(manifest) {
|
||||
let n = 0
|
||||
for (const f of Object.values(manifest)) n += f.size
|
||||
return n
|
||||
}
|
||||
|
||||
function sameManifest(a, b) {
|
||||
const ka = Object.keys(a)
|
||||
if (ka.length !== Object.keys(b).length) return false
|
||||
return ka.every((k) => b[k] && b[k].sha === a[k].sha)
|
||||
}
|
||||
|
||||
const clip = (s, n) => (s.length > n ? s.slice(0, n) + `\n… [${s.length - n} more bytes]` : s)
|
||||
|
||||
// Run a shell command in dir, capturing bounded output. Resolves with
|
||||
// { code, stdout, stderr, timedOut }; never rejects on a non-zero exit —
|
||||
// the caller reports the code, as a shell would. The child inherits
|
||||
// the host environment except TMPDIR and XDG_CACHE_HOME, which point
|
||||
// at the workspace's scratch directories (created first, so workspaces
|
||||
// provisioned before they existed get them too): temporary files and
|
||||
// caches stay inside the workspace instead of leaking to the host /tmp.
|
||||
//
|
||||
// The process plumbing is deliberate (round-2 review, item 6): stdin
|
||||
// is closed, so a command that reads it gets EOF instead of waiting
|
||||
// out the timeout; the child leads its own process group (detached),
|
||||
// so a timeout kills the whole tree, not just /bin/sh; and the caller
|
||||
// resolves on 'exit' plus a short drain, not on 'close' — a background
|
||||
// child holding the stdout pipe open must not hold the call open.
|
||||
function runShell(command, dir, timeoutMs) {
|
||||
return new Promise((resolvePromise) => {
|
||||
ensureScratch(dir)
|
||||
const child = spawn("/bin/sh", ["-c", command], {
|
||||
cwd: dir,
|
||||
detached: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: { ...process.env, TMPDIR: join(dir, ".tmp"), XDG_CACHE_HOME: join(dir, ".cache") },
|
||||
})
|
||||
let out = "", err = "", timedOut = false, settled = false
|
||||
let timer = null
|
||||
const finish = (code) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
if (timer) clearTimeout(timer)
|
||||
resolvePromise({ code: code ?? -1, stdout: clip(out, 8192), stderr: clip(err, 8192), timedOut })
|
||||
}
|
||||
timer = setTimeout(() => {
|
||||
timedOut = true
|
||||
try { process.kill(-child.pid, "SIGKILL") } // the whole group
|
||||
catch { try { child.kill("SIGKILL") } catch { /* already gone */ } }
|
||||
// 'exit' follows the group kill; this is only a backstop
|
||||
setTimeout(() => finish(-1), 250).unref()
|
||||
}, timeoutMs)
|
||||
child.stdout.on("data", (d) => { if (out.length < 65536) out += d })
|
||||
child.stderr.on("data", (d) => { if (err.length < 65536) err += d })
|
||||
child.on("error", (e) => { err += String(e); finish(-1) })
|
||||
child.on("exit", (code) => { setTimeout(() => finish(code), 25).unref() })
|
||||
})
|
||||
}
|
||||
|
||||
// ---- sim backend ---------------------------------------------------------------
|
||||
|
||||
export class SimBackend {
|
||||
kind = "sim"
|
||||
|
||||
constructor(root) {
|
||||
this.root = root || process.env.MAGPIE_LAYERFS_HOME || join(homedir(), ".magpie-layerfs")
|
||||
this.objectsDir = join(this.root, "store", "objects")
|
||||
this.projectsDir = join(this.root, "projects")
|
||||
this.workspacesDir = join(this.root, "workspaces")
|
||||
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)
|
||||
if (!this.readAccounting())
|
||||
writeJson(this.accountingPath(), { storedBytes: this.storedBytesWalk(), logicalBytes: this.logicalBytesWalk() })
|
||||
}
|
||||
|
||||
// -- store primitives
|
||||
blobPath(sha) { return join(this.objectsDir, sha.slice(0, 2), sha) }
|
||||
hasBlob(sha) { return existsSync(this.blobPath(sha)) }
|
||||
putBlob(buf, mode = 0o644) {
|
||||
const sha = sha256(buf)
|
||||
const p = this.blobPath(sha)
|
||||
if (!existsSync(p)) {
|
||||
mkdirPrivate(dirname(p))
|
||||
writeFileMode(p, buf, mode)
|
||||
this.bumpAccounting({ storedDelta: buf.length })
|
||||
return { sha, fresh: buf.length }
|
||||
}
|
||||
return { sha, fresh: 0 }
|
||||
}
|
||||
// Byte accounting, kept incrementally in a small record so status
|
||||
// never walks the whole store: putBlob and makeCommit bump it as
|
||||
// they write. storedBytes is the bytes the store actually occupies:
|
||||
// blob bytes PLUS the commit records (each holds its checkpoint's
|
||||
// full manifest — for a wide tree that is the larger half, and it
|
||||
// was not counted before 0.7.1; round-2 review, item 7). A missing
|
||||
// record (a pre-0.7 store) is rebuilt by one walk and then
|
||||
// maintained; a pre-0.7.1 record undercounts until it is rebuilt.
|
||||
accountingPath() { return join(this.root, "accounting.json") }
|
||||
readAccounting() {
|
||||
try { return JSON.parse(readFileSync(this.accountingPath(), "utf8")) } catch { return null }
|
||||
}
|
||||
bumpAccounting({ storedDelta = 0, logicalDelta = 0 } = {}) {
|
||||
if (!storedDelta && !logicalDelta) return
|
||||
const a = this.readAccounting() ?? { storedBytes: this.storedBytesWalk(), logicalBytes: this.logicalBytesWalk() }
|
||||
a.storedBytes += storedDelta
|
||||
a.logicalBytes += logicalDelta
|
||||
writeJson(this.accountingPath(), a)
|
||||
}
|
||||
storedBytes() {
|
||||
const a = this.readAccounting()
|
||||
if (a && Number.isFinite(a.storedBytes)) return a.storedBytes
|
||||
const n = this.storedBytesWalk()
|
||||
writeJson(this.accountingPath(), { storedBytes: n, logicalBytes: this.logicalBytesWalk() })
|
||||
return n
|
||||
}
|
||||
storedBytesWalk() {
|
||||
let n = 0
|
||||
const walk = (d) => {
|
||||
for (const e of readdirSync(d, { withFileTypes: true })) {
|
||||
const full = join(d, e.name)
|
||||
if (e.isDirectory()) walk(full)
|
||||
else n += statSync(full).size
|
||||
}
|
||||
}
|
||||
walk(this.objectsDir)
|
||||
// the commit records count too: each carries a full manifest
|
||||
if (existsSync(this.projectsDir))
|
||||
for (const name of readdirSync(this.projectsDir)) {
|
||||
const cdir = join(this.projectDir(name), "commits")
|
||||
if (existsSync(cdir))
|
||||
for (const f of readdirSync(cdir)) n += statSync(join(cdir, f)).size
|
||||
}
|
||||
return n
|
||||
}
|
||||
logicalBytesWalk() {
|
||||
let n = 0
|
||||
if (!existsSync(this.projectsDir)) return 0
|
||||
for (const name of readdirSync(this.projectsDir)) {
|
||||
const cdir = join(this.projectDir(name), "commits")
|
||||
if (!existsSync(cdir)) continue
|
||||
for (const f of readdirSync(cdir)) n += JSON.parse(readFileSync(join(cdir, f), "utf8")).logicalBytes
|
||||
}
|
||||
return n
|
||||
}
|
||||
// Store every blob of a manifest that the store has not seen; returns the
|
||||
// number of genuinely new bytes written.
|
||||
storeManifestFiles(baseDir, manifest) {
|
||||
let fresh = 0
|
||||
for (const [rel, f] of Object.entries(manifest)) {
|
||||
if (!this.hasBlob(f.sha)) fresh += this.putBlob(readFileSync(join(baseDir, ...rel.split("/"))), f.mode ?? 0o644).fresh
|
||||
}
|
||||
return fresh
|
||||
}
|
||||
|
||||
// -- project / branch / commit records
|
||||
projectDir(project) { return join(this.projectsDir, project) }
|
||||
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")) }
|
||||
writeCommit(project, commit) {
|
||||
mkdirPrivate(join(this.projectDir(project), "commits"))
|
||||
writeJson(this.commitPath(project, commit.id), commit, true)
|
||||
return statSync(this.commitPath(project, commit.id)).size
|
||||
}
|
||||
branchHeadPath(project, branch) { return join(this.projectDir(project), "branches", `${encodeBranchName(branch)}.json`) }
|
||||
branchExists(project, branch) { return existsSync(this.branchHeadPath(project, branch)) }
|
||||
head(project, branch) {
|
||||
if (!this.branchExists(project, branch)) throw new Error(`no branch ${branch} in project ${project}`)
|
||||
return JSON.parse(readFileSync(this.branchHeadPath(project, branch), "utf8")).commit
|
||||
}
|
||||
setHead(project, branch, commitId) {
|
||||
mkdirPrivate(dirname(this.branchHeadPath(project, branch)))
|
||||
writeJson(this.branchHeadPath(project, branch), { commit: commitId })
|
||||
}
|
||||
listBranches(project) {
|
||||
const dir = join(this.projectDir(project), "branches")
|
||||
if (!existsSync(dir)) return []
|
||||
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 }) {
|
||||
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,
|
||||
}
|
||||
const recordBytes = this.writeCommit(project, commit)
|
||||
this.bumpAccounting({ logicalDelta: commit.logicalBytes, storedDelta: recordBytes })
|
||||
this.setHead(project, branch, id)
|
||||
return commit
|
||||
}
|
||||
|
||||
// An append-only event log (provision / fork / checkpoint), the raw
|
||||
// material for the trajectory the magpie page replays.
|
||||
recordEvent(event) {
|
||||
const path = join(this.root, "events.json")
|
||||
let events = []
|
||||
try { events = JSON.parse(readFileSync(path, "utf8")) } catch { /* first event */ }
|
||||
events.push({ t: nowIso(), ...event })
|
||||
if (events.length > 500) events = events.slice(-500)
|
||||
writeFileMode(path, JSON.stringify(events))
|
||||
}
|
||||
readEvents() {
|
||||
try { return JSON.parse(readFileSync(join(this.root, "events.json"), "utf8")) } catch { return [] }
|
||||
}
|
||||
|
||||
async ensureProject(project, sourceDir) {
|
||||
if (this.projectExists(project)) return { created: false }
|
||||
mkdirPrivate(this.projectDir(project))
|
||||
writeJson(join(this.projectDir(project), "project.json"),
|
||||
{ name: project, created: nowIso(), backend: "sim" }, true)
|
||||
let manifest = {}
|
||||
let newBytes = 0
|
||||
let skipped = []
|
||||
let src = null
|
||||
if (sourceDir) {
|
||||
src = checkSourceDir(sourceDir, { storeRoot: this.root })
|
||||
const scan = scanImportTree(src)
|
||||
manifest = scan.manifest
|
||||
skipped = scan.skipped
|
||||
newBytes = this.storeManifestFiles(src, manifest)
|
||||
}
|
||||
const commit = this.makeCommit(project, "main", null, manifest,
|
||||
src ? `Import ${src}` : "Empty project", newBytes,
|
||||
{ added: Object.keys(manifest).length, modified: 0, deleted: 0 })
|
||||
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)
|
||||
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)
|
||||
if (existsSync(join(dir, BINDING))) {
|
||||
const binding = JSON.parse(readFileSync(join(dir, BINDING), "utf8"))
|
||||
return {
|
||||
path: dir, project, branch, backend: this.kind,
|
||||
commit: binding.baseCommit, reused: true, stale: binding.baseCommit !== headId,
|
||||
}
|
||||
}
|
||||
const commit = this.readCommit(project, headId)
|
||||
mkdirPrivate(dir)
|
||||
ensureScratch(dir)
|
||||
for (const [rel, f] of Object.entries(commit.manifest)) {
|
||||
const out = join(dir, ...rel.split("/"))
|
||||
mkdirSync(dirname(out), { recursive: true })
|
||||
copyFileSync(this.blobPath(f.sha), out)
|
||||
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 })
|
||||
return {
|
||||
path: dir, project, branch, backend: this.kind, commit: headId,
|
||||
reused: false, files: commit.files, logicalBytes: commit.logicalBytes,
|
||||
...(created.created ? { projectCreated: true } : {}),
|
||||
...(created.skipped?.length ? {
|
||||
importSkipped: created.skipped.length,
|
||||
skippedSecrets: created.skipped.slice(0, 5),
|
||||
} : {}),
|
||||
}
|
||||
}
|
||||
|
||||
async checkpoint(project, branch = "main", message = "") {
|
||||
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)
|
||||
const prev = this.readCommit(project, parent)
|
||||
const manifest = scanTree(dir, scanSkip())
|
||||
const newBytes = this.storeManifestFiles(dir, manifest)
|
||||
let added = 0, modified = 0, deleted = 0
|
||||
for (const [rel, f] of Object.entries(manifest)) {
|
||||
if (!prev.manifest[rel]) added++
|
||||
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 })
|
||||
writeJson(join(dir, BINDING), { project, branch, baseCommit: commit.id }, true)
|
||||
const stored = this.storedBytes()
|
||||
return {
|
||||
commit: commit.id, parent, branch, message: commit.message,
|
||||
added, modified, deleted, files: commit.files,
|
||||
logicalBytes: commit.logicalBytes, newBytes,
|
||||
storedBytes: stored, savedBytes: commit.logicalBytes - newBytes,
|
||||
}
|
||||
}
|
||||
|
||||
async fork(project, branch, from = "main") {
|
||||
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 })
|
||||
return { project, branch, from, commit: headId, copiedBytes: 0 }
|
||||
}
|
||||
|
||||
// Publish a branch's head as main's new Layer. The guard is the lesson
|
||||
// of a real dsh run, where publishing from a stale branch replaced
|
||||
// main and dropped it from 238 tests to 38: by default main must be
|
||||
// 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 } = {}) {
|
||||
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)
|
||||
const mainHead = this.head(project, "main")
|
||||
const layers = this.readEvents().filter((e) => e.kind === "publish" && e.project === project).length
|
||||
if (branchHead === mainHead)
|
||||
return { project, branch, layer: layers, commit: branchHead, alreadyPublished: true, overwrote: false }
|
||||
const chain = new Set()
|
||||
let id = branchHead
|
||||
while (id) { chain.add(id); id = this.readCommit(project, id).parent }
|
||||
const fastForward = chain.has(mainHead)
|
||||
if (!fastForward && !force)
|
||||
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 })
|
||||
return { project, branch, layer, commit: branchHead, previousMain: mainHead, overwrote: !fastForward }
|
||||
}
|
||||
|
||||
// Run a command in the branch's workspace and checkpoint whatever it
|
||||
// changed as one commit — the dsh shape, where every bash call is
|
||||
// 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) {
|
||||
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)
|
||||
if (!existsSync(join(dir, BINDING))) throw new Error(`no workspace for ${project}/${branch}; provision it first`)
|
||||
const prev = this.readCommit(project, this.head(project, branch))
|
||||
const r = await runShell(command, dir, Math.min(Math.max(100, timeoutMs || 50000), 55000))
|
||||
const manifest = scanTree(dir, scanSkip())
|
||||
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)}`)
|
||||
commit = c.commit
|
||||
}
|
||||
return {
|
||||
project, branch, exitCode: r.code, ...(r.timedOut ? { timedOut: true } : {}),
|
||||
stdout: r.stdout, stderr: r.stderr, changed, commit,
|
||||
}
|
||||
}
|
||||
|
||||
async history(project, branch = "main", limit = 20) {
|
||||
let id = this.head(project, branch)
|
||||
const out = []
|
||||
while (id && out.length < limit) {
|
||||
const c = this.readCommit(project, id)
|
||||
out.push({
|
||||
commit: c.id, message: c.message, time: c.time,
|
||||
files: c.files, logicalBytes: c.logicalBytes, newBytes: c.newBytes,
|
||||
})
|
||||
id = c.parent
|
||||
}
|
||||
return { project, branch, commits: out }
|
||||
}
|
||||
|
||||
// One project's slice of the recorded trajectory, oldest first per
|
||||
// branch. Commits carry their delta and byte accounting.
|
||||
async trajectoryProject(name) {
|
||||
if (!this.projectExists(name)) return null
|
||||
const branches = []
|
||||
for (const branch of this.listBranches(name)) {
|
||||
// the branch's OWN checkpoints: walk its whole chain (a publish
|
||||
// may have moved main's head onto another branch's work) and
|
||||
// keep only the commits made on this branch — ancestors belong
|
||||
// to the bough they were committed on
|
||||
const commits = []
|
||||
let id = this.head(name, branch)
|
||||
while (id) {
|
||||
const c = this.readCommit(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 },
|
||||
})
|
||||
}
|
||||
id = c.parent
|
||||
}
|
||||
branches.push({ name: branch, commits: commits.reverse() })
|
||||
}
|
||||
return { name, branches }
|
||||
}
|
||||
|
||||
// The whole recorded trajectory: what the magpie page replays.
|
||||
async trajectory() {
|
||||
const projects = []
|
||||
if (existsSync(this.projectsDir)) {
|
||||
for (const name of readdirSync(this.projectsDir).sort()) {
|
||||
const slice = await this.trajectoryProject(name)
|
||||
if (slice) projects.push(slice)
|
||||
}
|
||||
}
|
||||
const st = await this.status()
|
||||
return {
|
||||
generatedAt: nowIso(), backend: this.kind, projects,
|
||||
events: this.readEvents(),
|
||||
totals: {
|
||||
logicalBytes: st.logicalBytes, storedBytes: st.storedBytes,
|
||||
savedBytes: st.savedBytes, dedupRatio: st.dedupRatio, workspaces: st.workspaces,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// The recorded trajectory is built ON DEMAND by trajectory() and
|
||||
// by nothing else. An earlier version also kept a trajectory.json
|
||||
// in the store refreshed after every tool call — even scoped to
|
||||
// one project that re-walked the branch's whole chain, so the cost
|
||||
// of every call grew with the history, for a file the page cannot
|
||||
// read (its bridge serves a fixed host list) and nothing else did
|
||||
// (round-2 review, item 3). Removed in 0.7.1: no tool call creates
|
||||
// or updates a trajectory.json anymore. The page keeps its bundled
|
||||
// sample until the host can serve plugin data to a page.
|
||||
|
||||
async resolve(project, branch = "main", inner = "") {
|
||||
const headId = this.head(project, branch)
|
||||
const dir = this.workspaceDir(project, branch)
|
||||
if (!existsSync(join(dir, BINDING)))
|
||||
return { path: null, project, branch, commit: headId, provisioned: false, hint: "call provision to materialize this workspace" }
|
||||
const out = { path: inner ? join(dir, ...inner.split("/")) : dir, project, branch, commit: headId, provisioned: true }
|
||||
if (inner) {
|
||||
const commit = this.readCommit(project, headId)
|
||||
const f = commit.manifest[inner]
|
||||
if (f) { out.sha = f.sha; out.size = f.size; out.inHead = true }
|
||||
else out.inHead = existsSync(out.path)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
async status() {
|
||||
const projects = []
|
||||
if (existsSync(this.projectsDir)) {
|
||||
for (const name of readdirSync(this.projectsDir).sort()) {
|
||||
if (!this.projectExists(name)) continue
|
||||
const branches = this.listBranches(name)
|
||||
const cdir = join(this.projectDir(name), "commits")
|
||||
const commits = existsSync(cdir) ? readdirSync(cdir).length : 0
|
||||
projects.push({ name, branches, commits })
|
||||
}
|
||||
}
|
||||
const stored = this.storedBytes()
|
||||
const a = this.readAccounting()
|
||||
const logical = a && Number.isFinite(a.logicalBytes) ? a.logicalBytes : this.logicalBytesWalk()
|
||||
const workspaces = countWorkspaces(this.workspacesDir)
|
||||
return {
|
||||
backend: this.kind, root: this.root, projects, workspaces,
|
||||
logicalBytes: logical, storedBytes: stored,
|
||||
savedBytes: Math.max(0, logical - stored),
|
||||
dedupRatio: stored ? +(logical / stored).toFixed(2) : 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 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 the magpie-community package " +
|
||||
"(it returns in a follow-up PR once @layerfs/sdk is published to npm with a version to pin; " +
|
||||
"it is developed in the standalone repo, Mola-maker/magpie-layerfs). " +
|
||||
"Unset MAGPIE_LAYERFS_BACKEND / MAGPIE_LAYERFS_NATIVE and the \"native\" option to use the sim backend."
|
||||
|
||||
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(`MAGPIE_LAYERFS_BACKEND is auto or sim in this package; got ${JSON.stringify(want)}`)
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
import { afterAll, expect, test } from "bun:test"
|
||||
import { createHash } from "node:crypto"
|
||||
import {
|
||||
chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync,
|
||||
symlinkSync, writeFileSync,
|
||||
} from "node:fs"
|
||||
import { homedir, tmpdir } from "node:os"
|
||||
import { basename, dirname, join } from "node:path"
|
||||
import { LayerfsTools } from "./index.mjs"
|
||||
import {
|
||||
IMPORT_MAX_FILES, SimBackend, checkSourceDir, createBackend, scanImportTree,
|
||||
} from "./layerfs.mjs"
|
||||
|
||||
const sha = (s) => createHash("sha256").update(s).digest("hex")
|
||||
|
||||
// Hygiene: every temp dir a test makes is registered and removed, and
|
||||
// the process env the suite mutates is restored whole at the end —
|
||||
// a test run leaves nothing behind but its results.
|
||||
const envSnapshot = { ...process.env }
|
||||
const tmpDirs = []
|
||||
function mkTmp(prefix, base = tmpdir()) {
|
||||
const d = mkdtempSync(join(base, prefix))
|
||||
tmpDirs.push(d)
|
||||
return d
|
||||
}
|
||||
afterAll(() => {
|
||||
for (const d of tmpDirs) rmSync(d, { recursive: true, force: true })
|
||||
for (const k of Object.keys(process.env)) if (!(k in envSnapshot)) delete process.env[k]
|
||||
Object.assign(process.env, envSnapshot)
|
||||
})
|
||||
|
||||
function fixture() {
|
||||
const src = mkTmp("layerfs-src-")
|
||||
mkdirSync(join(src, "docs"), { recursive: true })
|
||||
writeFileSync(join(src, "README.md"), "hello layerfs\n")
|
||||
writeFileSync(join(src, "docs", "a.txt"), "A".repeat(1000))
|
||||
writeFileSync(join(src, "docs", "b.txt"), "A".repeat(1000)) // identical to a.txt on purpose
|
||||
writeFileSync(join(src, "code.js"), "console.log(1)\n")
|
||||
return src
|
||||
}
|
||||
|
||||
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
|
||||
const { tool } = await LayerfsTools({ directory: mkTmp("magpie-config-") }, opts)
|
||||
// provision's source is a required argument since 0.7.0: the wrapper
|
||||
// passes the fixture explicitly, the way a caller now must
|
||||
const call = (name, args) => tool[name].execute(
|
||||
name === "provision" && args.source === undefined ? { ...args, source: src } : args,
|
||||
{ agent: "test", abort: AbortSignal.timeout(5000) })
|
||||
return { call, home, src, tool }
|
||||
}
|
||||
|
||||
test("gives eight tools, each with a JSON Schema and an execute", async () => {
|
||||
const { tool } = await LayerfsTools({})
|
||||
expect(Object.keys(tool).sort()).toEqual(["checkpoint", "exec", "fork", "history", "provision", "publish", "resolve", "status"])
|
||||
for (const [name, t] of Object.entries(tool)) {
|
||||
expect(name).toMatch(/^[A-Za-z0-9_-]{1,48}$/)
|
||||
expect(t.description.length).toBeGreaterThan(40)
|
||||
expect(typeof t.execute).toBe("function")
|
||||
expect(t.args.type).toBe("object")
|
||||
}
|
||||
// source is a required provision argument; there is no default
|
||||
expect(tool.provision.args.required).toEqual(["project", "source"])
|
||||
})
|
||||
|
||||
test("provision imports the source once, then answers the same path without copying", async () => {
|
||||
const { call } = await simTools()
|
||||
const first = await call("provision", { project: "website" })
|
||||
expect(first.projectCreated).toBe(true)
|
||||
expect(first.reused).toBe(false)
|
||||
expect(first.files).toBe(4)
|
||||
expect(readFileSync(join(first.path, "README.md"), "utf8")).toBe("hello layerfs\n")
|
||||
const again = await call("provision", { project: "website" })
|
||||
expect(again.path).toBe(first.path)
|
||||
expect(again.reused).toBe(true)
|
||||
expect(again.stale).toBe(false)
|
||||
})
|
||||
|
||||
test("checkpoint stores only the blobs that changed", async () => {
|
||||
const { call } = await simTools()
|
||||
const ws = await call("provision", { project: "website" })
|
||||
writeFileSync(join(ws.path, "code.js"), "console.log(2)\n") // modified, 15 bytes
|
||||
writeFileSync(join(ws.path, "new.txt"), "brand new\n") // added, 10 bytes
|
||||
const cp = await call("checkpoint", { project: "website", message: "second take" })
|
||||
expect(cp.added).toBe(1)
|
||||
expect(cp.modified).toBe(1)
|
||||
expect(cp.deleted).toBe(0)
|
||||
expect(cp.newBytes).toBe(15 + 10)
|
||||
expect(cp.logicalBytes).toBe(14 + 1000 + 1000 + 15 + 10)
|
||||
expect(cp.savedBytes).toBe(cp.logicalBytes - cp.newBytes)
|
||||
})
|
||||
|
||||
test("fork copies no bytes and shares the history", async () => {
|
||||
const { call } = await simTools()
|
||||
await call("provision", { project: "website" })
|
||||
const before = await call("status", {})
|
||||
const f = await call("fork", { project: "website", branch: "agent-2" })
|
||||
expect(f.copiedBytes).toBe(0)
|
||||
const after = await call("status", {})
|
||||
expect(after.storedBytes).toBe(before.storedBytes)
|
||||
const ws2 = await call("provision", { project: "website", branch: "agent-2" })
|
||||
expect(readFileSync(join(ws2.path, "docs", "a.txt"), "utf8")).toBe("A".repeat(1000))
|
||||
const hist = await call("history", { project: "website", branch: "agent-2" })
|
||||
expect(hist.commits.length).toBe(1)
|
||||
expect(hist.commits[0].message).toContain("Import")
|
||||
await expect(call("fork", { project: "website", branch: "agent-2" })).rejects.toThrow("already exists")
|
||||
})
|
||||
|
||||
test("identical files are stored once (dedup at import)", async () => {
|
||||
const { call, home } = await simTools()
|
||||
await call("provision", { project: "website" })
|
||||
const st = await call("status", {})
|
||||
// unique contents: "hello layerfs\n" (14) + "A"*1000 (1000) + "console.log(1)\n" (15)
|
||||
// storedBytes is those blobs PLUS the import's commit record, whose
|
||||
// manifest the accounting has counted since 0.7.1 (r2 item 7)
|
||||
const cdir = join(home, "projects", "website", "commits")
|
||||
const recordBytes = readdirSync(cdir).reduce((n, f) => n + statSync(join(cdir, f)).size, 0)
|
||||
expect(recordBytes).toBeGreaterThan(0)
|
||||
expect(st.storedBytes).toBe(14 + 1000 + 15 + recordBytes)
|
||||
expect(st.logicalBytes).toBe(14 + 1000 + 1000 + 15)
|
||||
expect(st.dedupRatio).toBeGreaterThan(1)
|
||||
})
|
||||
|
||||
test("resolve answers a path and a file's hash without copying", async () => {
|
||||
const { call } = await simTools()
|
||||
const ws = await call("provision", { project: "website" })
|
||||
const root = await call("resolve", { project: "website" })
|
||||
expect(root.path).toBe(ws.path)
|
||||
const file = await call("resolve", { project: "website", path: "docs/a.txt" })
|
||||
expect(file.path).toBe(join(ws.path, "docs", "a.txt"))
|
||||
expect(file.sha).toBe(sha("A".repeat(1000)))
|
||||
expect(file.size).toBe(1000)
|
||||
})
|
||||
|
||||
test("names and paths are validated", async () => {
|
||||
const { call } = await simTools()
|
||||
await expect(call("provision", { project: "Bad Name" })).rejects.toThrow("project name")
|
||||
await call("provision", { project: "website" })
|
||||
await expect(call("resolve", { project: "website", path: "../escape" })).rejects.toThrow("stay inside")
|
||||
})
|
||||
|
||||
test("a workspace file survives on disk where resolve says it is", async () => {
|
||||
const { call } = await simTools()
|
||||
await call("provision", { project: "website" })
|
||||
const file = await call("resolve", { project: "website", path: "code.js" })
|
||||
expect(existsSync(file.path)).toBe(true)
|
||||
})
|
||||
|
||||
test("publish moves main forward to the branch head, as a numbered Layer", async () => {
|
||||
const { call } = await simTools()
|
||||
const ws = 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, "feature.js"), "export const f = 1\n")
|
||||
const cp = await call("checkpoint", { project: "website", branch: "feat", message: "add feature" })
|
||||
const pub = await call("publish", { project: "website", branch: "feat" })
|
||||
expect(pub.layer).toBe(1)
|
||||
expect(pub.commit).toBe(cp.commit)
|
||||
expect(pub.overwrote).toBe(false)
|
||||
const main = await call("history", { project: "website", branch: "main" })
|
||||
expect(main.commits[0].commit).toBe(cp.commit) // main now answers for the feature
|
||||
expect(main.commits[0].message).toBe("add feature")
|
||||
const again = await call("publish", { project: "website", branch: "feat" })
|
||||
expect(again.alreadyPublished).toBe(true)
|
||||
expect(ws.path).toBeTruthy()
|
||||
})
|
||||
|
||||
test("publish refuses to drop a main that moved, unless forced", async () => {
|
||||
const { call } = 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, "feature.js"), "f\n")
|
||||
await call("checkpoint", { project: "website", branch: "feat", message: "feature" })
|
||||
// main advances on its own after the fork: the branch no longer contains it
|
||||
const mainWs = await call("provision", { project: "website", branch: "main" })
|
||||
writeFileSync(join(mainWs.path, "hotfix.js"), "h\n")
|
||||
const hot = await call("checkpoint", { project: "website", branch: "main", message: "hotfix" })
|
||||
await expect(call("publish", { project: "website", branch: "feat" })).rejects.toThrow("main has moved")
|
||||
const forced = await call("publish", { project: "website", branch: "feat", force: true })
|
||||
expect(forced.overwrote).toBe(true)
|
||||
expect(forced.previousMain).toBe(hot.commit)
|
||||
await expect(call("publish", { project: "website", branch: "main" })).rejects.toThrow("other than main")
|
||||
})
|
||||
|
||||
test("exec runs in the workspace and checkpoints what changed", async () => {
|
||||
const { call } = await simTools()
|
||||
await call("provision", { project: "website" })
|
||||
const before = await call("history", { project: "website" })
|
||||
const r = await call("exec", { project: "website", command: "echo built > build.log && echo hello" })
|
||||
expect(r.exitCode).toBe(0)
|
||||
expect(r.stdout).toContain("hello")
|
||||
expect(r.changed).toBe(true)
|
||||
expect(r.commit).toBeTruthy()
|
||||
const after = await call("history", { project: "website" })
|
||||
expect(after.commits.length).toBe(before.commits.length + 1)
|
||||
expect(after.commits[0].message).toContain("exec:")
|
||||
const noop = await call("exec", { project: "website", command: "true" })
|
||||
expect(noop.changed).toBe(false)
|
||||
expect(noop.commit).toBeNull()
|
||||
const failed = await call("exec", { project: "website", command: "echo x > partial.txt; exit 3" })
|
||||
expect(failed.exitCode).toBe(3)
|
||||
expect(failed.changed).toBe(true) // a failing command's edits are still history
|
||||
})
|
||||
|
||||
test("exec redirects TMPDIR and the cache home into the workspace scratch dirs", async () => {
|
||||
const { call } = await simTools()
|
||||
const ws = await call("provision", { project: "website" })
|
||||
// provision pre-creates both scratch directories
|
||||
expect(existsSync(join(ws.path, ".tmp"))).toBe(true)
|
||||
expect(existsSync(join(ws.path, ".cache"))).toBe(true)
|
||||
const r = await call("exec", {
|
||||
project: "website",
|
||||
command: 'echo "$TMPDIR" && echo scratch > "$TMPDIR/probe.txt" && echo cache > "$XDG_CACHE_HOME/probe.txt"',
|
||||
})
|
||||
expect(r.exitCode).toBe(0)
|
||||
expect(r.stdout).toContain(join(ws.path, ".tmp")) // $TMPDIR points inside the workspace
|
||||
expect(readFileSync(join(ws.path, ".tmp", "probe.txt"), "utf8")).toBe("scratch\n")
|
||||
expect(readFileSync(join(ws.path, ".cache", "probe.txt"), "utf8")).toBe("cache\n")
|
||||
// scratch is not history: a run that touched only scratch commits nothing
|
||||
expect(r.changed).toBe(false)
|
||||
expect(r.commit).toBeNull()
|
||||
})
|
||||
|
||||
test("checkpoint never captures the scratch directories", async () => {
|
||||
const { call } = await simTools()
|
||||
const ws = await call("provision", { project: "website" })
|
||||
writeFileSync(join(ws.path, ".tmp", "junk.txt"), "junk\n")
|
||||
writeFileSync(join(ws.path, ".cache", "junk.txt"), "junk\n")
|
||||
writeFileSync(join(ws.path, "real.txt"), "real\n") // the one real change, 5 bytes
|
||||
const cp = await call("checkpoint", { project: "website", message: "with scratch present" })
|
||||
expect(cp.added).toBe(1) // real.txt only — the scratch files are not counted
|
||||
expect(cp.modified).toBe(0)
|
||||
expect(cp.deleted).toBe(0)
|
||||
expect(cp.files).toBe(5) // the 4 imported files + real.txt
|
||||
expect(cp.newBytes).toBe(5)
|
||||
expect(cp.logicalBytes).toBe(14 + 1000 + 1000 + 15 + 5)
|
||||
// the scratch content itself stays put in the live workspace
|
||||
expect(readFileSync(join(ws.path, ".tmp", "junk.txt"), "utf8")).toBe("junk\n")
|
||||
expect(readFileSync(join(ws.path, ".cache", "junk.txt"), "utf8")).toBe("junk\n")
|
||||
})
|
||||
|
||||
// ---- the review's findings, one regression test each -------------------------
|
||||
|
||||
test("item 1: provision has no default source — the host's config directory is never imported", async () => {
|
||||
const home = mkTmp("layerfs-home-")
|
||||
process.env.MAGPIE_LAYERFS_HOME = home
|
||||
process.env.MAGPIE_LAYERFS_BACKEND = "sim"
|
||||
const cfg = mkTmp("magpie-config-")
|
||||
writeFileSync(join(cfg, "plugin-auth.json"), JSON.stringify({ token: "secret" }))
|
||||
mkdirSync(join(cfg, "sub"))
|
||||
const { tool } = await LayerfsTools({ directory: cfg })
|
||||
const call = (name, args) => tool[name].execute(args, { agent: "test", abort: AbortSignal.timeout(5000) })
|
||||
// no source at all
|
||||
await expect(call("provision", { project: "website" })).rejects.toThrow("source is required")
|
||||
// the config directory itself, a directory under it, and a parent of it
|
||||
await expect(call("provision", { project: "website", source: cfg })).rejects.toThrow("refusing to import")
|
||||
await expect(call("provision", { project: "website", source: join(cfg, "sub") })).rejects.toThrow("refusing to import")
|
||||
await expect(call("provision", { project: "website", source: tmpdir() })).rejects.toThrow("refusing to import")
|
||||
// and the home directory
|
||||
await expect(call("provision", { project: "website", source: homedir() })).rejects.toThrow("refusing to import")
|
||||
// nothing was imported anywhere along the way
|
||||
const st = await call("status", {})
|
||||
expect(st.projects).toEqual([])
|
||||
})
|
||||
|
||||
test("item 2: exec is disabled by default and runs only on the user's opt-in", async () => {
|
||||
const off = await simTools({}) // no plugin options, no env switch
|
||||
await off.call("provision", { project: "website" })
|
||||
await expect(off.call("exec", { project: "website", command: "echo hi > hi.txt" }))
|
||||
.rejects.toThrow("disabled by default")
|
||||
const hist = await off.call("history", { project: "website" })
|
||||
expect(hist.commits.length).toBe(1) // the refused exec committed nothing
|
||||
// the environment switch turns it on for the same tools
|
||||
process.env.MAGPIE_LAYERFS_EXEC = "1"
|
||||
try {
|
||||
const r = await off.call("exec", { project: "website", command: "echo hi > hi.txt" })
|
||||
expect(r.exitCode).toBe(0)
|
||||
expect(r.changed).toBe(true)
|
||||
} finally {
|
||||
delete process.env.MAGPIE_LAYERFS_EXEC
|
||||
}
|
||||
// and the plugin option turns it on without the environment (the
|
||||
// other exec tests run through simTools' default { exec: true })
|
||||
const on = await simTools({ exec: true })
|
||||
await on.call("provision", { project: "website" })
|
||||
const r2 = await on.call("exec", { project: "website", command: "true" })
|
||||
expect(r2.exitCode).toBe(0)
|
||||
})
|
||||
|
||||
test("item 3: an import skips secret-shaped files and reports them", async () => {
|
||||
const { call, src } = await simTools()
|
||||
writeFileSync(join(src, ".env"), "TOKEN=x\n")
|
||||
writeFileSync(join(src, "docs", ".env.local"), "TOKEN=y\n")
|
||||
mkdirSync(join(src, ".git"))
|
||||
writeFileSync(join(src, ".git", "config"), "[core]\n")
|
||||
writeFileSync(join(src, "id_rsa"), "-----BEGIN-----\n")
|
||||
writeFileSync(join(src, "cert.pem"), "-----BEGIN-----\n")
|
||||
mkdirSync(join(src, "sub", ".ssh"), { recursive: true })
|
||||
writeFileSync(join(src, "sub", ".ssh", "known_hosts"), "host\n")
|
||||
const ws = await call("provision", { project: "website" })
|
||||
expect(ws.files).toBe(4) // only the fixture's real files
|
||||
expect(ws.importSkipped).toBe(6) // .env, docs/.env.local, .git, id_rsa, cert.pem, sub/.ssh
|
||||
expect(ws.skippedSecrets).toContain(".env")
|
||||
expect(existsSync(join(ws.path, ".env"))).toBe(false)
|
||||
expect(existsSync(join(ws.path, "id_rsa"))).toBe(false)
|
||||
expect(existsSync(join(ws.path, ".git"))).toBe(false)
|
||||
const st = await call("status", {})
|
||||
expect(st.logicalBytes).toBe(14 + 1000 + 1000 + 15) // none of the secrets' bytes either
|
||||
})
|
||||
|
||||
test("item 3: an import over the file limit is refused, not swept in", () => {
|
||||
const src = mkTmp("layerfs-big-")
|
||||
for (let i = 0; i <= IMPORT_MAX_FILES; i++) writeFileSync(join(src, `f${i}.txt`), "")
|
||||
expect(() => scanImportTree(src)).toThrow("import limit")
|
||||
}, 30000)
|
||||
|
||||
test("item 4: the store is private, and a file's mode survives the store", async () => {
|
||||
const { call, home, src } = await simTools()
|
||||
writeFileSync(join(src, "secret.txt"), "s3cret\n")
|
||||
chmodSync(join(src, "secret.txt"), 0o600)
|
||||
const ws = await call("provision", { project: "website" })
|
||||
const mode = (p) => statSync(p).mode & 0o777
|
||||
expect(mode(join(home, "store"))).toBe(0o700)
|
||||
expect(mode(join(home, "projects"))).toBe(0o700)
|
||||
expect(mode(join(home, "workspaces"))).toBe(0o700)
|
||||
expect(mode(ws.path)).toBe(0o700)
|
||||
expect(mode(join(ws.path, "secret.txt"))).toBe(0o600) // 0600 in, 0600 out
|
||||
expect(mode(join(ws.path, "README.md"))).toBe(mode(join(src, "README.md"))) // the source's own mode, kept
|
||||
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" })
|
||||
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")
|
||||
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")
|
||||
const before = readFileSync(pageFile, "utf8")
|
||||
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)
|
||||
// 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)
|
||||
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")
|
||||
expect(traj.totals.logicalBytes).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
test("items 9+10: slash branches are distinct, flat, and listed everywhere", async () => {
|
||||
const { call } = await simTools()
|
||||
await call("provision", { project: "website" })
|
||||
await call("fork", { project: "website", branch: "feat/x" })
|
||||
await call("fork", { project: "website", branch: "feat__x" })
|
||||
const a = await call("provision", { project: "website", branch: "feat/x" })
|
||||
const b = await call("provision", { project: "website", branch: "feat__x" })
|
||||
expect(a.path).not.toBe(b.path) // feat/x and feat__x no longer collide on one directory
|
||||
writeFileSync(join(a.path, "only-x.txt"), "x\n")
|
||||
const cp = await call("checkpoint", { project: "website", branch: "feat/x", message: "x work" })
|
||||
expect(cp.added).toBe(1)
|
||||
const st = await call("status", {})
|
||||
expect(st.projects[0].branches).toEqual(["feat/x", "feat__x", "main"]) // slash branches are listed
|
||||
const h = await call("history", { project: "website", branch: "feat/x" })
|
||||
expect(h.commits[0].message).toBe("x work")
|
||||
const h2 = await call("history", { project: "website", branch: "feat__x" })
|
||||
expect(h2.commits[0].message).toContain("Import")
|
||||
const traj = await new SimBackend(st.root).trajectory()
|
||||
expect(traj.projects[0].branches.map((x) => x.name).sort()).toEqual(["feat/x", "feat__x", "main"])
|
||||
})
|
||||
|
||||
// ---- the round-2 review's findings, one regression test each ------------------
|
||||
|
||||
test("r2 item 1: the source guard compares real paths — a symlink to a refused directory is refused", async () => {
|
||||
const cfg = mkTmp("magpie-config-")
|
||||
writeFileSync(join(cfg, "plugin-auth.json"), JSON.stringify({ token: "secret" }))
|
||||
// (a) a symlink whose target is the refused directory: resolve()
|
||||
// spellings differ, real paths do not
|
||||
const link = join(mkTmp("layerfs-links-"), "cfglink")
|
||||
symlinkSync(cfg, link)
|
||||
expect(() => checkSourceDir(link, { configDir: cfg })).toThrow("refusing to import")
|
||||
// a symlink PARENT of the source is seen through the same way
|
||||
const inner = join(mkTmp("layerfs-outer-"), "proj")
|
||||
mkdirSync(inner)
|
||||
const parentLink = join(mkTmp("layerfs-links-"), "parentlink")
|
||||
symlinkSync(dirname(inner), parentLink)
|
||||
expect(() => checkSourceDir(join(parentLink, "proj"), { configDir: dirname(inner) })).toThrow("refusing to import")
|
||||
// and end to end: provision through the symlink is refused, nothing imported
|
||||
const home = mkTmp("layerfs-home-")
|
||||
process.env.MAGPIE_LAYERFS_HOME = home
|
||||
process.env.MAGPIE_LAYERFS_BACKEND = "sim"
|
||||
const { tool } = await LayerfsTools({ directory: cfg }, {})
|
||||
const call = (name, args) => tool[name].execute(args, { agent: "test", abort: AbortSignal.timeout(5000) })
|
||||
await expect(call("provision", { project: "website", source: link })).rejects.toThrow("refusing to import")
|
||||
const st = await call("status", {})
|
||||
expect(st.projects).toEqual([])
|
||||
})
|
||||
|
||||
test("r2 item 1: the source guard folds case — a case-variant spelling of a refused root is refused", () => {
|
||||
const mixed = mkTmp("Layerfs-Case-")
|
||||
// the same directory, named by a differently-cased spelling: on a
|
||||
// case-insensitive volume that spelling IS the directory; the
|
||||
// guard's case-folded realpath comparison refuses it everywhere,
|
||||
// including here, where the volume is case-sensitive and the
|
||||
// lowercase spelling does not even exist as a path
|
||||
const lowerSpelling = join(dirname(mixed), basename(mixed).toLowerCase())
|
||||
expect(lowerSpelling).not.toBe(mixed)
|
||||
expect(() => checkSourceDir(mixed, { configDir: lowerSpelling })).toThrow("refusing to import")
|
||||
// the review's "~/.Config/Magpie" shape: an upper-case spelling of
|
||||
// the source itself — refused as the config dir where the volume
|
||||
// folds case, "not a directory" where it does not; never imported
|
||||
const variant = join(dirname(mixed), basename(mixed).toUpperCase())
|
||||
expect(() => checkSourceDir(variant, { configDir: mixed })).toThrow(/refusing to import|not a directory/)
|
||||
// a refused root that does not exist at all must not make the guard throw the wrong error
|
||||
const ok = mkTmp("layerfs-oksrc-")
|
||||
expect(checkSourceDir(ok, { configDir: join(mkTmp("layerfs-gone-"), "nope") })).toBe(ok)
|
||||
})
|
||||
|
||||
test("r2 item 2: project a branch b--c and project a--b branch c never share a workspace", async () => {
|
||||
const { call } = await simTools() // its wrapper supplies the (ignored) source branch provisions require
|
||||
const dirA = mkTmp("layerfs-srcA-")
|
||||
writeFileSync(join(dirA, "a.txt"), "from A\n")
|
||||
const dirB = mkTmp("layerfs-srcB-")
|
||||
writeFileSync(join(dirB, "b.txt"), "from B\n")
|
||||
await call("provision", { project: "a", source: dirA })
|
||||
await call("fork", { project: "a", branch: "b--c" })
|
||||
const pa = await call("provision", { project: "a", branch: "b--c" })
|
||||
await call("provision", { project: "a--b", source: dirB })
|
||||
await call("fork", { project: "a--b", branch: "c" })
|
||||
const pb = await call("provision", { project: "a--b", branch: "c" })
|
||||
// pre-fix both were workspaces/a--b--c, and pb answered a's checkout
|
||||
expect(pb.path).not.toBe(pa.path)
|
||||
expect(pb.reused).toBe(false)
|
||||
expect(readFileSync(join(pb.path, "b.txt"), "utf8")).toBe("from B\n")
|
||||
const st = await call("status", {})
|
||||
expect(st.workspaces).toBe(4) // a/main, a/b--c, a--b/main, a--b/c — counted across project dirs
|
||||
writeFileSync(join(pb.path, "b2.txt"), "more B\n")
|
||||
const cp = await call("checkpoint", { project: "a--b", branch: "c", message: "B work" })
|
||||
expect(cp.added).toBe(1)
|
||||
expect(cp.deleted).toBe(0) // pre-fix this committed a's files into a--b (added 1, deleted 1)
|
||||
const ha = await call("history", { project: "a", branch: "b--c" })
|
||||
expect(ha.commits).toHaveLength(1) // a's branch untouched by a--b's checkpoint
|
||||
})
|
||||
|
||||
test("r2 item 2: branches Main and main are distinct, on disk as in the model", async () => {
|
||||
const { call } = await simTools()
|
||||
await call("provision", { project: "website" })
|
||||
await call("fork", { project: "website", branch: "Main" })
|
||||
const lower = await call("provision", { project: "website", branch: "main" })
|
||||
const upper = await call("provision", { project: "website", branch: "Main" })
|
||||
// %4Dain vs main: distinct files even on a case-insensitive volume —
|
||||
// pre-fix they shared branches/main.json and one workspace
|
||||
expect(upper.path).not.toBe(lower.path)
|
||||
writeFileSync(join(upper.path, "upper.txt"), "upper\n")
|
||||
await call("checkpoint", { project: "website", branch: "Main", message: "upper work" })
|
||||
const mainHist = await call("history", { project: "website", branch: "main" })
|
||||
expect(mainHist.commits).toHaveLength(1) // a checkpoint on Main did not move main's head
|
||||
const st = await call("status", {})
|
||||
expect(st.projects[0].branches).toEqual(["Main", "main"])
|
||||
})
|
||||
|
||||
test("r2 item 6: exec's stdin is closed — a command that reads it finishes at once", async () => {
|
||||
const { call } = await simTools()
|
||||
await call("provision", { project: "website" })
|
||||
const t0 = Date.now()
|
||||
const r = await call("exec", { project: "website", command: "cat", timeoutMs: 5000 })
|
||||
expect(r.timedOut).toBeUndefined()
|
||||
expect(r.exitCode).toBe(0)
|
||||
expect(Date.now() - t0).toBeLessThan(3000) // pre-fix: an open stdin pipe held it to the full timeout
|
||||
})
|
||||
|
||||
test("r2 item 6: background children cannot hold an exec call open, and a timeout kills the group", async () => {
|
||||
const { call } = await simTools()
|
||||
await call("provision", { project: "website" })
|
||||
const t0 = Date.now()
|
||||
const r = await call("exec", { project: "website", command: "sleep 6 & echo started", timeoutMs: 1000 })
|
||||
expect(r.stdout).toContain("started")
|
||||
expect(Date.now() - t0).toBeLessThan(4000) // pre-fix: ~6011 ms, waiting for 'close' on the held pipe
|
||||
const t1 = Date.now()
|
||||
const r2 = await call("exec", { project: "website", command: "sleep 30", timeoutMs: 1000 })
|
||||
expect(r2.timedOut).toBe(true)
|
||||
expect(Date.now() - t1).toBeLessThan(4000) // the group kill lands; no orphaned sleep outlives the call
|
||||
})
|
||||
|
||||
test("r2 item 7: storedBytes grows by the commit record's size, not just the changed blobs", async () => {
|
||||
const { call, home } = await simTools()
|
||||
const ws = await call("provision", { project: "website" })
|
||||
const before = await call("status", {})
|
||||
writeFileSync(join(ws.path, "tiny.txt"), "x") // a 1-byte change on the imported tree
|
||||
const cp = await call("checkpoint", { project: "website", message: "tiny" })
|
||||
expect(cp.newBytes).toBe(1)
|
||||
const after = await call("status", {})
|
||||
const recordBytes = statSync(join(home, "projects", "website", "commits", `${cp.commit}.json`)).size
|
||||
expect(recordBytes).toBeGreaterThan(0)
|
||||
// pre-fix the growth was 1 (the blob alone); the manifest record is counted now
|
||||
expect(after.storedBytes - before.storedBytes).toBe(recordBytes + 1)
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"description": "LayerFS workspaces for every agent in magpie: deduplicated checkpoints and branches behind stable filesystem paths, instead of a fresh copy of the tree for every agent, with a page that replays the worktree trajectory",
|
||||
"exports": {
|
||||
".": "./index.mjs"
|
||||
},
|
||||
"files": [
|
||||
"index.mjs",
|
||||
"layerfs.mjs",
|
||||
"page",
|
||||
"README.md"
|
||||
],
|
||||
"keywords": [
|
||||
"magpie",
|
||||
"magpie-tools",
|
||||
"mcp",
|
||||
"opencode",
|
||||
"opencode-plugin",
|
||||
"layerfs",
|
||||
"filesystem",
|
||||
"workspace",
|
||||
"checkpoint",
|
||||
"dedup"
|
||||
],
|
||||
"license": "MIT",
|
||||
"magpie": {
|
||||
"options": {
|
||||
"exec": false
|
||||
},
|
||||
"page": {
|
||||
"file": "page/index.html",
|
||||
"icon": "page/icon.svg",
|
||||
"title": "LayerFS trajectory",
|
||||
"titles": {
|
||||
"ja": "LayerFS の軌跡",
|
||||
"zh": "LayerFS 轨迹",
|
||||
"zh-TW": "LayerFS 軌跡"
|
||||
}
|
||||
}
|
||||
},
|
||||
"main": "./index.mjs",
|
||||
"name": "@magpie-community/tools-layerfs",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/layerfs"
|
||||
},
|
||||
"type": "module",
|
||||
"version": "0.7.1"
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { existsSync, readFileSync, readdirSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
|
||||
const dir = import.meta.dir
|
||||
const page = join(dir, "page")
|
||||
const read = (f) => readFileSync(join(page, f), "utf8")
|
||||
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"))
|
||||
|
||||
// view.js is a classic script, as the page loads it
|
||||
const scope = {}
|
||||
new Function("globalThis", read("view.js"))(scope)
|
||||
const V = scope.LayerfsView
|
||||
|
||||
test("the package declares the page magpie shows", () => {
|
||||
const p = pkg.magpie.page
|
||||
expect(p.title).toBe("LayerFS trajectory")
|
||||
expect(p.titles.zh).toBe("LayerFS 轨迹")
|
||||
expect(p.file).toBe("page/index.html")
|
||||
expect(p.icon).toBe("page/icon.svg")
|
||||
expect(pkg.files).toContain("page")
|
||||
for (const f of ["index.html", "app.js", "view.js", "style.css", "icon.svg"])
|
||||
expect(existsSync(join(page, f))).toBe(true)
|
||||
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"')
|
||||
// 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)/)
|
||||
})
|
||||
|
||||
test("item 13: the page reads only what package.json declares — nothing — and reaches no network", () => {
|
||||
// the ecosystem's convention, as the usage page's test states it: the
|
||||
// set of magpie.read names in the page's scripts equals the declared
|
||||
// permissions, and no script has a way out of the frame. This page
|
||||
// declares no permissions: its data is the bundled sample, because
|
||||
// the bridge's reads are a fixed host list with no plugin-private
|
||||
// entry (see the README's page section).
|
||||
expect(pkg.magpie.permissions).toBeUndefined()
|
||||
const reads = new Set()
|
||||
for (const f of readdirSync(page).filter((f) => f.endsWith(".js"))) {
|
||||
const src = read(f)
|
||||
for (const m of src.matchAll(/magpie\.read\(\s*"([^"]+)"/g)) reads.add(m[1])
|
||||
expect(src).not.toMatch(/\bfetch\(|XMLHttpRequest|WebSocket|sendBeacon|EventSource|importScripts/)
|
||||
}
|
||||
expect([...reads]).toEqual([])
|
||||
})
|
||||
|
||||
test("item 14: every locale the package declares page titles for has a full string table", () => {
|
||||
const keys = Object.keys(V.TEXT.en).sort()
|
||||
expect(Object.keys(pkg.magpie.page.titles).sort()).toEqual(["ja", "zh", "zh-TW"])
|
||||
for (const table of [V.TEXT.ja, V.TEXT["zh-TW"], V.TEXT.zh])
|
||||
expect(Object.keys(table).sort()).toEqual(keys)
|
||||
expect(V.text("ja")).toBe(V.TEXT.ja)
|
||||
expect(V.text("ja-JP")).toBe(V.TEXT.ja)
|
||||
expect(V.text("ja").title).toBe(pkg.magpie.page.titles.ja)
|
||||
expect(V.text("zh-TW")).toBe(V.TEXT["zh-TW"])
|
||||
expect(V.text("zh-HK")).toBe(V.TEXT["zh-TW"]) // Traditional, like the host's title fallback
|
||||
expect(V.text("zh-TW").title).toBe(pkg.magpie.page.titles["zh-TW"])
|
||||
expect(V.text("zh-CN")).toBe(V.TEXT.zh)
|
||||
expect(V.text("zh").title).toBe(pkg.magpie.page.titles.zh)
|
||||
expect(V.text("fr")).toBe(V.TEXT.en)
|
||||
expect(V.detail(project.branches[1].commits[1], "ja").delta).toContain("追加")
|
||||
expect(V.detail(project.branches[1].commits[1], "zh-TW").delta).toContain("新增")
|
||||
})
|
||||
|
||||
test("item 16: the detail card marks its branch with a dot, and the picker is a menu, not a select", () => {
|
||||
const html = read("index.html")
|
||||
expect(html).not.toContain("<select")
|
||||
expect(html).toContain('id="projBtn"')
|
||||
expect(html).toContain('id="projList"')
|
||||
expect(html).toContain('id="dDot"')
|
||||
expect(read("style.css")).not.toMatch(/border-left:\s*3px/)
|
||||
const app = read("app.js")
|
||||
expect(app).not.toContain("borderLeftColor")
|
||||
expect(app).toContain("dDot")
|
||||
expect(app).toContain('style.background = colorOf')
|
||||
})
|
||||
|
||||
const C = (id, parent, time, over = {}) => ({
|
||||
id, parent, message: `commit ${id}`, time,
|
||||
files: 10, logicalBytes: 1000, newBytes: 100,
|
||||
delta: { added: 1, modified: 2, deleted: 0 }, ...over,
|
||||
})
|
||||
const project = {
|
||||
name: "demo",
|
||||
branches: [
|
||||
{ name: "agent-b", commits: [C("b1", "m2", "2026-01-01T00:03:00.000Z"), C("b2", "b1", "2026-01-01T00:05:00.000Z")] },
|
||||
{
|
||||
name: "main", commits: [
|
||||
C("m1", null, "2026-01-01T00:01:00.000Z", { newBytes: 1000 }),
|
||||
C("m2", "m1", "2026-01-01T00:02:00.000Z"),
|
||||
],
|
||||
},
|
||||
{ name: "agent-a", commits: [C("a1", "m1", "2026-01-01T00:04:00.000Z")] },
|
||||
],
|
||||
}
|
||||
|
||||
test("lanes put main first, then branches by first checkpoint", () => {
|
||||
const lane = V.lanes(project)
|
||||
expect(lane.get("main")).toBe(0)
|
||||
expect(lane.get("agent-b")).toBe(1) // first checkpoint 00:03, before agent-a's 00:04
|
||||
expect(lane.get("agent-a")).toBe(2)
|
||||
})
|
||||
|
||||
test("steps are time-ordered and accumulate both curves", () => {
|
||||
const s = V.steps(project)
|
||||
expect(s.map((x) => x.commit.id)).toEqual(["m1", "m2", "b1", "a1", "b2"])
|
||||
expect(s[0].cumLogical).toBe(1000)
|
||||
expect(s[0].cumStored).toBe(1000) // the import stores everything once
|
||||
expect(s[4].cumLogical).toBe(5000) // five checkpoints as copies
|
||||
expect(s[4].cumStored).toBe(1400) // but only the changed bytes were new
|
||||
})
|
||||
|
||||
test("layout links each checkpoint to its parent, across lanes on a fork", () => {
|
||||
const L = V.layout(project, [])
|
||||
expect(L.nodes.length).toBe(5)
|
||||
expect(L.laneCount).toBe(3)
|
||||
const edge = (id) => L.edges.find((e) => e.to.id === id)
|
||||
expect(edge("m2").fork).toBe(false)
|
||||
expect(edge("b1").fork).toBe(true) // agent-b forked from main's m2
|
||||
expect(edge("b1").from.id).toBe("m2")
|
||||
expect(edge("a1").from.id).toBe("m1")
|
||||
expect(L.nodes[4].x).toBeGreaterThan(L.nodes[0].x)
|
||||
})
|
||||
|
||||
test("a publish grafts its branch back onto main and adds a Layer band", () => {
|
||||
const events = [{ kind: "publish", project: "demo", branch: "agent-b", commit: "b2", layer: 1, t: "2026-01-01T00:06:00.000Z" }]
|
||||
expect(V.publishes(project, events)).toEqual([{ layer: 1, commit: "b2", branch: "agent-b", time: "2026-01-01T00:06:00.000Z", overwrote: false }])
|
||||
const L = V.layout(project, events)
|
||||
expect(L.topLayer).toBe(1)
|
||||
expect(L.grafts.length).toBe(1)
|
||||
expect(L.grafts[0].from.branch).toBe("agent-b")
|
||||
expect(L.grafts[0].to.branch).toBe("main")
|
||||
expect(L.grafts[0].to.landing).toBe(true) // main gains a landing leaf, not a copy
|
||||
expect(L.graftedBranches.has("agent-b")).toBe(true)
|
||||
expect(L.graftedBranches.has("agent-a")).toBe(false) // still a bare twig
|
||||
expect(L.bands.map((b) => b.layer)).toEqual([0, 1]) // L0 up to the publish, L1 after
|
||||
expect(L.bands[1].x0).toBe(L.bands[0].x1)
|
||||
})
|
||||
|
||||
test("a branch's spine grows out of its fork point on the parent's lane", () => {
|
||||
const L = V.layout(project, [])
|
||||
const spine = L.spines.get("agent-b")
|
||||
expect(spine[0].id).toBe("m2") // the fork point, drawn on main's lane
|
||||
expect(spine[0].lane).toBe(0)
|
||||
expect(spine.slice(1).map((n) => n.id)).toEqual(["b1", "b2"])
|
||||
// and each commit is counted once, however many branches descend from it
|
||||
const total = L.nodes[L.nodes.length - 1]
|
||||
expect(total.cumLogical).toBe(5000)
|
||||
expect(L.nodes.length).toBe(5)
|
||||
})
|
||||
|
||||
test("branches name their agent by token, in that agent's colour", () => {
|
||||
expect(V.agentOf("claude").name).toBe("Claude Code")
|
||||
expect(V.agentOf("claude").color).toBe("#d97757")
|
||||
expect(V.agentOf("claude-fix").id).toBe("claude")
|
||||
expect(V.agentOf("codex/feat").id).toBe("codex")
|
||||
expect(V.agentOf("pi").mark).toBe("Pi")
|
||||
expect(V.agentOf("pipeline")).toBeNull() // a token match, not a substring
|
||||
expect(V.agentOf("release")).toBeNull()
|
||||
expect(V.agentOf("agent-1")).toBeNull()
|
||||
})
|
||||
|
||||
test("the page's stat tiles and speed seg are in the markup, magpie-style", () => {
|
||||
const html = read("index.html")
|
||||
expect(html).toContain('class="tiles"')
|
||||
for (const id of ["nCommits", "tBranches", "vCopies", "vStored", "tDedup", "vSaved"])
|
||||
expect(html).toContain(`id="${id}"`)
|
||||
expect(html).toContain('id="speed"')
|
||||
expect(html).toContain('data-speed="0.5"')
|
||||
expect(html).toContain('data-speed="4"')
|
||||
expect(html).not.toContain('<select id="speed"') // a seg control, not a select
|
||||
expect(html).toContain('max="1000"') // the scrub is smooth, not per-step
|
||||
})
|
||||
|
||||
test("magpie's easing curve starts and ends true and stays monotonic", () => {
|
||||
const e = V.magpieEase // cubic-bezier(.2,.8,.2,1), magpie's --ease token
|
||||
expect(e(0)).toBe(0)
|
||||
expect(e(1)).toBe(1)
|
||||
expect(e(-1)).toBe(0)
|
||||
expect(e(2)).toBe(1)
|
||||
let prev = 0
|
||||
for (let x = 0.05; x < 1; x += 0.05) {
|
||||
expect(e(x)).toBeGreaterThan(prev)
|
||||
prev = e(x)
|
||||
}
|
||||
expect(e(0.5)).toBeGreaterThan(0.8) // the curve leans out early
|
||||
expect(V.easeOutCubic(0)).toBe(0)
|
||||
expect(V.easeOutCubic(1)).toBe(1)
|
||||
expect(V.easeOutBack(0)).toBeCloseTo(0)
|
||||
expect(V.easeOutBack(1)).toBe(1)
|
||||
expect(V.easeOutBack(0.7)).toBeGreaterThan(1) // the badge pop overshoots
|
||||
})
|
||||
|
||||
test("a frame at playhead t eases each step in and interpolates the counters", () => {
|
||||
const s = V.steps(project) // cumStored 1000,1100,1200,1300,1400; cumLogical 1000..5000
|
||||
const f0 = V.frame(s, 0)
|
||||
expect(f0.progress).toEqual([0, 0, 0, 0, 0])
|
||||
expect(f0.logical).toBe(0)
|
||||
expect(f0.landed).toBe(0)
|
||||
const fEnd = V.frame(s, 5)
|
||||
expect(fEnd.progress).toEqual([1, 1, 1, 1, 1])
|
||||
expect(fEnd.logical).toBe(5000)
|
||||
expect(fEnd.stored).toBe(1400)
|
||||
expect(fEnd.landed).toBe(5)
|
||||
expect(fEnd.branches).toBe(3)
|
||||
const fMid = V.frame(s, 2.5) // third step half-way through its stretch
|
||||
expect(fMid.landed).toBe(2)
|
||||
expect(fMid.progress[2]).toBeGreaterThan(0)
|
||||
expect(fMid.progress[2]).toBeLessThan(1)
|
||||
expect(fMid.logical).toBeGreaterThan(2000)
|
||||
expect(fMid.logical).toBeLessThan(3000)
|
||||
expect(fMid.branches).toBe(1) // only main's two checkpoints have landed
|
||||
// and the counters never run backwards as t grows
|
||||
let last = 0
|
||||
for (let tt = 0; tt <= 5; tt += 0.25) {
|
||||
expect(V.frame(s, tt).logical).toBeGreaterThanOrEqual(last)
|
||||
last = V.frame(s, tt).logical
|
||||
}
|
||||
expect(V.frame(s, 99).landed).toBe(5) // clamped past the end
|
||||
expect(V.frame(s, -1).landed).toBe(0)
|
||||
})
|
||||
|
||||
test("a landing pulse swells and thins, then is spent", () => {
|
||||
const p0 = V.pulse(0)
|
||||
expect(p0.opacity).toBeCloseTo(0.85)
|
||||
const pMid = V.pulse(0.5)
|
||||
expect(pMid.scale).toBeGreaterThan(p0.scale)
|
||||
expect(pMid.opacity).toBeLessThan(p0.opacity)
|
||||
expect(V.pulse(1).opacity).toBe(0)
|
||||
expect(V.pulse(1.5)).toBeNull()
|
||||
expect(V.pulse(-0.1)).toBeNull()
|
||||
})
|
||||
|
||||
test("a monogram's ink reads on its agent's colour", () => {
|
||||
expect(V.markInk("#e7e5e4")).toBe("#101410") // OpenCode's near-white
|
||||
expect(V.markInk("#f59e0b")).toBe("#101410") // Pi's amber
|
||||
expect(V.markInk("#4d6bfe")).toBe("#ffffff") // dsh's deep blue
|
||||
expect(V.markInk("#d97757")).toBe("#ffffff") // Claude's terracotta
|
||||
expect(V.markInk("not-a-color")).toBe("#101410")
|
||||
})
|
||||
|
||||
test("every agent has a drawable icon in the registry", () => {
|
||||
expect(Object.keys(V.ICONS).sort()).toEqual(Object.keys(V.AGENTS).sort())
|
||||
for (const [id, icon] of Object.entries(V.ICONS)) {
|
||||
const box = icon.viewBox.split(/\s+/).map(Number)
|
||||
expect(box.length).toBe(4)
|
||||
expect(box.every((n) => Number.isFinite(n))).toBe(true)
|
||||
expect(icon.paths.length).toBeGreaterThanOrEqual(1)
|
||||
for (const p of icon.paths) {
|
||||
expect(p.d.startsWith("M")).toBe(true)
|
||||
expect(p.d.length).toBeGreaterThanOrEqual(20)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test("a checkpoint badge carries its agent's icon, else a monogram, else the leaf", () => {
|
||||
const g = V.glyphFor("claude-fix")
|
||||
expect(g.type).toBe("icon")
|
||||
expect(g.agent.id).toBe("claude")
|
||||
// the geometry the renderer puts in the node is the registry's own
|
||||
expect(g.icon).toBe(V.ICONS.claude)
|
||||
expect(g.icon.paths[0].d).toContain("M4.709 15.955") // claude's starburst, as magpie ships it
|
||||
expect(V.glyphFor("pi").icon.paths.length).toBe(2) // pi's two block paths
|
||||
expect(V.glyphFor("main").type).toBe("leaf") // no agent on main's bough
|
||||
expect(V.glyphFor("release").type).toBe("leaf")
|
||||
expect(V.glyphFor("release").glyph).toBe(V.LEAF_GLYPH)
|
||||
// an agent whose glyph goes missing falls back to its monogram
|
||||
const saved = V.ICONS.grok
|
||||
delete V.ICONS.grok
|
||||
const fb = V.glyphFor("grok")
|
||||
expect(fb.type).toBe("mark")
|
||||
expect(fb.agent.mark).toBe("Gk")
|
||||
V.ICONS.grok = saved
|
||||
expect(V.glyphFor("grok").type).toBe("icon")
|
||||
})
|
||||
|
||||
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
|
||||
expect(d0.fillOpacity).toBe(0)
|
||||
const dMid = V.iconDraw(0.36, false)
|
||||
expect(dMid.offset).toBeCloseTo(0.5)
|
||||
expect(dMid.fillOpacity).toBe(0) // the fill waits for the outline
|
||||
const dLate = V.iconDraw(0.75, false)
|
||||
expect(dLate.offset).toBe(0) // outline complete before the step ends
|
||||
expect(dLate.fillOpacity).toBeCloseTo(0.5)
|
||||
const d1 = V.iconDraw(1, false)
|
||||
expect(d1.offset).toBe(0)
|
||||
expect(d1.fillOpacity).toBe(1)
|
||||
expect(d1.strokeOpacity).toBeCloseTo(0.45) // a soft outline lingers
|
||||
// neither measure ever runs backwards as progress grows
|
||||
let lastOff = 1, lastFill = 0
|
||||
for (let p = 0; p <= 1.001; p += 0.1) {
|
||||
const d = V.iconDraw(Math.min(1, p), false)
|
||||
expect(d.offset).toBeLessThanOrEqual(lastOff)
|
||||
expect(d.fillOpacity).toBeGreaterThanOrEqual(lastFill)
|
||||
lastOff = d.offset; lastFill = d.fillOpacity
|
||||
}
|
||||
})
|
||||
|
||||
test("reduced motion renders every icon fully drawn at any progress", () => {
|
||||
for (const p of [0, 0.2, 0.63, 1]) {
|
||||
const d = V.iconDraw(p, true)
|
||||
expect(d.offset).toBe(0)
|
||||
expect(d.fillOpacity).toBe(1)
|
||||
}
|
||||
// and the page wires the model in: badges, glyphs, no leaf nodes left
|
||||
const app = read("app.js")
|
||||
expect(app).toContain("glyphFor")
|
||||
expect(app).toContain("iconDraw")
|
||||
expect(app).toContain("badge-disc")
|
||||
expect(app).not.toContain("leaf-core")
|
||||
expect(app).not.toContain("LEAF")
|
||||
expect(read("style.css")).toContain(".glyph-path")
|
||||
})
|
||||
|
||||
test("a checkpoint's detail line carries its delta and byte split", () => {
|
||||
const d = V.detail(project.branches[1].commits[1], "en")
|
||||
expect(d.meta).toContain("10 files")
|
||||
expect(d.meta).toContain("100 B / 1.0 KB")
|
||||
expect(d.delta).toContain("+1 added")
|
||||
expect(d.delta).toContain("~2 modified")
|
||||
expect(V.detail(project.branches[1].commits[1], "zh").delta).toContain("新增")
|
||||
})
|
||||
@@ -0,0 +1,462 @@
|
||||
// The trajectory page, drawn the way LayerFS's own History picture is:
|
||||
// main is the green middle bough, every other branch a bough that splits
|
||||
// off it, a checkpoint a badge on its bough bearing its agent's own
|
||||
// icon (the marks magpie itself ships for them), and a publish a graft
|
||||
// back onto main that lands a Layer badge. The replay is one continuous
|
||||
// timeline, driven by requestAnimationFrame through the pure motion
|
||||
// model in view.js: boughs draw themselves as the playhead passes,
|
||||
// badges land with a pulse while their icons draw themselves, and the
|
||||
// counters count up along the same easing magpie itself uses
|
||||
// (--ease, cubic-bezier(.2,.8,.2,1)).
|
||||
//
|
||||
// The data is the trajectory bundled with the package (trajectory.js,
|
||||
// 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.
|
||||
(async () => {
|
||||
const V = globalThis.LayerfsView;
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const SVG = "http://www.w3.org/2000/svg";
|
||||
const RM = matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
const STEP_MS = 560; // one checkpoint's stretch of timeline at 1×
|
||||
const PULSE_MS = 650;
|
||||
|
||||
let theme = { lang: "en", dark: matchMedia("(prefers-color-scheme: dark)").matches };
|
||||
try { theme = (await magpie.ready) || theme; } catch { /* standalone preview */ }
|
||||
const lang = theme.lang || "en";
|
||||
const t = V.text(lang);
|
||||
document.querySelectorAll("[data-t]").forEach((e) => { e.textContent = t[e.dataset.t]; });
|
||||
|
||||
// branch colours: an agent's branch wears the agent's own brand
|
||||
// colour in both themes; the rest take magpie's chart series, and
|
||||
// main is the leaf green (deeper on light, brighter on dark)
|
||||
const SERIES = {
|
||||
dark: ["#a5b4fc", "#7dd3fc", "#6ee7b7", "#fcd34d", "#f9a8d4", "#c4b5fd", "#94a3b8"],
|
||||
light: ["#4f46e5", "#0ea5e9", "#10b981", "#f59e0b", "#ec4899", "#8b5cf6", "#64748b"],
|
||||
};
|
||||
const series = () => SERIES[theme.dark ? "dark" : "light"];
|
||||
const mainColor = () => (theme.dark ? "#4ade80" : "#16a34a");
|
||||
const colorOf = (branch, lane) =>
|
||||
(V.agentOf(branch) || {}).color ||
|
||||
(lane === 0 ? mainColor() : series()[(lane - 1) % series().length]);
|
||||
|
||||
const data = globalThis.LayerfsTrajectory;
|
||||
const projects = (data && data.projects || []).filter((p) => p.branches.some((b) => b.commits.length));
|
||||
if (!projects.length) {
|
||||
$("stage").hidden = true; $("controls").hidden = true; $("stats").hidden = true;
|
||||
$("empty").hidden = false; $("empty").textContent = t.noData;
|
||||
return;
|
||||
}
|
||||
$("stamp").textContent = data.sample ? t.sample : `${t.recorded} ${String(data.generatedAt || "").replace("T", " ").slice(0, 19)} · ${data.backend || ""}`;
|
||||
|
||||
// the project picker: a magpie-style menu (a button and a listbox),
|
||||
// not a native <select> — magpie's own UI never uses one
|
||||
let currentProject = projects[0].name;
|
||||
const menu = $("projectMenu"), projBtn = $("projBtn"), projList = $("projList");
|
||||
for (const p of projects) {
|
||||
const b = document.createElement("button");
|
||||
b.type = "button";
|
||||
b.setAttribute("role", "option");
|
||||
b.dataset.project = p.name;
|
||||
b.textContent = p.name;
|
||||
projList.append(b);
|
||||
}
|
||||
menu.hidden = projects.length < 2;
|
||||
function paintMenu() {
|
||||
projBtn.textContent = currentProject;
|
||||
projList.querySelectorAll("button").forEach((b) =>
|
||||
b.setAttribute("aria-selected", String(b.dataset.project === currentProject)));
|
||||
}
|
||||
function setMenuOpen(open) {
|
||||
projList.hidden = !open;
|
||||
projBtn.setAttribute("aria-expanded", String(open));
|
||||
}
|
||||
projBtn.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
setMenuOpen(projList.hidden);
|
||||
});
|
||||
projList.addEventListener("click", (e) => {
|
||||
const b = e.target.closest("button[data-project]");
|
||||
if (!b) return;
|
||||
setMenuOpen(false);
|
||||
if (b.dataset.project !== currentProject) show(b.dataset.project);
|
||||
});
|
||||
document.addEventListener("click", () => setMenuOpen(false));
|
||||
|
||||
function el(name, attrs = {}, parent) {
|
||||
const e = document.createElementNS(SVG, name);
|
||||
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
|
||||
if (parent) parent.append(e);
|
||||
return e;
|
||||
}
|
||||
const seg = (a, b) => {
|
||||
const mx = (a.x + b.x) / 2;
|
||||
return `M ${a.x} ${a.y} C ${mx} ${a.y}, ${mx} ${b.y}, ${b.x} ${b.y}`;
|
||||
};
|
||||
|
||||
// the live picture: element registries keyed by replay step, rebuilt
|
||||
// per project; render() then only moves styles and attributes
|
||||
let view = null; // { project, L, stepsList, nodes, segs, grafts, bands, badges }
|
||||
let playhead = 0, playing = false, speed = 1, focus = null, pinned = false;
|
||||
let lastLanded = -1, raf = 0, lastTs = 0;
|
||||
const pulses = new Map(); // step -> pulse start (performance.now)
|
||||
const shown = {}; // last strings written to the stat tiles
|
||||
|
||||
function build(name) {
|
||||
stop(); focus = null; pinned = false; pulses.clear(); lastLanded = -1;
|
||||
const project = projects.find((p) => p.name === name) || projects[0];
|
||||
const stepsList = V.steps(project);
|
||||
const wide = Math.max(320, ($("stage").clientWidth || 720) - 8);
|
||||
// never squish below a readable pitch: the stage scrolls instead
|
||||
const dx = stepsList.length > 1 ? Math.max(46, Math.min(76, (wide - 68) / (stepsList.length - 1))) : 54;
|
||||
const L = V.layout(project, data.events, { dx, laneH: 56, padTop: 46 });
|
||||
view = { project, L, stepsList, nodes: [], segs: [], grafts: [], bands: [], badges: [] };
|
||||
$("histLine").textContent = `${t.history} ${project.name} @ L${L.topLayer}`;
|
||||
$("histMeta").textContent = `${L.nodes.length} commits · ${L.laneCount} ${t.live} · ${L.topLayer + 1} ${t.layers}`;
|
||||
const svg = $("graph");
|
||||
svg.replaceChildren();
|
||||
svg.removeAttribute("data-focus");
|
||||
svg.setAttribute("viewBox", `0 0 ${L.width} ${L.height}`);
|
||||
svg.setAttribute("width", L.width); svg.setAttribute("height", L.height);
|
||||
const all = [...L.nodes, ...L.landings];
|
||||
const mainY = (L.spines.get("main") || [])[0]?.y ?? 46;
|
||||
|
||||
// Layer bands on main: a stratum behind the bough per layer,
|
||||
// fading in as its layer begins
|
||||
L.bands.forEach((band, i) => {
|
||||
const g = el("g", { class: "band" }, svg);
|
||||
el("rect", {
|
||||
x: band.x0 - 16, y: mainY - 18, width: Math.max(30, band.x1 - band.x0 + 32), height: 36, rx: 18,
|
||||
class: "band-fill",
|
||||
}, g);
|
||||
const label = el("text", { y: mainY - 28, class: "band-label" }, g);
|
||||
// the band a head publish just opened has no width yet: anchor its
|
||||
// label at the publish point instead of past the edge
|
||||
if (i === L.bands.length - 1 && band.x1 - band.x0 < 60) {
|
||||
label.setAttribute("x", band.x1 + 14); label.setAttribute("text-anchor", "end");
|
||||
} else {
|
||||
label.setAttribute("x", band.x0 - 6);
|
||||
}
|
||||
label.textContent = `L${band.layer}`;
|
||||
view.bands.push({ g, start: i === 0 ? 0 : L.grafts[i - 1].to.step });
|
||||
});
|
||||
// grafts under everything: a publish joining a branch back to main,
|
||||
// drawn as the playhead reaches it; a Layer badge pops at its head
|
||||
for (const gr of L.grafts) {
|
||||
const path = el("path", {
|
||||
d: seg(gr.from, gr.to), class: "graft", pathLength: 1,
|
||||
"data-branch": gr.from.branch, stroke: colorOf(gr.from.branch, gr.from.lane),
|
||||
}, svg);
|
||||
view.grafts.push({ path, step: gr.to.step, branch: gr.from.branch });
|
||||
const badge = el("g", { class: "badge", transform: `translate(${gr.to.x} ${mainY - 36})` }, svg);
|
||||
const pop = el("g", { class: "badge-pop" }, badge);
|
||||
const label = `L${gr.layer}`;
|
||||
el("rect", { x: -13 - (label.length - 2) * 3.5, y: -8, width: 26 + (label.length - 2) * 7, height: 16, rx: 8, class: "badge-fill" }, pop);
|
||||
const txt = el("text", { y: 3.5, class: "badge-text" }, pop);
|
||||
txt.textContent = label;
|
||||
view.badges.push({ g: badge, pop, step: gr.to.step, branch: gr.from.branch });
|
||||
}
|
||||
// one group per branch: spine segments that draw themselves as
|
||||
// their target checkpoint appears
|
||||
for (const [branch, pts] of L.spines) {
|
||||
const g = el("g", { class: "lane", "data-branch": branch }, svg);
|
||||
const laneIdx = L.laneOf(branch);
|
||||
for (let i = 1; i < pts.length; i++) {
|
||||
const a = pts[i - 1], b = pts[i];
|
||||
const path = el("path", {
|
||||
d: seg(a, b), class: "seg" + (a.lane !== b.lane ? " split-seg" : ""), pathLength: 1,
|
||||
stroke: colorOf(branch, laneIdx), "data-branch": branch,
|
||||
}, g);
|
||||
view.segs.push({ path, step: b.step });
|
||||
}
|
||||
}
|
||||
// checkpoints: a positioned group (attribute transform) around an
|
||||
// animated group (style transform), so the two never fight; the
|
||||
// loose ring is the landing pulse. The badge itself is a soft disc
|
||||
// in the branch's colour, ringed in it, and its face is the icon
|
||||
// of the agent that owns the branch — drawn in the ink that reads
|
||||
// on that colour — or the agent's monogram when it has no glyph,
|
||||
// or LayerFS's leaf when the bough names no agent at all
|
||||
for (const n of all) {
|
||||
const g = el("g", { class: "lane", "data-branch": n.branch }, svg);
|
||||
const pos = el("g", { transform: `translate(${n.x} ${n.y})` }, g);
|
||||
const color = colorOf(n.branch, n.lane);
|
||||
const ring = el("circle", {
|
||||
r: 13, class: "ring", fill: "none",
|
||||
stroke: color, "stroke-width": 2, opacity: 0,
|
||||
}, pos);
|
||||
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 ink = V.markInk(color);
|
||||
const glyphPaths = [];
|
||||
let glyphMark = null;
|
||||
if (face.type === "mark") {
|
||||
glyphMark = el("text", { y: 3.4, class: "glyph-mark", fill: ink }, anim);
|
||||
glyphMark.textContent = face.agent.mark;
|
||||
} else {
|
||||
const glyph = face.type === "icon" ? face.icon : face.glyph;
|
||||
const inner = el("svg", {
|
||||
x: -8, y: -8, width: 16, height: 16, viewBox: glyph.viewBox, class: "glyph",
|
||||
}, anim);
|
||||
for (const p of glyph.paths) {
|
||||
const attrs = {
|
||||
d: p.d, class: "glyph-path", pathLength: 1,
|
||||
fill: ink, stroke: ink, "stroke-width": glyph.sw || 1.3,
|
||||
};
|
||||
if (p.rule) attrs["fill-rule"] = p.rule;
|
||||
glyphPaths.push(el("path", attrs, inner));
|
||||
}
|
||||
}
|
||||
anim.addEventListener("click", () => { pinned = true; pause(); select(n); });
|
||||
view.nodes.push({ anim, ring, step: n.step, node: n, glyphPaths, glyphMark });
|
||||
}
|
||||
// name tags at each branch's first own leaf; main needs none — the
|
||||
// HISTORY line and the Layer bands name it. An agent's branch gets
|
||||
// its monogram chip in the agent's colour, like magpie's own rows.
|
||||
for (const b of project.branches) {
|
||||
if (b.name === "main") continue;
|
||||
const first = L.nodes.find((n) => n.branch === b.name);
|
||||
if (!first) continue;
|
||||
const g = el("g", { class: "lane", "data-branch": b.name }, svg);
|
||||
const tag = el("g", { class: "tag", transform: `translate(${first.x - 4} ${first.y - 30})` }, g);
|
||||
const agent = V.agentOf(b.name);
|
||||
let nameX = 0;
|
||||
if (agent) {
|
||||
el("rect", { x: -2, y: -11, width: 23, height: 15, rx: 3.5, fill: agent.color, class: "chip" }, tag);
|
||||
const mark = el("text", { x: 9.5, y: 1, class: "chip-mark", fill: V.markInk(agent.color) }, tag);
|
||||
mark.textContent = agent.mark;
|
||||
nameX = 27;
|
||||
}
|
||||
const label = el("text", { x: nameX, y: 1, class: "tag-label", fill: colorOf(b.name, first.lane) }, tag);
|
||||
label.textContent = b.name + (!L.graftedBranches.has(b.name) ? " ·" : "");
|
||||
tag.addEventListener("click", () => setFocus(focus === b.name ? null : b.name));
|
||||
}
|
||||
// legend: which agents are in this picture, in their own colours
|
||||
const legend = $("legend");
|
||||
legend.replaceChildren();
|
||||
const seen = new Map();
|
||||
for (const b of project.branches) {
|
||||
const a = V.agentOf(b.name);
|
||||
if (a && !seen.has(a.id)) seen.set(a.id, a);
|
||||
}
|
||||
for (const a of seen.values()) {
|
||||
const item = document.createElement("span");
|
||||
item.className = "legend-item";
|
||||
const icon = V.ICONS[a.id];
|
||||
if (icon) {
|
||||
const mini = el("svg", { width: 14, height: 14, viewBox: icon.viewBox, class: "legend-icon" });
|
||||
for (const p of icon.paths) {
|
||||
const attrs = { d: p.d, fill: a.color };
|
||||
if (p.rule) attrs["fill-rule"] = p.rule;
|
||||
el("path", attrs, mini);
|
||||
}
|
||||
item.append(mini);
|
||||
} else {
|
||||
const dot = document.createElement("i");
|
||||
dot.style.background = a.color;
|
||||
item.append(dot);
|
||||
}
|
||||
item.append(document.createTextNode(a.name));
|
||||
legend.append(item);
|
||||
}
|
||||
legend.hidden = seen.size === 0;
|
||||
for (const k of Object.keys(shown)) delete shown[k];
|
||||
}
|
||||
|
||||
function setFocus(branch) {
|
||||
focus = branch;
|
||||
const svg = $("graph");
|
||||
if (!branch) { svg.removeAttribute("data-focus"); return; }
|
||||
svg.setAttribute("data-focus", branch);
|
||||
document.querySelectorAll("#graph .lane, #graph .graft").forEach((e) => {
|
||||
e.classList.toggle("focus", e.dataset.branch === branch);
|
||||
});
|
||||
}
|
||||
|
||||
function setText(id, value) {
|
||||
if (shown[id] === value) return;
|
||||
shown[id] = value;
|
||||
$(id).textContent = value;
|
||||
}
|
||||
|
||||
// one frame of the replay at the current playhead
|
||||
function render() {
|
||||
if (!view) return;
|
||||
const { L, stepsList } = view;
|
||||
const n = stepsList.length;
|
||||
const f = V.frame(stepsList, playhead);
|
||||
for (const s of view.segs) {
|
||||
const p = f.progress[s.step];
|
||||
s.path.style.strokeDashoffset = String(1 - p);
|
||||
s.path.style.opacity = p > 0 ? "" : "0";
|
||||
}
|
||||
for (const g of view.grafts) {
|
||||
const p = f.progress[g.step];
|
||||
g.path.style.strokeDashoffset = String(1 - p);
|
||||
g.path.style.opacity = p > 0 ? (focus && focus !== g.branch ? "0.13" : "") : "0";
|
||||
}
|
||||
for (const b of view.bands) {
|
||||
b.g.style.opacity = String(V.magpieEase(V.clamp01(playhead - b.start)));
|
||||
}
|
||||
for (const b of view.badges) {
|
||||
const raw = V.clamp01(playhead - b.step);
|
||||
b.g.style.opacity = raw > 0 ? (focus && focus !== b.branch ? "0.25" : "1") : "0";
|
||||
b.pop.style.transform = `scale(${Math.max(0.0001, V.easeOutBack(raw))})`;
|
||||
}
|
||||
for (const nd of view.nodes) {
|
||||
const p = f.progress[nd.step];
|
||||
nd.anim.style.opacity = String(p);
|
||||
nd.anim.style.transform = `scale(${0.35 + 0.65 * p}) rotate(${-14 * (1 - p)}deg)`;
|
||||
nd.anim.classList.toggle("sel", !!nd.node._sel);
|
||||
// as the badge lands, its icon draws itself and then its fill
|
||||
// fades in; under reduced motion the icon is simply there,
|
||||
// fully drawn at any point of the scrub
|
||||
const d = V.iconDraw(p, RM);
|
||||
for (const gp of nd.glyphPaths) {
|
||||
gp.style.strokeDashoffset = String(d.offset);
|
||||
gp.style.fillOpacity = String(d.fillOpacity);
|
||||
gp.style.strokeOpacity = String(d.strokeOpacity);
|
||||
}
|
||||
if (nd.glyphMark) nd.glyphMark.style.opacity = String(d.fillOpacity);
|
||||
}
|
||||
// the counters count up along the same frame
|
||||
const total = stepsList[n - 1];
|
||||
setText("nCommits", `${f.landed} / ${n}`);
|
||||
setText("tBranches", String(f.branches));
|
||||
setText("vCopies", V.bytes(f.logical));
|
||||
setText("vStored", V.bytes(f.stored));
|
||||
setText("tDedup", f.stored > 0 ? `${(f.logical / f.stored).toFixed(2)}×` : "–");
|
||||
setText("vSaved", f.logical > 0 ? `${t.saved} ${V.bytes(f.logical - f.stored)} (${Math.round((1 - f.stored / f.logical) * 100)}%)` : "");
|
||||
$("barCopies").style.width = total && total.cumLogical ? `${Math.max(1.5, (f.logical / total.cumLogical) * 100)}%` : "0%";
|
||||
$("barStored").style.width = total && total.cumLogical ? `${Math.max(1.5, (f.stored / total.cumLogical) * 100)}%` : "0%";
|
||||
if (document.activeElement !== $("scrub")) $("scrub").value = n ? Math.round((playhead / n) * 1000) : 0;
|
||||
// landing bookkeeping: pulses only for steps the playhead crosses
|
||||
// while playing — a scrub sets the state without fanfare
|
||||
if (playing && !RM) {
|
||||
for (let s = Math.max(0, lastLanded); s < f.landed; s++) pulses.set(s, performance.now());
|
||||
}
|
||||
if (f.landed !== lastLanded) {
|
||||
lastLanded = f.landed;
|
||||
if (!pinned) {
|
||||
if (f.landed > 0) select(L.nodes[f.landed - 1]);
|
||||
else clearDetail();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderPulses(now) {
|
||||
for (const [step, start] of pulses) {
|
||||
const s = V.pulse((now - start) / PULSE_MS);
|
||||
for (const nd of view.nodes) {
|
||||
if (nd.step !== step) continue;
|
||||
if (!s) { nd.ring.setAttribute("opacity", 0); continue; }
|
||||
nd.ring.setAttribute("r", (nd.node.landing ? 17 : 13) * s.scale);
|
||||
nd.ring.setAttribute("opacity", s.opacity);
|
||||
}
|
||||
if (!s) pulses.delete(step);
|
||||
}
|
||||
}
|
||||
|
||||
function loop(ts) {
|
||||
raf = 0;
|
||||
if (playing) {
|
||||
if (lastTs) {
|
||||
playhead = Math.min(view.stepsList.length, playhead + ((ts - lastTs) / STEP_MS) * speed);
|
||||
if (playhead >= view.stepsList.length) pause();
|
||||
}
|
||||
lastTs = ts;
|
||||
} else {
|
||||
lastTs = 0;
|
||||
}
|
||||
render();
|
||||
renderPulses(ts);
|
||||
if (playing || pulses.size) raf = requestAnimationFrame(loop);
|
||||
}
|
||||
function ensureLoop() { if (!raf) { lastTs = 0; raf = requestAnimationFrame(loop); } }
|
||||
|
||||
function play() {
|
||||
if (!view || playing) return;
|
||||
pinned = false;
|
||||
if (playhead >= view.stepsList.length) { playhead = 0; lastLanded = -1; pulses.clear(); }
|
||||
if (RM) { playhead = view.stepsList.length; render(); return; }
|
||||
playing = true;
|
||||
$("play").textContent = t.pause;
|
||||
ensureLoop();
|
||||
}
|
||||
function pause() {
|
||||
playing = false;
|
||||
$("play").textContent = t.replay;
|
||||
}
|
||||
function stop() { pause(); if (raf) cancelAnimationFrame(raf); raf = 0; }
|
||||
|
||||
function select(node) {
|
||||
const d = V.detail(node.commit, lang);
|
||||
const graft = view.L.grafts.find((g) => g.to === node);
|
||||
$("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;
|
||||
$("dDelta").textContent = d.delta;
|
||||
$("dTime").textContent = String(node.commit.time || "").replace("T", " ").slice(0, 19);
|
||||
$("dDot").style.background = colorOf(node.branch, node.lane);
|
||||
for (const nd of view.nodes) nd.node._sel = nd.node === node;
|
||||
for (const nd of view.nodes) nd.anim.classList.toggle("sel", nd.node === node);
|
||||
}
|
||||
function clearDetail() {
|
||||
$("dBranch").textContent = ""; $("dMsg").textContent = "";
|
||||
$("dMeta").textContent = ""; $("dDelta").textContent = ""; $("dTime").textContent = "";
|
||||
$("dDot").style.background = "transparent";
|
||||
for (const nd of view.nodes) { nd.node._sel = false; nd.anim.classList.remove("sel"); }
|
||||
}
|
||||
function isTip(node) {
|
||||
return !view.L.nodes.some((n) => n.branch === node.branch && n.step > node.step);
|
||||
}
|
||||
|
||||
function show(name, keep = false) {
|
||||
const at = playhead;
|
||||
currentProject = name;
|
||||
paintMenu();
|
||||
build(name);
|
||||
const n = view.stepsList.length;
|
||||
// reduced motion, or a theme change mid-look: settle on the final
|
||||
// state (clamped to the new picture) instead of replaying
|
||||
playhead = keep ? Math.min(at, n) : RM ? n : 0;
|
||||
render();
|
||||
if (!RM && !keep && n) play();
|
||||
}
|
||||
|
||||
$("play").addEventListener("click", () => (playing ? pause() : play()));
|
||||
$("scrub").addEventListener("input", () => {
|
||||
pause(); pinned = false; pulses.clear();
|
||||
playhead = view ? (Number($("scrub").value) / 1000) * view.stepsList.length : 0;
|
||||
lastLanded = -1; // render re-derives the detail for the new position
|
||||
render();
|
||||
});
|
||||
$("speed").addEventListener("click", (e) => {
|
||||
const b = e.target.closest("button[data-speed]");
|
||||
if (!b) return;
|
||||
speed = Number(b.dataset.speed);
|
||||
for (const x of $("speed").querySelectorAll("button")) {
|
||||
if (x === b) x.setAttribute("aria-selected", "true"); else x.removeAttribute("aria-selected");
|
||||
}
|
||||
});
|
||||
if (window.magpie && typeof magpie.onTheme === "function") {
|
||||
magpie.onTheme((th) => {
|
||||
const dark = !!th.dark;
|
||||
if (dark === theme.dark) return;
|
||||
theme = { ...theme, dark };
|
||||
show(currentProject, true);
|
||||
});
|
||||
}
|
||||
|
||||
// the store.stats line, in LayerFS's own accounting words
|
||||
const totals = data.totals || {};
|
||||
$("statsLine").textContent =
|
||||
`${t.stats} · ${t.dedupe} ${totals.dedupRatio ?? "–"}× · ${t.stored} ${V.bytes(totals.storedBytes)} / ${V.bytes(totals.logicalBytes)}`;
|
||||
|
||||
show(projects[0].name);
|
||||
})();
|
||||
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<path d="M14 10v30" stroke="#7dd3fc" stroke-width="4" stroke-linecap="round"/>
|
||||
<path d="M14 24c14 0 10 16 24 16h12" fill="none" stroke="#a5b4fc" stroke-width="4" stroke-linecap="round"/>
|
||||
<circle cx="14" cy="10" r="6" fill="#7dd3fc"/>
|
||||
<circle cx="14" cy="46" r="6" fill="#7dd3fc"/>
|
||||
<circle cx="50" cy="40" r="6" fill="#a5b4fc"/>
|
||||
<circle cx="38" cy="16" r="5" fill="#6ee7b7"/>
|
||||
<path d="M14 16c8 0 8-2 18-2" fill="none" stroke="#6ee7b7" stroke-width="3.4" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 560 B |
@@ -0,0 +1,61 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>LayerFS trajectory</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<script src="_magpie/bridge.js"></script>
|
||||
<script src="trajectory.js"></script>
|
||||
<script src="view.js"></script>
|
||||
<script src="app.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<div class="hist">
|
||||
<h1 id="histLine">HISTORY</h1>
|
||||
<p class="hist-meta" id="histMeta"></p>
|
||||
</div>
|
||||
<div class="menu" id="projectMenu" hidden>
|
||||
<button type="button" id="projBtn" aria-haspopup="listbox" aria-expanded="false"></button>
|
||||
<div class="menu-list" id="projList" role="listbox" aria-label="project" hidden></div>
|
||||
</div>
|
||||
<p class="stamp" id="stamp"></p>
|
||||
</header>
|
||||
|
||||
<section class="stats" id="stats">
|
||||
<div class="tiles">
|
||||
<div class="tile"><span class="k" data-t="checkpointsK">Checkpoints</span><span class="v" id="nCommits">0 / 0</span></div>
|
||||
<div class="tile"><span class="k" data-t="branchesK">Branches</span><span class="v" id="tBranches">0</span></div>
|
||||
<div class="tile"><span class="k" data-t="asCopies">as copies</span><span class="v" id="vCopies">0 B</span></div>
|
||||
<div class="tile"><span class="k" data-t="stored">stored</span><span class="v" id="vStored">0 B</span></div>
|
||||
<div class="tile"><span class="k" data-t="dedupe">dedupe</span><span class="v" id="tDedup">–</span><span class="s saved" id="vSaved"></span></div>
|
||||
</div>
|
||||
<div class="bar-row"><span class="bar-label" data-t="asCopies">as copies</span><div class="bar"><i id="barCopies" class="copies"></i></div></div>
|
||||
<div class="bar-row"><span class="bar-label" data-t="stored">stored</span><div class="bar"><i id="barStored" class="stored"></i></div></div>
|
||||
<p class="stats-line" id="statsLine"></p>
|
||||
</section>
|
||||
|
||||
<div class="stage" id="stage"><svg id="graph" role="img" aria-label="worktree trajectory"></svg></div>
|
||||
<div class="legend" id="legend" hidden></div>
|
||||
|
||||
<section class="controls" id="controls">
|
||||
<button type="button" id="play" class="primary">Replay</button>
|
||||
<input type="range" id="scrub" min="0" max="1000" value="0" step="1" aria-label="replay position">
|
||||
<div class="seg" id="speed" role="group" aria-label="speed">
|
||||
<button type="button" data-speed="0.5">0.5×</button>
|
||||
<button type="button" data-speed="1" aria-selected="true">1×</button>
|
||||
<button type="button" data-speed="2">2×</button>
|
||||
<button type="button" data-speed="4">4×</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="detail" id="detail">
|
||||
<div class="d-head"><span class="d-branch"><i id="dDot" class="d-dot"></i><span id="dBranch"></span></span><span class="d-time" id="dTime"></span></div>
|
||||
<p class="d-msg" id="dMsg"></p>
|
||||
<p class="d-meta"><span id="dMeta"></span> <span id="dDelta" class="delta"></span></p>
|
||||
</section>
|
||||
|
||||
<p class="empty" id="empty" hidden></p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,178 @@
|
||||
/* Magpie's own design language, the way every page in its window is
|
||||
drawn (see the bridge's base sheet and the usage page): the host's
|
||||
theme tokens, its UI face at 13px, hairline rules, cards with a 1px
|
||||
edge and a 10px radius, an indigo accent, and its motion curve
|
||||
--ease = cubic-bezier(.2,.8,.2,1). The fallbacks are magpie's own
|
||||
light theme; its dark theme sits behind the media query for when
|
||||
the page is previewed without the host painting the tokens in.
|
||||
Inside the graphic, LayerFS's picture stays: a leaf-green main
|
||||
bough, each agent's branch in that agent's own colour. */
|
||||
:root {
|
||||
--bg: var(--magpie-bg, #f4f4f6);
|
||||
--card: var(--magpie-card, #ffffff);
|
||||
--fg: var(--magpie-fg, #1c1c21);
|
||||
--fg-2: var(--magpie-fg-2, #4b4b53);
|
||||
--muted: var(--magpie-muted, #85858d);
|
||||
--faint: var(--magpie-faint, #b9b9c2);
|
||||
--line: var(--magpie-line, #e3e3e8);
|
||||
--accent: var(--magpie-accent, #4f46e5);
|
||||
--accent-soft: var(--magpie-accent-soft, #eeedfd);
|
||||
--accent-fg: var(--magpie-accent-fg, #ffffff);
|
||||
--green: var(--magpie-green, #189a58);
|
||||
--red: var(--magpie-red, #d64545);
|
||||
--amber: var(--magpie-amber, #b45309);
|
||||
--font: var(--magpie-font, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui, sans-serif);
|
||||
--code: var(--magpie-code, ui-monospace, "SF Mono", Menlo, Consolas, monospace);
|
||||
--ease: cubic-bezier(.2, .8, .2, 1);
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: var(--magpie-bg, #1a1a1e);
|
||||
--card: var(--magpie-card, #232327);
|
||||
--fg: var(--magpie-fg, #ededf1);
|
||||
--fg-2: var(--magpie-fg-2, #b9b9c1);
|
||||
--muted: var(--magpie-muted, #8b8b94);
|
||||
--faint: var(--magpie-faint, #56565f);
|
||||
--line: var(--magpie-line, #333339);
|
||||
--accent: var(--magpie-accent, #a5b4fc);
|
||||
--accent-soft: var(--magpie-accent-soft, #2b2c47);
|
||||
--accent-fg: var(--magpie-accent-fg, #14142a);
|
||||
--green: var(--magpie-green, #6fd99b);
|
||||
--red: var(--magpie-red, #f28b82);
|
||||
--amber: var(--magpie-amber, #f2b544);
|
||||
}
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; background: var(--bg); color: var(--fg); }
|
||||
body { padding: 20px 24px 32px; font: 13px/1.45 var(--font); -webkit-font-smoothing: antialiased; }
|
||||
|
||||
header { display: flex; align-items: baseline; gap: 16px; flex-wrap: wrap; border-bottom: 1px solid var(--line); padding-bottom: 12px; }
|
||||
.hist h1 { font-size: 15px; font-weight: 600; letter-spacing: -.01em; margin: 0; }
|
||||
.hist-meta {
|
||||
font-size: 11px; font-weight: 500; letter-spacing: .08em; text-transform: uppercase;
|
||||
color: var(--muted); margin: 3px 0 0;
|
||||
}
|
||||
.stamp { color: var(--muted); font-size: 12px; margin: 0 0 0 auto; }
|
||||
/* the project picker, magpie-style: a button that opens a menu of
|
||||
options — its own UI uses no native <select> */
|
||||
.menu { position: relative; }
|
||||
.menu > button {
|
||||
background: var(--card); color: inherit; border: 1px solid var(--line);
|
||||
border-radius: 6px; padding: 4px 10px; font: inherit; cursor: pointer;
|
||||
}
|
||||
.menu-list {
|
||||
position: absolute; top: calc(100% + 4px); left: 0; z-index: 5; min-width: 160px;
|
||||
background: var(--card); border: 1px solid var(--line); border-radius: 10px;
|
||||
padding: 4px; box-shadow: 0 8px 24px rgba(0, 0, 0, .14);
|
||||
}
|
||||
.menu-list button {
|
||||
display: block; width: 100%; text-align: left; background: none; border: 0;
|
||||
border-radius: 6px; padding: 5px 9px; font: inherit; color: inherit; cursor: pointer;
|
||||
}
|
||||
.menu-list button:hover { background: var(--bg); }
|
||||
.menu-list button[aria-selected="true"] { background: var(--accent-soft); }
|
||||
|
||||
/* the counters, as tiles in magpie's usage-page idiom */
|
||||
.stats { margin: 14px 0 2px; }
|
||||
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
|
||||
.tile {
|
||||
background: var(--card); border: 1px solid var(--line); border-radius: 10px;
|
||||
padding: 10px 12px; min-width: 0; display: flex; flex-direction: column; gap: 1px;
|
||||
}
|
||||
.tile .k { color: var(--muted); font-size: 12px; text-transform: capitalize; }
|
||||
.tile .v { font-size: 20px; font-weight: 600; font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tile .s { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||
.tile .s.saved { color: var(--green); font-weight: 600; }
|
||||
.bar-row { display: grid; grid-template-columns: 92px 1fr; gap: 10px; align-items: center; margin: 10px 0 -4px; }
|
||||
.bar-row + .bar-row { margin-top: 6px; }
|
||||
.bar-label {
|
||||
color: var(--muted); font-size: 11px; font-family: var(--code);
|
||||
letter-spacing: .06em; text-transform: uppercase;
|
||||
}
|
||||
.bar { height: 6px; border-radius: 3px; background: color-mix(in srgb, var(--fg) 8%, transparent); overflow: hidden; }
|
||||
.bar i { display: block; height: 100%; width: 0; border-radius: 3px; }
|
||||
.bar i.copies { background: var(--amber); }
|
||||
.bar i.stored { background: var(--green); }
|
||||
.stats-line {
|
||||
font-family: var(--code); font-size: 11.5px; letter-spacing: .05em;
|
||||
color: var(--muted); margin: 12px 0 0;
|
||||
}
|
||||
|
||||
.stage { overflow-x: auto; padding: 12px 0 2px; }
|
||||
#graph .band-fill { fill: var(--green); opacity: .08; }
|
||||
#graph .band-label {
|
||||
font-family: var(--code); font-size: 10.5px; letter-spacing: .12em; fill: var(--muted);
|
||||
}
|
||||
#graph .seg { fill: none; stroke-width: 5; stroke-linecap: round; stroke-dasharray: 1; }
|
||||
#graph .lane[data-branch="main"] .seg { stroke-width: 9; }
|
||||
#graph .seg.split-seg { stroke-width: 3.2; }
|
||||
#graph .graft { fill: none; stroke-width: 3.4; stroke-linecap: round; stroke-dasharray: 1; }
|
||||
#graph .node { transform-box: fill-box; transform-origin: center; cursor: pointer; }
|
||||
#graph .badge-disc { opacity: .22; }
|
||||
#graph .badge-ring { stroke-width: 1.8; opacity: .9; }
|
||||
#graph .node.landing .badge-ring { stroke: var(--fg); stroke-width: 2.2; }
|
||||
#graph .node.sel .badge-ring { stroke: var(--fg); stroke-width: 2.6; }
|
||||
/* the badge's face: the agent's icon, its outline drawn by dashoffset
|
||||
(pathLength is 1, so a dash of 1 is the whole outline) and its fill
|
||||
faded in by the renderer; a monogram sits in the same badge when
|
||||
the agent has no glyph */
|
||||
#graph .glyph { overflow: visible; }
|
||||
#graph .glyph-path { stroke-dasharray: 1; stroke-linejoin: round; stroke-linecap: round; }
|
||||
#graph .glyph-mark {
|
||||
font-family: var(--code); font-size: 9px; font-weight: 700; text-anchor: middle;
|
||||
}
|
||||
.legend-icon { flex: none; display: inline-block; }
|
||||
#graph .ring { pointer-events: none; }
|
||||
#graph .badge-pop { transform-box: fill-box; transform-origin: center; }
|
||||
#graph .badge-fill { fill: var(--accent); }
|
||||
#graph .badge-text {
|
||||
font-family: var(--code); font-size: 9.5px; font-weight: 700;
|
||||
fill: var(--accent-fg); text-anchor: middle;
|
||||
}
|
||||
#graph .tag { cursor: pointer; }
|
||||
#graph .tag-label { font-family: var(--code); font-size: 12px; letter-spacing: .04em; font-weight: 600; }
|
||||
#graph .chip-mark { font-family: var(--code); font-size: 9px; font-weight: 700; text-anchor: middle; }
|
||||
/* focus: click a name tag and the rest of the thicket dims (grafts and
|
||||
badges are dimmed by the renderer, which owns their opacity) */
|
||||
#graph[data-focus] .lane { opacity: .13; }
|
||||
#graph[data-focus] .lane.focus { opacity: 1; }
|
||||
.legend { display: flex; gap: 16px; flex-wrap: wrap; padding: 2px 2px 0; }
|
||||
.legend-item {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
font-size: 12px; color: var(--muted);
|
||||
}
|
||||
.legend-item i { width: 9px; height: 9px; border-radius: 2.5px; display: inline-block; }
|
||||
|
||||
.controls { display: flex; gap: 12px; align-items: center; margin-top: 12px; }
|
||||
.controls button { font: inherit; cursor: pointer; }
|
||||
#play {
|
||||
background: var(--accent); color: var(--accent-fg); border: 1px solid transparent;
|
||||
border-radius: 6px; padding: 4px 16px; font-weight: 600;
|
||||
transition: filter .12s var(--ease);
|
||||
}
|
||||
#play:hover { filter: brightness(1.08); }
|
||||
.controls input[type="range"] { flex: 1; accent-color: var(--accent); }
|
||||
.seg { display: inline-flex; padding: 2px; border-radius: 8px; background: var(--card); border: 1px solid var(--line); }
|
||||
.seg button {
|
||||
color: var(--muted); background: none; border: 0; border-radius: 6px;
|
||||
padding: 3px 10px; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.seg button[aria-selected="true"] { color: var(--fg); background: var(--bg); box-shadow: 0 1px 2px rgba(0, 0, 0, .18); }
|
||||
|
||||
.detail {
|
||||
margin-top: 16px; background: var(--card); border: 1px solid var(--line);
|
||||
border-radius: 10px; padding: 12px 14px; min-height: 74px;
|
||||
}
|
||||
.d-head { display: flex; justify-content: space-between; gap: 12px; color: var(--muted); font-size: 12px; font-family: var(--code); }
|
||||
.d-branch { display: inline-flex; align-items: center; gap: 7px; min-width: 0; }
|
||||
/* the branch colour rides on a dot, the way magpie's own rows mark a
|
||||
series — not a coloured edge on the card */
|
||||
.d-dot { width: 9px; height: 9px; border-radius: 50%; flex: none; background: transparent; }
|
||||
.d-msg { margin: 6px 0 2px; font-weight: 600; font-size: 13.5px; }
|
||||
.d-meta { margin: 0; color: var(--muted); font-size: 12.5px; font-variant-numeric: tabular-nums; }
|
||||
.d-meta .delta { color: var(--green); font-weight: 600; }
|
||||
.empty { color: var(--muted); margin-top: 22px; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
#play { transition: none; }
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,391 @@
|
||||
// The trajectory page's working parts, with no DOM in them, so a test can
|
||||
// check them. The model follows LayerFS's own History picture: main is
|
||||
// the middle bough, each branch a bough of its own, a commit a leaf on
|
||||
// its bough, a fork a split, a publish a graft back onto main that adds
|
||||
// a Layer band. A classic script: it sets globalThis.LayerfsView.
|
||||
(() => {
|
||||
const TEXT = {
|
||||
en: {
|
||||
title: "LayerFS trajectory", replay: "Replay", pause: "Pause",
|
||||
commits: "checkpoints", stored: "stored", asCopies: "as copies",
|
||||
saved: "saved by dedup", added: "added", modified: "modified", deleted: "deleted",
|
||||
files: "files", newBytes: "new bytes", noData: "No trajectory recorded yet. When an agent provisions, forks or checkpoints, the path appears here.",
|
||||
sample: "Sample trajectory from the plugin's benchmark run.",
|
||||
recorded: "Recorded", branch: "branch", workspace: "workspace",
|
||||
live: "live", layers: "layers", history: "HISTORY", stats: "store.stats · read-only",
|
||||
dedupe: "dedupe", graft: "published", twig: "bare twig",
|
||||
checkpointsK: "Checkpoints", branchesK: "Branches",
|
||||
},
|
||||
zh: {
|
||||
title: "LayerFS 轨迹", replay: "回放", pause: "暂停",
|
||||
commits: "个检查点", stored: "实际存储", asCopies: "若逐份复制",
|
||||
saved: "去重省下", added: "新增", modified: "修改", deleted: "删除",
|
||||
files: "个文件", newBytes: "新增字节", noData: "还没有记录到轨迹。agent 一旦 provision、fork 或 checkpoint,它的路径就会出现在这里。",
|
||||
sample: "示例轨迹,来自插件的基准运行。",
|
||||
recorded: "记录于", branch: "分支", workspace: "工作区",
|
||||
live: "条存活分支", layers: "层", history: "HISTORY", stats: "store.stats · 只读",
|
||||
dedupe: "去重", graft: "已发布", twig: "未发布的枝条",
|
||||
checkpointsK: "检查点", branchesK: "分支",
|
||||
},
|
||||
"zh-TW": {
|
||||
title: "LayerFS 軌跡", replay: "重播", pause: "暫停",
|
||||
commits: "個檢查點", stored: "實際儲存", asCopies: "若逐份複製",
|
||||
saved: "去重省下", added: "新增", modified: "修改", deleted: "刪除",
|
||||
files: "個檔案", newBytes: "新增位元組", noData: "還沒有記錄到軌跡。agent 一旦 provision、fork 或 checkpoint,它的路徑就會出現在這裡。",
|
||||
sample: "範例軌跡,來自外掛的基準執行。",
|
||||
recorded: "記錄於", branch: "分支", workspace: "工作區",
|
||||
live: "條存活分支", layers: "層", history: "HISTORY", stats: "store.stats · 唯讀",
|
||||
dedupe: "去重", graft: "已發布", twig: "未發布的枝條",
|
||||
checkpointsK: "檢查點", branchesK: "分支",
|
||||
},
|
||||
ja: {
|
||||
title: "LayerFS の軌跡", replay: "再生", pause: "一時停止",
|
||||
commits: "件のチェックポイント", stored: "実ストレージ", asCopies: "コピー換算",
|
||||
saved: "重複排除で節約", added: "追加", modified: "変更", deleted: "削除",
|
||||
files: "ファイル", newBytes: "新規バイト", noData: "まだ軌跡が記録されていません。エージェントが provision、fork、checkpoint を行うと、その経路がここに表示されます。",
|
||||
sample: "サンプル軌跡(プラグインのベンチマーク実行より)。",
|
||||
recorded: "記録", branch: "ブランチ", workspace: "ワークスペース",
|
||||
live: "本の生存ブランチ", layers: "レイヤー", history: "HISTORY", stats: "store.stats · 読み取り専用",
|
||||
dedupe: "重複排除", graft: "公開済み", twig: "未公開の枝",
|
||||
checkpointsK: "チェックポイント", branchesK: "ブランチ",
|
||||
},
|
||||
};
|
||||
|
||||
// The locale the host hands over picks the table, the way the host
|
||||
// resolves page titles: zh-TW / zh-HK / zh-Hant get Traditional,
|
||||
// other zh gets Simplified, ja gets Japanese, the rest English.
|
||||
function text(lang) {
|
||||
const l = String(lang || "").toLowerCase();
|
||||
if (l.startsWith("ja")) return TEXT.ja;
|
||||
if (/^(zh-tw|zh-hk|zh-hant)/.test(l)) return TEXT["zh-TW"];
|
||||
if (l.startsWith("zh")) return TEXT.zh;
|
||||
return TEXT.en;
|
||||
}
|
||||
|
||||
// The agents magpie drives, in the colours their own products wear, so
|
||||
// a branch an agent worked on carries that agent's identity in the
|
||||
// picture: its colour on the bough and leaves, its monogram on the
|
||||
// name tag. Matching is by token: "claude", "claude-fix" and
|
||||
// "codex/feat" name their agent; anything else keeps the palette.
|
||||
const AGENTS = {
|
||||
claude: { name: "Claude Code", color: "#d97757", mark: "Cl" },
|
||||
codex: { name: "Codex", color: "#10a37f", mark: "Cx" },
|
||||
opencode: { name: "OpenCode", color: "#e7e5e4", mark: "Oc" },
|
||||
cursor: { name: "Cursor", color: "#94a3b8", mark: "Cu" },
|
||||
gemini: { name: "Gemini", color: "#5b8def", mark: "Gm" },
|
||||
pi: { name: "Pi", color: "#f59e0b", mark: "Pi" },
|
||||
dsh: { name: "DeepSeek Harness", color: "#4d6bfe", mark: "Ds" },
|
||||
qoder: { name: "Qoder", color: "#6366f1", mark: "Qd" },
|
||||
cline: { name: "Cline", color: "#38bdf8", mark: "Cn" },
|
||||
grok: { name: "Grok", color: "#d4d4d8", mark: "Gk" },
|
||||
kimi: { name: "Kimi", color: "#a78bfa", mark: "Km" },
|
||||
droid: { name: "Droid", color: "#34d399", mark: "Dr" },
|
||||
hermes: { name: "Hermes", color: "#f472b6", mark: "Hm" },
|
||||
goose: { name: "Goose", color: "#fbbf24", mark: "Gs" },
|
||||
zcode: { name: "ZCode", color: "#22d3ee", mark: "Zc" },
|
||||
};
|
||||
|
||||
function agentOf(branch) {
|
||||
const tokens = String(branch || "").toLowerCase().split(/[-_/ ]+/).filter(Boolean);
|
||||
for (const tok of tokens) if (AGENTS[tok]) return { id: tok, ...AGENTS[tok] };
|
||||
return null;
|
||||
}
|
||||
|
||||
function bytes(n) {
|
||||
n = Number(n) || 0;
|
||||
if (n >= 1e9) return (n / 1e9).toFixed(2) + " GB";
|
||||
if (n >= 1e6) return (n / 1e6).toFixed(1) + " MB";
|
||||
if (n >= 1e3) return (n / 1e3).toFixed(1) + " KB";
|
||||
return n + " B";
|
||||
}
|
||||
|
||||
// Lane 0 is main, the middle bough; other branches follow in the order
|
||||
// their first checkpoint appears.
|
||||
function lanes(project) {
|
||||
const firstAt = new Map();
|
||||
for (const b of project.branches) {
|
||||
if (b.commits.length) firstAt.set(b.name, b.commits[0].time);
|
||||
}
|
||||
const names = project.branches.map((b) => b.name).sort((a, b) => {
|
||||
if (a === "main") return -1;
|
||||
if (b === "main") return 1;
|
||||
return String(firstAt.get(a) ?? "").localeCompare(String(firstAt.get(b) ?? "")) || a.localeCompare(b);
|
||||
});
|
||||
return new Map(names.map((name, i) => [name, i]));
|
||||
}
|
||||
|
||||
// Every commit of the project in the order the replay reveals them:
|
||||
// by time, ties broken by lane then id so a fork's first checkpoint
|
||||
// never precedes the checkpoint it forked from. A branch's list holds
|
||||
// only its own checkpoints (ancestors belong to their own bough), so
|
||||
// each commit appears exactly once and the curves count it once.
|
||||
function steps(project) {
|
||||
const lane = lanes(project);
|
||||
const all = [];
|
||||
for (const b of project.branches) {
|
||||
for (const c of b.commits) all.push({ branch: b.name, lane: lane.get(b.name), commit: c });
|
||||
}
|
||||
all.sort((x, y) =>
|
||||
String(x.commit.time).localeCompare(String(y.commit.time)) ||
|
||||
x.lane - y.lane || String(x.commit.id).localeCompare(String(y.commit.id)));
|
||||
let cumLogical = 0, cumStored = 0;
|
||||
for (const s of all) {
|
||||
cumLogical += s.commit.logicalBytes || 0;
|
||||
cumStored += s.commit.newBytes || 0;
|
||||
s.cumLogical = cumLogical;
|
||||
s.cumStored = cumStored;
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
// The publishes that landed on this project, oldest first, each one a
|
||||
// Layer on main. Falls back to numbering by order when an older
|
||||
// recording has no layer field.
|
||||
function publishes(project, events) {
|
||||
const pubs = (events || [])
|
||||
.filter((e) => e.kind === "publish" && e.project === project.name)
|
||||
.sort((a, b) => String(a.t).localeCompare(String(b.t)));
|
||||
return pubs.map((e, i) => ({
|
||||
layer: Number.isInteger(e.layer) ? e.layer : i + 1,
|
||||
commit: e.commit, branch: e.branch, time: e.t, overwrote: !!e.overwrote,
|
||||
}));
|
||||
}
|
||||
|
||||
// The picture, worked out: one node per checkpoint on the lane of the
|
||||
// branch that made it; a publish adds a landing node on main's lane at
|
||||
// the same step and a graft from the branch's leaf to it; each branch's
|
||||
// spine runs from its fork point (a node on another lane) through its
|
||||
// own leaves; main's Layer bands run between consecutive landings.
|
||||
function layout(project, events, { dx = 54, laneH = 64, padX = 34, padTop = 42 } = {}) {
|
||||
const lane = lanes(project);
|
||||
const ordered = steps(project);
|
||||
const nodes = ordered.map((s, i) => ({
|
||||
id: s.commit.id, branch: s.branch, lane: s.lane, step: i,
|
||||
x: padX + i * dx, y: padTop + s.lane * laneH, commit: s.commit,
|
||||
cumLogical: s.cumLogical, cumStored: s.cumStored, landing: false,
|
||||
}));
|
||||
const byId = new Map(nodes.map((n) => [n.id, n]));
|
||||
const pubs = publishes(project, events);
|
||||
const mainLane = lane.get("main") ?? 0;
|
||||
const landings = [];
|
||||
const grafts = [];
|
||||
for (const pub of pubs) {
|
||||
const from = byId.get(pub.commit);
|
||||
if (!from || from.branch === "main") continue;
|
||||
const to = {
|
||||
id: pub.commit, branch: "main", lane: mainLane, step: from.step,
|
||||
x: from.x, y: padTop + mainLane * laneH, commit: from.commit,
|
||||
cumLogical: from.cumLogical, cumStored: from.cumStored, landing: true,
|
||||
};
|
||||
landings.push(to);
|
||||
grafts.push({ from, to, layer: pub.layer });
|
||||
}
|
||||
// parent edges: within a lane along the bough, or a fork split when
|
||||
// the parent leaf sits on another lane
|
||||
const edges = [];
|
||||
for (const n of nodes) {
|
||||
const p = n.commit.parent && byId.get(n.commit.parent);
|
||||
if (p && p !== n) edges.push({ from: p, to: n, fork: p.lane !== n.lane });
|
||||
}
|
||||
// spines: per branch, the fork point first (when it lives on another
|
||||
// lane), then the branch's own leaves in order. Main's spine also
|
||||
// runs through its landing leaves.
|
||||
const spines = new Map();
|
||||
for (const b of project.branches) {
|
||||
const own = nodes.filter((n) => n.branch === b.name);
|
||||
const pts = [];
|
||||
if (b.name !== "main" && own.length) {
|
||||
const parent = byId.get(own[0].commit.parent);
|
||||
if (parent && parent.lane !== own[0].lane) pts.push({ ...parent, spineStep: own[0].step });
|
||||
}
|
||||
pts.push(...own);
|
||||
if (b.name === "main") {
|
||||
const merged = [...pts, ...landings].sort((a, z) => a.x - z.x || a.step - z.step);
|
||||
spines.set(b.name, merged);
|
||||
} else {
|
||||
spines.set(b.name, pts);
|
||||
}
|
||||
}
|
||||
// A branch whose head was published is grafted; any other branch is
|
||||
// still a bare twig at its tip.
|
||||
const grafted = new Set(grafts.map((g) => g.from.branch));
|
||||
const bands = [];
|
||||
const mainExtent = spines.get("main") || [];
|
||||
if (mainExtent.length) {
|
||||
let start = mainExtent[0].x, layer = 0;
|
||||
for (const g of grafts) {
|
||||
bands.push({ layer, x0: start, x1: g.to.x });
|
||||
start = g.to.x; layer = g.layer;
|
||||
}
|
||||
bands.push({ layer, x0: start, x1: mainExtent[mainExtent.length - 1].x });
|
||||
}
|
||||
const laneCount = Math.max(1, lane.size);
|
||||
return {
|
||||
nodes, landings, edges, grafts, spines, bands,
|
||||
topLayer: pubs.length ? pubs[pubs.length - 1].layer : 0,
|
||||
graftedBranches: grafted,
|
||||
width: padX * 2 + Math.max(0, nodes.length - 1) * dx,
|
||||
height: padTop * 2 + (laneCount - 1) * laneH + 18,
|
||||
laneOf: (name) => lane.get(name), laneCount,
|
||||
};
|
||||
}
|
||||
|
||||
// --- the replay's motion model, pure so a test can check it --------
|
||||
// Magpie's own easing (its --ease token): cubic-bezier(.2,.8,.2,1).
|
||||
// Solved the way browsers solve it: Newton steps on x, bisection
|
||||
// when they stall.
|
||||
function cubicBezier(x1, y1, x2, y2) {
|
||||
const at = (a, b, u) => {
|
||||
const v = 1 - u;
|
||||
return 3 * v * v * u * a + 3 * v * u * u * b + u * u * u;
|
||||
};
|
||||
const dx = (u) => {
|
||||
const v = 1 - u;
|
||||
return 3 * v * v * x1 + 6 * v * u * (x2 - x1) + 3 * u * u * (1 - x2);
|
||||
};
|
||||
return (x) => {
|
||||
if (x <= 0) return 0;
|
||||
if (x >= 1) return 1;
|
||||
let u = x;
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const err = at(x1, x2, u) - x;
|
||||
if (Math.abs(err) < 1e-6) return at(y1, y2, u);
|
||||
const d = dx(u);
|
||||
if (Math.abs(d) < 1e-6) break;
|
||||
u -= err / d;
|
||||
}
|
||||
let lo = 0, hi = 1;
|
||||
u = x;
|
||||
while (hi - lo > 1e-6) {
|
||||
if (at(x1, x2, u) < x) lo = u; else hi = u;
|
||||
u = (lo + hi) / 2;
|
||||
}
|
||||
return at(y1, y2, u);
|
||||
};
|
||||
}
|
||||
const magpieEase = cubicBezier(0.2, 0.8, 0.2, 1);
|
||||
const easeOutCubic = (t) => 1 - Math.pow(1 - Math.min(1, Math.max(0, t)), 3);
|
||||
// a soft overshoot for the Layer badges popping in
|
||||
const easeOutBack = (t) => {
|
||||
t = Math.min(1, Math.max(0, t));
|
||||
const c = 1.70158;
|
||||
return 1 + (c + 1) * Math.pow(t - 1, 3) + c * Math.pow(t - 1, 2);
|
||||
};
|
||||
const clamp01 = (v) => Math.min(1, Math.max(0, v));
|
||||
|
||||
// The replay at playhead t (0..steps.length, fractional): each step
|
||||
// appears over the unit after its index, eased by magpie's curve.
|
||||
// Bytes interpolate along the same easing, so the counters count up
|
||||
// smoothly instead of jumping at each landing.
|
||||
function frame(stepsList, t) {
|
||||
const n = stepsList.length;
|
||||
t = Math.min(n, Math.max(0, t));
|
||||
const progress = new Array(n);
|
||||
let logical = 0, stored = 0, landed = 0;
|
||||
const branches = new Set();
|
||||
for (let i = 0; i < n; i++) {
|
||||
const raw = clamp01(t - i);
|
||||
const p = magpieEase(raw);
|
||||
progress[i] = p;
|
||||
const prevL = i ? stepsList[i - 1].cumLogical : 0;
|
||||
const prevS = i ? stepsList[i - 1].cumStored : 0;
|
||||
logical += (stepsList[i].cumLogical - prevL) * p;
|
||||
stored += (stepsList[i].cumStored - prevS) * p;
|
||||
if (raw >= 1) { landed++; branches.add(stepsList[i].branch); }
|
||||
}
|
||||
return { progress, logical, stored, landed, branches: branches.size };
|
||||
}
|
||||
|
||||
// A landing's pulse ring, u seconds-fraction through its life: it
|
||||
// swells out and thins away. Null once spent.
|
||||
function pulse(u) {
|
||||
if (u < 0 || u > 1) return null;
|
||||
return { scale: 0.35 + 1.9 * easeOutCubic(u), opacity: 0.85 * (1 - u) * (1 - u) };
|
||||
}
|
||||
|
||||
// The ink for an agent's monogram on its own colour: near-black on
|
||||
// light brand colours, white on dark ones (relative luminance).
|
||||
function markInk(hex) {
|
||||
const m = /^#?([0-9a-f]{6})$/i.exec(String(hex || ""));
|
||||
if (!m) return "#101410";
|
||||
const n = parseInt(m[1], 16);
|
||||
const lum = (0.2126 * (n >> 16) + 0.7152 * (n >> 8 & 255) + 0.0722 * (n & 255)) / 255;
|
||||
return lum > 0.62 ? "#101410" : "#ffffff";
|
||||
}
|
||||
|
||||
// The agents' own marks, drawn inside each checkpoint badge.
|
||||
// Geometry sources: for most agents this is the icon magpie itself
|
||||
// ships in internal/gui/assets/icons (claude's starburst, codex's
|
||||
// knot — its rounded-square backing dropped, the badge is the disc
|
||||
// — cursor's hex mark, gemini's sparkle, opencode's frame, pi's
|
||||
// blocks, deepseek's whale for dsh, cline's bot head, grok's swirl,
|
||||
// kimi's K, hermes' winged H, goose's bird). Three are original
|
||||
// simplified glyphs in the same weight, where magpie ships only a
|
||||
// raster (zcode) or a mark too fine to survive at badge size
|
||||
// (qoder's folded ribbon, factory's droid). An agent with no entry
|
||||
// here falls back to its monogram in the same badge (glyphFor).
|
||||
const ICONS = {
|
||||
claude: { viewBox: "0 0 24 24", sw: 1.0, paths: [{ d: "M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z", rule: "nonzero" }] },
|
||||
codex: { viewBox: "0 0 24 24", sw: 1.1, paths: [{ d: "M9.064 3.344a4.578 4.578 0 012.285-.312c1 .115 1.891.54 2.673 1.275.01.01.024.017.037.021a.09.09 0 00.043 0 4.55 4.55 0 013.046.275l.047.022.116.057a4.581 4.581 0 012.188 2.399c.209.51.313 1.041.315 1.595a4.24 4.24 0 01-.134 1.223.123.123 0 00.03.115c.594.607.988 1.33 1.183 2.17.289 1.425-.007 2.71-.887 3.854l-.136.166a4.548 4.548 0 01-2.201 1.388.123.123 0 00-.081.076c-.191.551-.383 1.023-.74 1.494-.9 1.187-2.222 1.846-3.711 1.838-1.187-.006-2.239-.44-3.157-1.302a.107.107 0 00-.105-.024c-.388.125-.78.143-1.204.138a4.441 4.441 0 01-1.945-.466 4.544 4.544 0 01-1.61-1.335c-.152-.202-.303-.392-.414-.617a5.81 5.81 0 01-.37-.961 4.582 4.582 0 01-.014-2.298.124.124 0 00.006-.056.085.085 0 00-.027-.048 4.467 4.467 0 01-1.034-1.651 3.896 3.896 0 01-.251-1.192 5.189 5.189 0 01.141-1.6c.337-1.112.982-1.985 1.933-2.618.212-.141.413-.251.601-.33.215-.089.43-.164.646-.227a.098.098 0 00.065-.066 4.51 4.51 0 01.829-1.615 4.535 4.535 0 011.837-1.388zm3.482 10.565a.637.637 0 000 1.272h3.636a.637.637 0 100-1.272h-3.636zM8.462 9.23a.637.637 0 00-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 101.095.649l1.454-2.455a.636.636 0 00.005-.64L8.462 9.23z" }] },
|
||||
opencode: { viewBox: "0 0 24 24", paths: [{ d: "M16 6H8v12h8V6zm4 16H4V2h16v20z" }] },
|
||||
cursor: { viewBox: "0 0 24 24", paths: [{ d: "M22.106 5.68L12.5.135a.998.998 0 00-.998 0L1.893 5.68a.84.84 0 00-.419.726v11.186c0 .3.16.577.42.727l9.607 5.547a.999.999 0 00.998 0l9.608-5.547a.84.84 0 00.42-.727V6.407a.84.84 0 00-.42-.726zm-.603 1.176L12.228 22.92c-.063.108-.228.064-.228-.061V12.34a.59.59 0 00-.295-.51l-9.11-5.26c-.107-.062-.063-.228.062-.228h18.55c.264 0 .428.286.296.514z" }] },
|
||||
gemini: { viewBox: "0 0 24 24", paths: [{ d: "M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" }] },
|
||||
pi: { viewBox: "0 0 24 24", paths: [{ d: "M1 1h16.5v11H12v5.5H6.5V23H1V1zm5.5 5.5V12H12V6.5H6.5z", rule: "evenodd" }, { d: "M17.5 12H23v11h-5.5V12z", rule: "evenodd" }] },
|
||||
dsh: { viewBox: "0 0 24 24", sw: 1.1, paths: [{ d: "M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" }] },
|
||||
qoder: { viewBox: "0 0 24 24", paths: [{ d: "M3.9 11.5a7.6 7.6 0 1 1 15.2 0a7.6 7.6 0 1 1-15.2 0M7.4 11.5a4.1 4.1 0 1 1 8.2 0a4.1 4.1 0 1 1-8.2 0", rule: "evenodd" }, { d: "M13.9 14.6l2.5-1.7 4.9 7.3-2.5 1.7z" }] },
|
||||
cline: { viewBox: "0 0 24 24", paths: [{ d: "M17.035 3.991c2.75 0 4.98 2.24 4.98 5.003v1.667l1.45 2.896a1.01 1.01 0 01-.002.909l-1.448 2.864v1.668c0 2.762-2.23 5.002-4.98 5.002H7.074c-2.751 0-4.98-2.24-4.98-5.002V17.33l-1.48-2.855a1.01 1.01 0 01-.003-.927l1.482-2.887V8.994c0-2.763 2.23-5.003 4.98-5.003h9.962zM8.265 9.6a2.274 2.274 0 00-2.274 2.274v4.042a2.274 2.274 0 004.547 0v-4.042A2.274 2.274 0 008.265 9.6zm7.326 0a2.274 2.274 0 00-2.274 2.274v4.042a2.274 2.274 0 104.548 0v-4.042A2.274 2.274 0 0015.59 9.6z" }, { d: "M12.054 5.558a2.779 2.779 0 100-5.558 2.779 2.779 0 000 5.558z" }] },
|
||||
grok: { viewBox: "0 0 24 24", paths: [{ d: "M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815" }] },
|
||||
kimi: { viewBox: "0 0 24 24", paths: [{ d: "M21.846 0a1.923 1.923 0 110 3.846H20.15a.226.226 0 01-.227-.226V1.923C19.923.861 20.784 0 21.846 0z" }, { d: "M11.065 11.199l7.257-7.2c.137-.136.06-.41-.116-.41H14.3a.164.164 0 00-.117.051l-7.82 7.756c-.122.12-.302.013-.302-.179V3.82c0-.127-.083-.23-.185-.23H3.186c-.103 0-.186.103-.186.23V19.77c0 .128.083.23.186.23h2.69c.103 0 .186-.102.186-.23v-3.25c0-.069.025-.135.069-.178l2.424-2.406a.158.158 0 01.205-.023l6.484 4.772a7.677 7.677 0 003.453 1.283c.108.012.2-.095.2-.23v-3.06c0-.117-.07-.212-.164-.227a5.028 5.028 0 01-2.027-.807l-5.613-4.064c-.117-.078-.132-.279-.028-.381z" }] },
|
||||
droid: { viewBox: "0 0 24 24", paths: [{ d: "M4.5 10.2c0-1.9 1.5-3.4 3.4-3.4h8.2c1.9 0 3.4 1.5 3.4 3.4v5.6c0 1.9-1.5 3.4-3.4 3.4H7.9c-1.9 0-3.4-1.5-3.4-3.4zM11.2 3.9h1.6v2.9h-1.6zM10.8 3a1.2 1.2 0 1 1 2.4 0a1.2 1.2 0 1 1-2.4 0M7.65 12.8a1.35 1.35 0 1 1 2.7 0a1.35 1.35 0 1 1-2.7 0M13.65 12.8a1.35 1.35 0 1 1 2.7 0a1.35 1.35 0 1 1-2.7 0", rule: "evenodd" }] },
|
||||
hermes: { viewBox: "12 16 40 40", sw: 2.2, paths: [{ d: "M21 20h7v14h8V20h7v32h-7V40h-8v12h-7zM13 21l7 3v6l-7-3zM51 21l-7 3v6l7-3z" }] },
|
||||
goose: { viewBox: "0 0 24 24", paths: [{ d: "M21.595 23.61c1.167-.254 2.405-.944 2.405-.944l-2.167-1.784a12.124 12.124 0 01-2.695-3.131 12.127 12.127 0 00-3.97-4.049l-.794-.462a1.115 1.115 0 01-.488-.815.844.844 0 01.154-.575c.413-.582 2.548-3.115 2.94-3.44.503-.416 1.065-.762 1.586-1.159.074-.056.148-.112.221-.17.003-.002.007-.004.009-.007.167-.131.325-.272.45-.438.453-.524.563-.988.59-1.193-.061-.197-.244-.639-.753-1.148.319.02.705.272 1.056.569.235-.376.481-.773.727-1.171.165-.266-.08-.465-.086-.471h-.001V3.22c-.007-.007-.206-.25-.471-.086-.567.35-1.134.702-1.639 1.021 0 0-.597-.012-1.305.599a2.464 2.464 0 00-.438.45l-.007.009c-.058.072-.114.147-.17.221-.397.521-.743 1.083-1.16 1.587-.323.391-2.857 2.526-3.44 2.94a.842.842 0 01-.574.153 1.115 1.115 0 01-.815-.488l-.462-.794a12.123 12.123 0 00-4.049-3.97 12.133 12.133 0 01-3.13-2.695L1.332 0S.643 1.238.39 2.405c.352.428 1.27 1.49 2.34 2.302C1.58 4.167.73 3.75.06 3.4c-.103.765-.063 1.92.043 2.816.726.317 1.961.806 3.219 1.066-1.006.236-2.11.278-2.961.262.15.554.358 1.119.64 1.688.119.263.25.52.39.77.452.125 2.222.383 3.164.171l-2.51.897a27.776 27.776 0 002.544 2.726c2.031-1.092 2.494-1.241 4.018-2.238-2.467 2.008-3.108 2.828-3.8 3.67l-.483.678c-.25.351-.469.725-.65 1.117-.61 1.31-1.47 4.1-1.47 4.1-.154.486.202.842.674.674 0 0 2.79-.861 4.1-1.47.392-.182.766-.4 1.118-.65l.677-.483c.227-.187.453-.37.701-.586 0 0 1.705 2.02 3.458 3.349l.896-2.511c-.211.942.046 2.712.17 3.163.252.142.509.272.772.392.569.28 1.134.49 1.688.64-.016-.853.026-1.956.261-2.962.26 1.258.75 2.493 1.067 3.219.895.106 2.051.146 2.816.043a73.87 73.87 0 01-1.308-2.67c.811 1.07 1.874 1.988 2.302 2.34h-.001z" }] },
|
||||
zcode: { viewBox: "0 0 24 24", paths: [{ d: "M5.5 4.2h13v3L10.7 16.8h7.8v3h-13v-3L13.3 7.2H5.5z" }] },
|
||||
};
|
||||
|
||||
// LayerFS's own mark for a bough with no agent on it (main, or a
|
||||
// branch named for its work): the leaf the picture began with, in
|
||||
// the same badge and the same draw-on treatment as the icons.
|
||||
const LEAF_GLYPH = { viewBox: "-11 -11 22 22", paths: [{ d: "M0-10C8-6 10 4 0 11C-10 4-8-6 0-10Z" }] };
|
||||
|
||||
// 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);
|
||||
if (!agent) return { type: "leaf", glyph: LEAF_GLYPH };
|
||||
const icon = ICONS[agent.id];
|
||||
if (icon) return { type: "icon", agent, icon };
|
||||
return { type: "mark", agent };
|
||||
}
|
||||
|
||||
// A glyph's draw state at step progress p: its outline draws
|
||||
// itself over the first stretch (stroke dashoffset, the same
|
||||
// pathLength trick as the boughs), the fill fades in over the
|
||||
// second half, and a soft outline lingers once landed. Reduced
|
||||
// motion settles every glyph fully drawn at any progress.
|
||||
function iconDraw(p, rm) {
|
||||
if (rm) return { offset: 0, fillOpacity: 1, strokeOpacity: 0.45 };
|
||||
const fill = clamp01((p - 0.5) / 0.5);
|
||||
return { offset: 1 - clamp01(p / 0.72), fillOpacity: fill, strokeOpacity: 1 - fill * 0.55 };
|
||||
}
|
||||
// One line of a checkpoint's detail card.
|
||||
function detail(commit, lang) {
|
||||
const t = text(lang);
|
||||
const d = commit.delta || { added: 0, modified: 0, deleted: 0 };
|
||||
const parts = [];
|
||||
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}`);
|
||||
return {
|
||||
message: commit.message || "",
|
||||
meta: `${commit.files == null ? "" : `${commit.files} ${t.files} · `}${t.newBytes} ${bytes(commit.newBytes)} / ${bytes(commit.logicalBytes)}`,
|
||||
delta: parts.join(" · "),
|
||||
};
|
||||
}
|
||||
|
||||
globalThis.LayerfsView = {
|
||||
TEXT, text, bytes, lanes, steps, publishes, layout, detail, AGENTS, agentOf,
|
||||
ICONS, LEAF_GLYPH, glyphFor, iconDraw,
|
||||
cubicBezier, magpieEase, easeOutCubic, easeOutBack, clamp01, frame, pulse, markInk,
|
||||
};
|
||||
})();
|
||||
@@ -64,6 +64,7 @@
|
||||
"summary": { "en": "Two routings that keep something in reserve: fill accounts up to a ceiling of their allowance, or use subscriptions before API keys.", "zh": "两种留余量的路由:账号用到额度上限就换下一个,或订阅账号优先于 API key。" } },
|
||||
{ "package": "@magpie-community/tools-calc", "name": "Calc", "kind": "tools", "community": true,
|
||||
"summary": { "en": "Exact arithmetic, unit conversion and calendar date math as tools for every agent: no network, no key.", "zh": "给每个 agent 的精确计算、单位换算和日历日期计算工具:不联网,不需要 key。" } },
|
||||
{"package": "@magpie-community/tools-layerfs", "name": "LayerFS", "kind": "tools", "community": true, "summary": {"en": "LayerFS workspaces for every agent: deduplicated checkpoints and branches behind stable filesystem paths, instead of a fresh copy of the tree for every agent.", "zh": "给每个 agent 的 LayerFS 工作区:稳定的文件系统路径背后是可去重的检查点与分支,而不是每个 agent 各复制一棵项目树。"}},
|
||||
{ "package": "@magpie-community/page-usage", "name": "Usage Glance", "kind": "page", "community": true,
|
||||
"summary": { "en": "A page in magpie's window with calls, errors, tokens and cost for today, 7 or 30 days, and the models behind them. Reads only your usage summary.", "zh": "在 magpie 窗口里一眼看到今天、7 天或 30 天的调用、错误、token、费用和对应模型。只读取用量汇总。" } },
|
||||
{"package": "@magpie-community/agent-kimi-desktop", "name": "Kimi", "kind": "agent", "community": true, "summary": {"en": "Kimi desktop Work on Magpie's Agents page: select a model from Magpie, then disconnect to restore the original service. Not Kimi Code CLI.", "zh": "把普通 Kimi 桌面版 Work 接入 Magpie Agent 页,使用已配置的模型;断开恢复原连接。不是 Kimi Code CLI。"}},
|
||||
|
||||
Reference in New Issue
Block a user