SLOPSHOPPER

arch

Multi-session architecture exploration workflow — turn raw project ideas into feature briefs for OpenSpec changes

paneguardcommandtoaststatusprompt
★ 1v4.3.0MITupdated 2026-10-17JRoot3D/plugins-cc/plugins/arch
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · arch
│ ┃ Arch graph ✕ › fix the failing auth test and add an audit log call │ ┃ No .arch/index.json here — run /arch:new. │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /arch-graph │ ⎿ arch: Arch graph pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Arch graph
No .arch/index.json here — run /arch:new.
README

Architector

A multi-session architecture exploration workflow that turns raw ideas into implementation-ready feature briefs, each the input for OpenSpec changes.

Requirements

Node.js 18+ (node) on PATH — the native Claude Code installer does not ship it. scripts/arch.mjs (standard library only) owns .arch/index.json; without node every skill stops at start with Claude Code's Shell command failed error.

macOS, Linux and Windows work the same way: the skills call the script with a command that both Bash and PowerShell run, so Git for Windows is optional, and a home directory with spaces in its path is fine.

For a board several people work on at once (see Working in Parallel): git, and a remote the branch tracks.

For the handoff after /arch:finalize: the OpenSpec CLI (npm install -g @fission-ai/openspec) and openspec init in the project. The arch skills themselves don't need it.

Installation

From the plugins-cc marketplace (recommended):

/plugin marketplace add JRoot3D/plugins-cc
/plugin install arch@plugins-cc

For development (from a clone of this repository):

claude --plugin-dir plugins/arch

Once installed, all skills are available as /arch:new, /arch:explore, etc.

Flow

/arch:new [project description]
      ↓ creates: .arch/project-context.md
                 .arch/index.json
                 .arch/ideas/[slug].md  (one per idea node)

/arch:triage                  ← enrich raw ideas with expert discussion points
/arch:explore                 ← navigate and deepen any node
/arch:map                     ← visualise connections (use anytime)
/arch:decide [node]           ← lock in a decision: alternatives, rationale, assumptions, confirmation
/arch:status                  ← where are we, what's blocking, how implementation is going
/arch:audit                   ← audit for gaps, inconsistencies, risks, drift from the briefs

      ↓ repeat until all blocking nodes reach `ready`

/arch:finalize
      ↓ creates: .arch/feature-briefs/NN-[slug].md
                 .arch/todo-list.md
      ↓ updates: openspec/config.yaml  (context, rules, apply guidance — after you confirm)

      ↓ each stage becomes OpenSpec changes:
        /opsx:explore (open questions) → /opsx:propose [change] @brief → /opsx:apply → /opsx:archive
        /arch:status tracks them; /arch:audit openspec checks them against their briefs

When to Use Which Skill

SituationSkill
Starting a new project from scratch/arch:new
Adding new ideas to an existing session/arch:new (appends nodes)
Just finished /arch:new, want expert prep before exploring/arch:triage
Want to enrich a specific node with discussion points/arch:triage [node]
Want to see all nodes and their status/arch:explore (shows dashboard)
Want to go deeper on a specific idea/arch:explore [node]
Want to understand how ideas relate/arch:map
Two ideas might be the same thing/arch:map [a] [b]
Ready to commit to a direction/arch:decide [node]
Decided node with all questions resolved → ready/arch:decide [node]
Revisit or reopen a decision/arch:decide [node]
A node needs another slug, its scope and decision unchanged/arch:map [node] → rename (arch.mjs rename-node OLD NEW)
Change a node's priority/arch:decide [node] priority [level]
Want a progress snapshot/arch:status
Want to see the board and its dependency graph in the browser/arch-board
Several people will work on the board at once, or the project takes changes through pull requests/arch-share [branch] (once, at the start), then the skills as usual
A run ended before it released its locks, or release failed and you fixed the cause/arch-release
A teammate's lock is abandoned/arch-unlock [node]
Want to find gaps or inconsistencies/arch:audit
Checking one node's decisions in context/arch:audit [node]
All blocking nodes are ready/arch:finalize
More nodes became ready after finalizing/arch:finalize (appends new stages)
A decision changed after its brief was written/arch:finalize (supersedes, follows up or amends the brief)
The plan moved scope or order between stages, and every decision holds/arch:finalize revise NN (amends, supersedes or follows up brief NN)
Ran openspec init after finalizing/arch:finalize (adds the arch config to openspec/config.yaml)
Want to know how implementation of the feature briefs is going/arch:status
Checking for drift between OpenSpec changes and the feature briefs they came from/arch:audit openspec

Graph Pane

/arch-graph opens a side pane with the dependency graph from .arch/index.json: nodes grouped into layers by dependency depth (layer 0 has no prerequisites), each with its maturity symbol, priority and ← prerequisites; nodes caught in a dependency cycle under cycle; then shared concerns (↔) and conflicts (⚡). Press a node (click it, or ctrl+x tab into the pane and Enter) to run /arch:explore on it — queued until the current turn ends. It redraws after every arch.mjs call, so it follows /arch:map, /arch:decide and the rest live. In a fullscreen terminal 144+ columns wide it opens by itself when the project has an .arch/index.json; run /arch-graph again to refresh after editing the index by hand.

Viewing the Board

/arch-board opens the board in your browser, live. The page shows everything /arch:status knows, plus the dependency graph, and it updates while you and the skills work. It needs no server and nothing to install: it is .arch/board.html, a file you can also open directly or bookmark.

What you see

  • Header: project, stage, revision, the time the data was written, and the finalize gate. The gate is green when open, and red with the reasons when closed.
  • Maturity: how many nodes are at each level.
  • Dependency graph: layers run left to right. Layer 0 has no prerequisites, and each later layer depends on earlier ones. Nodes caught in a dependency cycle sit in a cycle column.
  • Box colour is maturity: grey raw-idea, blue explored, purple decided, green ready. A thick border marks a blocking node, a faded box a deferred one, and 🔒 a locked one.
  • An arrow is a dependency, from prerequisite to dependent. Grey dashes are a shared concern; red dashes a conflict.
  • Hover a box or a line for its summary or note.
  • Nodes: the table, by priority then maturity. Rev counts the sessions that changed the node; Lock says who holds it (hover for host and time).
  • Node file: the clicked node's file as it is on disk.
  • Problems: what arch.mjs check reports.
  • Full state report: the arch.mjs summary the skills read.

Moving around

  • Click a node, in the graph or the table: it, its connections and the nodes at their other end stay lit, the rest dims, and its file opens beside the table. Click it again, click an empty spot or press Esc to clear.
  • board.html#auth opens on auth.
  • Past 40 nodes the boxes shrink to one line (details on hover); a wide graph scrolls sideways.
  • Untick live to freeze the page while you read.

How it stays current

The page itself never changes. Its data is .arch/board.js, which arch.mjs rewrites after every write (set, connect, log and the rest) and whenever it fetches the locks. The page reads it every 2 seconds.

The data is a script rather than JSON for a reason: a page opened from disk may load a script beside it, but the browser will not let it read index.json.

  • A node file edited by hand shows up at the next arch.mjs write.
  • On a shared board the page follows the board branch in your clone: it is pulled, and the locks fetched, when a session or an /arch: skill starts, and at every claim and release.

board.html is created with the board, and copied again only when a plugin update changes it. For a board from an older version, run /arch-board once. If the page says board.js not found, run /arch-board. Both files are listed in .arch/.gitignore.

Idea Node Maturity

raw-idea → explored → decided → ready
MaturitySymbolMeaning
raw-idea◻Named and described, nothing more
explored◽Discussed in depth, tradeoffs surfaced
decided◈Approach chosen, rationale documented
ready✦Fully specified, can go into a feature brief for OpenSpec

Maturity is advanced by:

  • raw-idea → explored : /arch:explore
  • explored → decided : /arch:decide
  • decided → ready : /arch:decide (when the readiness criteria hold: no open questions, implications for every connection, prerequisites ready, no open conflict, assumptions backed in proportion to reversal cost)
  • decided/ready → explored : /arch:decide (reopening a decision)

Node Priority

PriorityMeaning
blockingMust reach ready before /arch:finalize can run
coreCentral to the product, should be decided before finalize
extensionValuable but not required for first implementation pass
deferredConsciously set aside — will not appear in todo list

Gate rule: /arch:finalize requires all blocking nodes to be at ready and arch.mjs check to report no problems — a decided/ready node without a ## Decision, an open conflict on a decided node, a dependency cycle, or a ready node whose prerequisite is not. It then re-checks each node's readiness criteria before writing its brief. Non-blocking nodes that aren't ready are flagged but do not block finalization.

Decision Records and Briefs

Decisions follow ADR practice (MADR): each ## Decision lists alternatives, rationale, implications, the assumptions it rests on (with confidence and basis — a dated source, a spike or a measurement) and a confirmation criterion that would show it is wrong. Evidence is scaled to reversal cost: a database choice needs more than a logging library. A costly choice resting on a shaky assumption, or on one vendor, can instead be made cheaper to reverse: its Implications name a Boundary: — the interface the other nodes use instead of it — and /arch:audit flags a node that reaches past it. A revisited decision is kept as ## Previous Decision (superseded …), never erased. A decision recorded in the project's own records (an ADR folder, say) carries a _Record: docs/adr/0004-auth.md @ 2026-10-13_ line: until that file is on the remote's default branch, changed on or after that date (without @ date, until it exists there), summary lists the node under RECORDS_PENDING, and the node stays decided — no brief is written for it. A node's slug changes with arch.mjs rename-node, which moves its file, connections and revision; briefs that name the old slug keep counting it through aliases in index.json. Run it only once every clone of a shared board is on 4.3 or later.

Feature briefs are append-only. Each records the revision of every node it covers (_Arch revision: auth=3, data-model=5_ — a node's revision counts the sessions that changed it), and of each node its text relies on without covering it (_Arch context: billing=2_); when one of them changes later, or the brief requires a stage another brief superseded, summary lists the brief under BRIEFS_OUTDATED, and /arch:finalize asks whether to supersede it (a replacement brief; the old todo-list row is marked superseded), follow it up (a delta brief that depends on it), amend it (its text brought in line with the current decisions and the plan, marked _Amended:_; only before the stage has tasks done) or keep it. After a supersede, the other briefs' - Requires: lines and the todo list's Depends On cells name the replacement. When the plan moves scope between stages and no decision changed, /arch:finalize revise NN offers the same options for brief NN. The stage's state in OpenSpec decides which: not started → amend, supersede or keep; planned → amend, supersede or keep, where an amended brief's change is revised with /opsx:update [change] @[brief] and the replacement keeps the change names and you revise the proposed change with /opsx:update [change] @.arch/feature-briefs/[new brief] before /opsx:apply (one with no tasks yet is continued with /opsx:propose [change] @.arch/feature-briefs/[new brief]); in progress or done → follow up or keep. When the state is unknown, or there is no openspec/ directory here, finalize asks how far the stage got. After a follow up, a change of the old stage that already has tasks done finishes on the old brief's decisions; one with no task done takes the follow-up brief too: not proposed or no tasks yet → /opsx:propose [change] @[old brief] @[follow-up brief]; 0/M tasks → /opsx:update [change] @[follow-up brief] before /opsx:apply.

project-context.md can name two more things. ## Task plans lists the files that hold the project's task ids, their dependencies and their scope: /arch:finalize then checks each proposed stage against them (a task whose dependency sits in a later stage, scope the plan gives to another task) before it writes, and /arch:audit reports briefs that drifted from the plan, with /arch:finalize revise NN as the fix. ## Writing rules names a style guide, a skill or a lint command: finalize follows it in the briefs it writes and runs the lint on them.

.arch/ Structure

.arch/
  project-context.md          ← shared context (product type, constraints, out of scope; optional ## Task plans and ## Writing rules)
  index.json                  ← all nodes and connections
  sessions.jsonl              ← session history, one line per skill run
  .gitattributes              ← merges sessions.jsonl by union, index.json through arch's merge driver
  .gitignore                  ← keeps the local write lock and the board page out of git
  board.html, board.js        ← the board page (/arch-board) and the state it shows
  ideas/
    tech-stack.md             ← one file per idea node
    data-model.md
    canvas-ui.md
    ...
    [slug].archived.md        ← merged/split nodes (kept for history)
  feature-briefs/
    01-foundation.md          ← output of /arch:finalize
    02-auth.md
    03-canvas.md
    ...
  todo-list.md                ← master implementation list

Add .arch/ to .gitignore if you don't want architecture exploration in version history. Or commit it — the decision history is valuable. Or give it a branch of its own with /arch-share: the history is kept, and it never mixes with the code's branches or pull requests (see Working in Parallel).

Working in Parallel

Several people can work on one board at the same time, each in their own clone on their own machine. A node is held by one person at a time, and everyone else keeps working on other nodes. Reading, /arch:status, /arch:audit and the board page are never blocked.

The board lives on a git branch of its own, apart from the code. Whatever branch your code is on, and however the project takes code changes (pull requests from feature branches included), board changes go straight to the board branch. They never land in a code branch or a pull request.

Set it up

At the start of the architecture work, one person runs /arch-share (/arch:new suggests it). Use /arch-share [branch] to name the branch; the default is arch. You need a git repository with a remote and git config user.email set; that address is how arch tells people apart. /arch-share does four things:

  1. It moves .arch/ onto a new branch that holds only the board. .arch/ stays where it is, now as a git worktree of that branch.
  2. It pushes the board branch.
  3. It creates refs/arch/locks on the remote: a ref of its own holding locks.json.
  4. It hides .arch/ from the code checkout through .git/info/exclude, so git status on the code stays clean. If a code branch already tracked .arch/, the removal is staged there. Commit it the way the project takes changes; a pull request is fine, since the board itself never needs one again.

Everyone else pulls the project, installs the plugin and starts Claude Code there. At session start the plugin checks out the board branch at .arch/ by itself, once the clone has fetched it (a clone made before /arch-share gets it with its next git fetch or git pull). A repository with no board makes no network call for this, and neither does a code checkout made with git worktree add: the board stays in the main worktree. If you already have a .arch/ folder, run /arch-share: it sets the board branch up and keeps the old folder as .arch.local-….

Board commits run this clone's git hooks, like any commit. Never skip them with --no-verify: a secret scan, for one, must see board commits too. If the code's hooks reject board commits (a commit-message rule for the code, say), give the board worktree hooks of its own: git config extensions.worktreeConfig true, then git -C .arch config --worktree core.hooksPath <dir>. arch never runs a hook stored on the board branch: that branch gets no review, so such a hook would run unreviewed code.

The board branch is pushed to directly, so it must not require pull requests. If the repository protects every branch, exempt the board branch. main cannot serve as the board branch: your code checkout usually has it checked out, git checks a branch out in one place only, and main often takes changes only through pull requests.

This is worth doing alone too: in a project that merges through pull requests, /arch-share keeps board commits out of your feature branches.

Day to day

Run the skills as usual; they take the locks and give them back:

Alice: /arch:explore auth            Bob: /arch:decide data-model
  claim auth ✓ (pulls arch first)      claim data-model ✓
  … discussion, node file updated …    … decision recorded …
  release: commit, pull, push arch,    release: commit, pull (merges
           free auth                            Alice's push), push arch,
                                                free data-model
  • Claim. A skill claims a node as soon as it starts working on it, before the discussion, so nobody changes the node under you. A new node is claimed by its slug before its file is written. The status line shows arch: holding auth.
  • Fresh content. Claim pulls the board branch before it takes the node, so you start from what the others released. A session start and the start of each /arch: skill pull it too, committing nothing: when the pull would overwrite a change you have not released, it waits (BOARD_PULL_SKIPPED), and your next claim or release commits and merges it. Claim and release commit only board files (index.json, sessions.jsonl, .gitattributes, .gitignore, todo-list.md, project-context.md, ideas/*.md, feature-briefs/*.md); anything else in .arch/, such as .DS_Store or a scratch script, stays out and is named in their output. On a large repository the fetch of the code's branches behind /arch:status adds a moment to each skill start.
  • Busy node. When someone else holds the node, the skill says who and since when, and leaves the node alone: auth is locked by alice@team.dev on alice-mbp since 2026-10-10 09:12 UTC. Pick another node, or ask them to finish.
  • Release. At the end of the run the skill releases. It commits the board files on the board branch, pulls (merge, never rebase), pushes the board branch and frees your locks. Your code branch is never touched. The commit title names the first three keys you held; the body lists all of them.

Implementing the features

Implementation goes the project's usual way: feature branches and pull requests. The board only supplies the briefs.

WhatWhereHow it reaches the remote
Nodes, decisions, feature briefs, todo list.arch/ (the board branch)release, directly
openspec/config.yaml (arch's context, rules, apply guidance)a code branchthe project's pull request flow
OpenSpec changes (openspec/changes/) and the codefeature branchespull requests
  1. /arch:finalize takes the #briefs lock, so two runs never number stages alike. The briefs and the todo list go to the board branch. Its edit to openspec/config.yaml is a code change: merge it the usual way, since the /opsx: commands follow arch's rules only once it is in.
  2. For each stage, a developer starts a feature branch and runs /opsx:propose [change] @.arch/feature-briefs/NN-slug.md. The brief is on disk in every clone, whatever the code branch, because .arch/ is the board's worktree. Then /opsx:apply, the pull request, and /opsx:archive.
  3. Implementation takes no locks: locks guard the board, so several people implement different stages at once.
  4. When a task cannot follow a Key Decision, apply stops and points to /arch:decide [node]. Run it from any code branch; it claims the node on the board. The brief then reads as outdated, and /arch:finalize supersedes or follows it up. /opsx:update [change] @[new brief] carries the change in the feature branch.
  5. The proposal and design.md name each brief as feature-briefs/NN-slug.md on the board branch. A reviewer finds it there, and design.md carries its Key Decisions anyway, so the pull request reads on its own.

/arch:status shows the same progress to everyone, whatever branch their code checkout is on. On a shared board it reads openspec/changes/ on every branch of the remote, open pull requests included, as well as the working tree. A change archived on any branch counts as done; otherwise its furthest progress is shown with the branch it is on, e.g. add-auth 3/8 tasks on origin/feat/auth. The remote's branches are fetched at session start and when an /arch: skill starts.

What a lock covers

LockCoversTaken by
a node slug, e.g. authits file ideas/auth.md; its maturity, priority, name and summary; archiving it/arch:explore, /arch:decide, /arch:triage, /arch:map (each node it changes), /arch:new (each new node)
#briefsfeature-briefs/ and todo-list.md/arch:finalize
#contextproject-context.md/arch:new, when it adds constraints

Connections and the session log take no lock: two people connecting nodes at the same time merge cleanly (see below).

Commands

CommandWhat it does
/arch-share [branch]Gives the board its own branch and the locks: once per project. In another clone of a shared project, sets .arch/ up as the board branch's worktree
/arch-releaseReleases now: commits and pushes the board branch, frees your locks. Use it after fixing a failed release, or when a run ended before it could release
/arch-unlock <node>Frees a lock its holder abandoned, such as a lost laptop or a crashed session. Works on anyone's lock, so check with them first: changes they made under it and never released may conflict later

Locks never expire on their own.

Never run git clean -x (-fdx, -ffdx) in the project: .arch/ is hidden from the code through .git/info/exclude, and -x deletes excluded files, board worktree included. What was released is on the remote; what was not is gone. Plain git clean -fd leaves it alone.

When something goes wrong

You seeDo
auth is locked by …Work on another node, or ask them to release

| `this project's board is shared on the branch arch, and .arch/ in <folder

Source 1 files
hooks/register.tsx 212 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3const PANE = 'arch-graph'
4const INDEX = '.arch/index.json'
5const SYMBOL: Record<string, string> = { 'raw-idea': '◻', explored: '◽', decided: '◈', ready: '✦' }
6const PRIORITY = ['blocking', 'core', 'extension', 'deferred']
7
8type Node = { slug: string; priority?: string; maturity?: string }
9type Link = { from: string; to: string; type: string }
10type Index = { project?: string; nodes?: Node[]; connections?: Link[] }
11
12// A file under .arch/, on any platform's separators
13const ARCH_FILE = /(^|[\\/])\.arch[\\/]/
14// summary's and sync's lock report: the header and its indented lines
15const LOCKS = /^LOCKS shared via .*(?:\r?\n {2}.*)*/m
16const SHARING = /arch\.mjs"?\s+(share|claim|release|unlock)\b/
17
18const fit = (text: string, width: number) => (text.length > width ? `${text.slice(0, width - 1)}…` : text)
19const rank = (n: Node) => {
20  const i = PRIORITY.indexOf(n.priority ?? '')
21  return i < 0 ? PRIORITY.length : i
22}
23const open = ($: EngineInterface) => $.ui.open({ id: PANE, title: 'Arch graph' })
24// Not awaited by the Button: the skill is queued and runs once the session is idle.
25const explore = ($: EngineInterface, slug: string) => {
26  void $.command.run({ command: 'arch:explore', args: slug }).catch(err => $.ui.toast(`/arch:explore failed: ${err}`))
27}
28
29const arch = ($: EngineInterface, args: string[]) => $.process.run(['node', `${$.plugin.root}/scripts/arch.mjs`, ...args])
30
31// Fetches refs/arch/locks (a shared board's locks) and shows the ones you hold; resolves the LOCKS block, if shared.
32const sync = async ($: EngineInterface) => {
33  const block = LOCKS.exec((await arch($, ['sync'])).stdout)?.[0]
34  const mine = (block ?? '').split(/\r?\n/).flatMap(line => /^ {2}(\S+) — yours/.exec(line)?.[1] ?? [])
35  $.ui.status(mine.length ? `arch: holding ${mine.join(', ')}` : undefined)
36  return block
37}
38
39// The reason a lock keeps you from editing file, or undefined
40const locked = async ($: EngineInterface, file: string) => {
41  if (!ARCH_FILE.test(file)) return undefined
42  const { exitCode, stdout, stderr } = await arch($, ['can-edit', file])
43  return exitCode === 0 ? undefined : `${$.plugin.name}: ${(stderr || stdout).replace(/^ERROR: /, '').trim()}`
44}
45
46// The refusal when the lock check itself failed
47const unchecked = ($: EngineInterface, file: unknown) => ({
48  deny: `${$.plugin.name}: could not check the lock on ${String(file)} — run /arch:status, then try again`,
49})
50
51// Runs an arch.mjs command the person typed, then refreshes the locks it may have changed.
52const typed = async ($: EngineInterface, args: string[]) => {
53  const { exitCode, stdout, stderr } = await arch($, args)
54  await sync($).catch(() => undefined)
55
56  return { text: (exitCode === 0 ? stdout : stderr || stdout).trim() }
57}
58
59// Dependency depth: 0 without prerequisites, else one past the deepest. Nodes in or behind a cycle never settle.
60const levels = (slugs: string[], prereqs: Map<string, string[]>) => {
61  const level = new Map<string, number>()
62  for (let moved = true; moved; ) {
63    moved = false
64    for (const slug of slugs) {
65      const before = prereqs.get(slug) ?? []
66      if (level.has(slug) || !before.every(p => level.has(p))) continue
67      level.set(slug, Math.max(-1, ...before.map(p => level.get(p) ?? 0)) + 1)
68      moved = true
69    }
70  }
71  return level
72}
73
74export const register: Register = on => {
75  on('session.start', async ($, e, next) => {
76    await $.command.register({ name: 'arch-graph', description: 'Show the arch dependency graph (.arch/index.json) in a pane' })
77    await $.command.register({ name: 'arch-board', description: 'Open .arch/board.html: the board state and dependency graph, live in the browser' })
78    await $.command.register({ name: 'arch-share', description: 'Give the arch board its own git branch and per-node locks, or set this clone up for a shared board: /arch-share [branch]' })
79    await $.command.register({ name: 'arch-release', description: 'Commit and push .arch/, then free the arch nodes you hold' })
80    await $.command.register({ name: 'arch-unlock', description: "Free an abandoned arch lock, yours or another person's: /arch-unlock <node>" })
81    // with no .arch/ at all, sync joins a board the remote holds (a fresh clone) and otherwise makes no network call
82    const board = await $.fs.exists(INDEX)
83    if (board) void open($)
84    if (board || !(await $.fs.exists('.arch')))
85      void sync($)
86        .then(async () => {
87          if (!board && (await $.fs.exists(INDEX))) void open($)
88        })
89        .catch(() => undefined)
90
91    return next(e)
92  })
93
94  on('command.run', { command: 'arch-graph' }, async $ => {
95    await open($)
96    $.ui.invalidate('ui.render')
97
98    return { text: 'Arch graph pane opened.' }
99  })
100
101  on('command.run', { command: 'arch-board' }, async $ => {
102    const { exitCode, stdout, stderr } = await arch($, ['board', '--open'])
103
104    return { text: (exitCode === 0 ? stdout : stderr || stdout).trim() }
105  })
106
107  // The person typed it, so it runs: /arch-unlock passes --force, their call that the lock is abandoned.
108  on('command.run', { command: 'arch-share' }, ($, e) => typed($, e.args.trim() ? ['share', e.args.trim()] : ['share']))
109  on('command.run', { command: 'arch-release' }, $ => typed($, ['release']))
110  on('command.run', { command: 'arch-unlock' }, ($, e) =>
111    e.args.trim() ? typed($, ['unlock', e.args.trim(), '--force']) : { text: 'usage: /arch-unlock <node, #briefs or #context>' },
112  )
113
114  // A skill's Current State shows the locks as last fetched: fetch them now and put the fresh block in its place.
115  on('skill.prompt', async ($, e, next) => {
116    const result = await next(e)
117    if (!e.skill.startsWith('arch:') || !(await $.fs.exists(INDEX))) return result
118    const fresh = await sync($).catch(() => undefined)
119    if (fresh === undefined) return result
120
121    return { text: LOCKS.test(result.text) ? result.text.replace(LOCKS, fresh) : `${result.text}\n\nLocks fetched just now:\n${fresh}` }
122  })
123
124  // On a shared board a node's file is edited only under your lock; arch.mjs set/add-node/archive check it themselves.
125  // A check that fails refuses a file under .arch/: a failed guard would otherwise let the edit run.
126  on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
127    const deny = await locked($, e.file_path)
128    return deny === undefined ? next(e) : { deny }
129  }).catch(($, e, next) => (next.called || !ARCH_FILE.test(String(e.file_path)) ? next(e) : unchecked($, e.file_path)))
130  on('tool.call', { tool: 'Write' }, async ($, e, next) => {
131    const deny = await locked($, e.file_path)
132    return deny === undefined ? next(e) : { deny }
133  }).catch(($, e, next) => (next.called || !ARCH_FILE.test(String(e.file_path)) ? next(e) : unchecked($, e.file_path)))
134
135  // Every write to index.json goes through arch.mjs, from Bash or PowerShell.
136  on('tool.call', async ($, e, next) => {
137    const result = await next(e)
138    if ('command' in e && String(e.command).includes('arch.mjs')) {
139      $.ui.invalidate('ui.render')
140      if (SHARING.test(String(e.command))) void sync($).catch(() => undefined)
141    }
142
143    return result
144  })
145
146  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
147    const { Box, Button, Text } = $.ui.resolve(e)
148    const width = Math.max(20, e.props.bodyColumns)
149
150    const raw = await $.fs.read(INDEX).catch(() => undefined)
151    if (raw === undefined) return <Text dimColor>No {INDEX} here — run /arch:new.</Text>
152    let index: Index | null
153    try {
154      index = JSON.parse(String(raw))
155    } catch {
156      return <Text dimColor>{INDEX} is not valid JSON.</Text>
157    }
158
159    const nodes = Array.isArray(index?.nodes) ? [...index.nodes].sort((a, b) => rank(a) - rank(b) || a.slug.localeCompare(b.slug)) : []
160    const live = new Set(nodes.map(n => n.slug))
161    // connections to unknown slugs are left to `arch.mjs check`
162    const links = (Array.isArray(index?.connections) ? index.connections : []).filter(c => live.has(c.from) && live.has(c.to))
163    const prereqs = new Map<string, string[]>()
164    for (const c of links) if (c.type === 'dependency') prereqs.set(c.to, [...(prereqs.get(c.to) ?? []), c.from])
165    const level = levels([...live], prereqs)
166    const groups: [string, Node[]][] = Array.from({ length: Math.max(-1, ...level.values()) + 1 }, (_, i) => [
167      `layer ${i}`,
168      nodes.filter(n => level.get(n.slug) === i),
169    ])
170    groups.push(['cycle', nodes.filter(n => !level.has(n.slug))])
171    const pairs = (type: string, mark: string) => links.filter(c => c.type === type).map(c => `${mark} ${c.from} · ${c.to}`)
172    const extras: [string, string[]][] = [['shared', pairs('shared-concern', '↔')], ['conflicts', pairs('conflict', '⚡')]]
173    const rule = (title: string) => <Text dimColor>{`── ${title} `.padEnd(width, '─').slice(0, width)}</Text>
174
175    return (
176      <Box flexDirection="column">
177        <Text bold>{fit(`${index?.project ?? 'arch'} · ${nodes.length} nodes · ${links.length} links`, width)}</Text>
178        {nodes.length === 0 && <Text dimColor>No nodes yet.</Text>}
179        {groups
180          .filter(([, group]) => group.length)
181          .map(([title, group]) => (
182            <Box flexDirection="column">
183              {rule(title)}
184              {group.map(n => (
185                <Box flexDirection="column">
186                  <Button
187                    plain
188                    key={`node:${n.slug}`}
189                    dimColor={n.priority === 'deferred'}
190                    label={fit(`${SYMBOL[n.maturity ?? ''] ?? '?'} ${n.slug}  ${n.priority ?? ''}`, width)}
191                    onPress={() => explore($, n.slug)}
192                  />
193                  {prereqs.has(n.slug) && <Text dimColor>{fit(`    ← ${prereqs.get(n.slug)?.join(', ')}`, width)}</Text>}
194                </Box>
195              ))}
196            </Box>
197          ))}
198        {extras
199          .filter(([, lines]) => lines.length)
200          .map(([title, lines]) => (
201            <Box flexDirection="column">
202              {rule(title)}
203              {lines.map(line => (
204                <Text>{fit(line, width)}</Text>
205              ))}
206            </Box>
207          ))}
208      </Box>
209    )
210  })
211}
212