dsh-architecture-map 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/CODE_OF_CONDUCT.md +7 -0
- package/CONTRIBUTING.md +24 -0
- package/LICENSE +21 -0
- package/README.md +264 -2
- package/README.zh.md +247 -0
- package/THIRD_PARTY_NOTICES.md +36 -0
- package/client.js +1171 -0
- package/cordis.patch.yml +5 -0
- package/docs/DETAIL.md +76 -0
- package/docs/DETAIL.zh.md +76 -0
- package/docs/preview.svg +50 -0
- package/icon.svg +9 -0
- package/index.js +1 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +68 -4
- package/skills/architecture-map/SKILL.md +75 -0
- package/skills/architecture-map/references/bootstrap.md +100 -0
- package/skills/architecture-map/references/discussion.md +71 -0
- package/skills/architecture-map/references/incremental.md +80 -0
- package/skills/architecture-map/references/schema.md +94 -0
- package/src/README.md +34 -0
- package/src/host/content/index.js +20 -0
- package/src/host/content/local.js +250 -0
- package/src/host/export.js +228 -0
- package/src/host/graph.js +707 -0
- package/src/host/memory.js +364 -0
- package/src/host/plugin.js +1125 -0
- package/src/host/projects.js +241 -0
- package/src/host/remote/commands.js +227 -0
- package/src/host/remote/consent.js +216 -0
- package/src/host/remote/content.js +391 -0
- package/src/host/remote/indexer.js +180 -0
- package/src/host/remote/maintainer.js +85 -0
- package/src/host/remote/ssh.js +287 -0
- package/src/host/remote/state.js +65 -0
- package/src/host/remote/tools.js +162 -0
- package/src/host/signature.js +42 -0
- package/src/host/workspace.js +131 -0
- package/vendor/elkjs.LICENSE +264 -0
- package/vendor/mermaid.LICENSE +21 -0
- package/vendor/mermaid.esm.min.mjs +4343 -0
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# Graph and dossier schema
|
|
2
|
+
|
|
3
|
+
All data lives under `<workspace>/.archmap/`. Do not invent another store.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
.archmap/
|
|
7
|
+
├── graph.json # canonical graph, schema 1
|
|
8
|
+
├── graph.bak.json # previous revision (written from the second write on)
|
|
9
|
+
├── manifest.json # analyzed-file hashes and normalized signatures
|
|
10
|
+
├── overview.md # dossier entry point
|
|
11
|
+
├── modules/<id>.md # one document per graph node
|
|
12
|
+
├── notes/<id>.md # append-only discussion notes
|
|
13
|
+
└── export/ # arch_export output (architecture.mmd/.svg/.md)
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## graph.json
|
|
17
|
+
|
|
18
|
+
```json
|
|
19
|
+
{
|
|
20
|
+
"schema": 1,
|
|
21
|
+
"rev": 6,
|
|
22
|
+
"updatedAt": "2026-11-20T...",
|
|
23
|
+
"layout": { "mode": "layered", "direction": "LR" },
|
|
24
|
+
"groups": [{ "id": "g-core", "title": "Core" }],
|
|
25
|
+
"nodes": [
|
|
26
|
+
{
|
|
27
|
+
"id": "n1",
|
|
28
|
+
"title": "Entry",
|
|
29
|
+
"kind": "entry",
|
|
30
|
+
"group": "g-core",
|
|
31
|
+
"summary": "User request enters the agent and dispatches tools.",
|
|
32
|
+
"status": "fresh",
|
|
33
|
+
"anchors": [{ "path": "src/host/plugin.js", "symbol": "apply" }]
|
|
34
|
+
}
|
|
35
|
+
],
|
|
36
|
+
"edges": [
|
|
37
|
+
{ "id": "e1", "from": "n1", "to": "n2", "label": "writes", "kind": "call" }
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
- **id**: lowercase letter, then lowercase letters/digits/`_`/`-`; unique within its kind.
|
|
43
|
+
- **kind**: free lower-case text; common values `entry`, `module`, `store`, `client`, `service`, `external`.
|
|
44
|
+
- **status**: `fresh`, `stale`, `proposed`.
|
|
45
|
+
- **anchor**: workspace-relative POSIX `path`, optional `symbol`, optional `hash` (the normalized content signature: comments/whitespace ignored for code); no `..`, absolute paths, backslashes or empty segments. `arch_graph_patch` fills a missing hash from disk and preserves an existing hash unless `refreshAnchors:true` is passed.
|
|
46
|
+
- **group**: optional group id; groups have `id` and `title`.
|
|
47
|
+
- **edge**: `from`/`to` must be existing node ids; `kind` common values `call`, `data`, `dependency`, `next`, `contains`.
|
|
48
|
+
- `layout.mode` is advisory for the client; the current client uses its own grid + local positions.
|
|
49
|
+
|
|
50
|
+
`rev` increments on every successful write. Pass the latest `rev` as `baseRev`; a mismatch returns `STALE_REV`. `apply:false` validates and returns a diff without writing. `refreshAnchors:true` recomputes all anchor hashes after review; without it, only missing hashes are filled.
|
|
51
|
+
|
|
52
|
+
## Patch operations
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
add_node { node }
|
|
56
|
+
update_node { id, patch }
|
|
57
|
+
remove_node { id, cascade? }
|
|
58
|
+
add_edge { edge }
|
|
59
|
+
update_edge { id, patch }
|
|
60
|
+
remove_edge { id }
|
|
61
|
+
set_group { group }
|
|
62
|
+
remove_group{ id }
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Add referenced nodes/groups before edges. Large edits should be batched; the tool bounds operation count and field sizes. Unknown fields are rejected so a typo cannot be silently ignored.
|
|
66
|
+
|
|
67
|
+
## Dossier
|
|
68
|
+
|
|
69
|
+
- `arch_doc_get({ id })` / `arch_doc_put({ id, content, mode })`
|
|
70
|
+
- Valid ids: `overview`, `modules/<node-id>`, `notes/<node-id>`.
|
|
71
|
+
- `mode:"append"` adds a blank line + content; overwrite is the default.
|
|
72
|
+
- Documents are capped at **32 KiB** and always end with a newline.
|
|
73
|
+
- `modules/<id>` documents the node (content, relations, history); `notes/<id>` records decisions/findings; `overview` is the map-level summary.
|
|
74
|
+
|
|
75
|
+
## Memory files
|
|
76
|
+
|
|
77
|
+
`manifest.json` stores `{sha256, size, signature}` per analyzed file. `signature` is a normalized hash that ignores comments/whitespace for code files. Never edit the manifest by hand; use `arch_manifest_commit`.
|
|
78
|
+
|
|
79
|
+
## Exports
|
|
80
|
+
|
|
81
|
+
`arch_export` writes deterministic files:
|
|
82
|
+
|
|
83
|
+
- `format:"mermaid"` → `.archmap/export/architecture.mmd`
|
|
84
|
+
- `format:"svg"` → `.archmap/export/architecture.svg`
|
|
85
|
+
- `format:"markdown"` → `.archmap/export/architecture.md`
|
|
86
|
+
|
|
87
|
+
Exports never modify `graph.json` or the manifest.
|
|
88
|
+
|
|
89
|
+
## Limits and failures
|
|
90
|
+
|
|
91
|
+
- Paths are realpath-checked and must stay inside the workspace.
|
|
92
|
+
- Writes are atomic (temp file + rename); a failed write must be reported, never silently retried.
|
|
93
|
+
- The UI polls the graph every 2s; a successful patch becomes visible within ~3s.
|
|
94
|
+
- Node positions are a **local view preference** (browser localStorage), not part of `graph.json`.
|
package/src/README.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# src
|
|
2
|
+
|
|
3
|
+
Host implementation (plain ESM) and the hand-written client bundle.
|
|
4
|
+
|
|
5
|
+
## Host
|
|
6
|
+
|
|
7
|
+
- `host/plugin.js` — entry: `arch_*` tools, `/arch` command, Mermaid static routes, bundled skill registration.
|
|
8
|
+
- `host/projects.js` — `.archmap/index.json` project registry: local and remote entries, validation, atomic writes.
|
|
9
|
+
- `host/workspace.js` — resolves a local path or `remote:<id>` into `workspaceRoot` + per-project `stateDir`, and attaches the local or SSH remote content source.
|
|
10
|
+
- `host/content/index.js` — read-only content contract shared by local and remote content sources.
|
|
11
|
+
- `host/content/local.js` — local content source: scan, anchor hashes, describe, bounded reads.
|
|
12
|
+
- `host/remote/ssh.js` — read-only SSH transport: fixed options, ControlMaster, POSIX quoting, timeouts, output caps and capability probe.
|
|
13
|
+
- `host/remote/content.js` — remote content source: list, batch hash, describe, bounded reads, grep and change fingerprint; enforces root containment and uses metadata-only non-git fingerprints.
|
|
14
|
+
- `host/remote/consent.js` — blocking consent gate for remote content: session grant, durable workspace grant, revoke and child inheritance.
|
|
15
|
+
- `host/remote/tools.js` — `arch_remote_list/status/tree/read/grep` handlers; content reads pass the consent gate.
|
|
16
|
+
- `host/remote/state.js` — `remote-state.json`: fingerprint, pending counts, polling state and maintenance time.
|
|
17
|
+
- `host/remote/indexer.js` — fingerprint polling, change sync, backoff and auto-maintenance handoff.
|
|
18
|
+
- `host/remote/commands.js` — `/arch remote add/list/select/sync/update/grant/revoke/remove` handlers.
|
|
19
|
+
- `host/remote/maintainer.js` — consent/count/cooldown/single-flight policy and the maintenance child prompt.
|
|
20
|
+
- `host/graph.js` — graph schema/validation, store, rev, atomic writes, backup, anchor hashes.
|
|
21
|
+
- `host/memory.js` — manifest, incremental sync (local scan; remote path list + manifest-only hashes), cosmetic signatures, stale marking, dossier docs.
|
|
22
|
+
- `host/export.js` — deterministic Mermaid/SVG/Markdown exports.
|
|
23
|
+
- `host/signature.js` — shared sha256 + normalized code signature.
|
|
24
|
+
|
|
25
|
+
## Client
|
|
26
|
+
|
|
27
|
+
The client is the package-root `client.js` (hand-written, no build step):
|
|
28
|
+
|
|
29
|
+
- right-sidebar panel with a local/remote source picker and remote status line, plus a layered SVG canvas,
|
|
30
|
+
- node dragging and local positions,
|
|
31
|
+
- discussion buttons and the `subagentchat` resource,
|
|
32
|
+
- the `mermaid` chat fence renderer.
|
|
33
|
+
|
|
34
|
+
The local `docs/PLAN.md` / `docs/DESIGN.md` are design notes and are intentionally not shipped.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only content contract shared by the local filesystem and the SSH source.
|
|
3
|
+
*
|
|
4
|
+
* The graph store asks for anchor hashes; the memory store asks for a scan and
|
|
5
|
+
* per-file commit info. Remote model tools (W7) add on-demand reads through the
|
|
6
|
+
* same object.
|
|
7
|
+
*/
|
|
8
|
+
export class ContentError extends Error {
|
|
9
|
+
constructor(message, code = 'CONTENT_ERROR') {
|
|
10
|
+
super(`${code}: ${message}`)
|
|
11
|
+
this.name = 'ContentError'
|
|
12
|
+
this.code = code
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function contentFail(code, message) {
|
|
17
|
+
throw new ContentError(message, code)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export { createLocalContent } from './local.js'
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local filesystem implementation of the read-only content contract.
|
|
3
|
+
*
|
|
4
|
+
* This is the previous memory scan moved behind one object, so the graph store
|
|
5
|
+
* and the memory store no longer read workspace files directly. The behavior
|
|
6
|
+
* (ignored directories, binary/oversized rejection, sha256 and normalized
|
|
7
|
+
* signature) is intentionally identical to the pre-refactor code.
|
|
8
|
+
*/
|
|
9
|
+
import { promises as fs } from 'node:fs'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
import { hashBuffer, signatureOf } from '../signature.js'
|
|
12
|
+
import { contentFail } from './index.js'
|
|
13
|
+
|
|
14
|
+
const DEFAULT_LIMITS = Object.freeze({
|
|
15
|
+
maxFiles: 20000,
|
|
16
|
+
maxFileBytes: 256 * 1024,
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
const IGNORED_DIRS = new Set([
|
|
20
|
+
'.git', '.archmap', '.codegraph', 'node_modules', 'dist', 'build', 'out',
|
|
21
|
+
'vendor', 'coverage', '.next', '.turbo', '.cache',
|
|
22
|
+
])
|
|
23
|
+
|
|
24
|
+
const BINARY_EXTS = new Set([
|
|
25
|
+
'.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.pdf', '.zip', '.gz',
|
|
26
|
+
'.tar', '.wasm', '.node', '.mp4', '.mov', '.mp3', '.wav', '.woff', '.woff2',
|
|
27
|
+
'.ttf', '.otf', '.eot', '.class', '.so', '.dylib', '.dll', '.exe',
|
|
28
|
+
])
|
|
29
|
+
|
|
30
|
+
function looksTextual(buffer) {
|
|
31
|
+
return !buffer.includes(0)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** True when a workspace-relative path has a known binary extension. */
|
|
35
|
+
export function isBinaryPath(relative) {
|
|
36
|
+
return BINARY_EXTS.has(path.posix.extname(relative).toLowerCase())
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function relativeOf(root, abs) {
|
|
40
|
+
return path.relative(root, abs).split(path.sep).join('/')
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function createLocalContent(root, options = {}) {
|
|
44
|
+
const defaults = { ...DEFAULT_LIMITS, ...options }
|
|
45
|
+
|
|
46
|
+
function absolute(rel) {
|
|
47
|
+
if (typeof rel !== 'string' || rel.trim() === '') {
|
|
48
|
+
contentFail('INVALID_PATH', 'path must be a non-empty string')
|
|
49
|
+
}
|
|
50
|
+
if (path.isAbsolute(rel) || rel.includes('\\')) {
|
|
51
|
+
contentFail('PATH_ESCAPE', `"${rel}" must be a workspace-relative POSIX path`)
|
|
52
|
+
}
|
|
53
|
+
const segments = rel.split('/')
|
|
54
|
+
if (segments.some(segment => segment === '' || segment === '.' || segment === '..')) {
|
|
55
|
+
contentFail('PATH_ESCAPE', `"${rel}" must not contain empty, "." or ".." segments`)
|
|
56
|
+
}
|
|
57
|
+
const abs = path.resolve(root, rel)
|
|
58
|
+
const prefix = root.endsWith(path.sep) ? root : root + path.sep
|
|
59
|
+
if (!abs.startsWith(prefix)) {
|
|
60
|
+
contentFail('PATH_ESCAPE', `"${rel}" escapes the workspace`)
|
|
61
|
+
}
|
|
62
|
+
return abs
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function listTree(limit = defaults.maxFiles) {
|
|
66
|
+
const entries = []
|
|
67
|
+
let truncated = false
|
|
68
|
+
const visit = async directory => {
|
|
69
|
+
if (entries.length >= limit) {
|
|
70
|
+
truncated = true
|
|
71
|
+
return
|
|
72
|
+
}
|
|
73
|
+
let children
|
|
74
|
+
try {
|
|
75
|
+
children = await fs.readdir(directory, { withFileTypes: true })
|
|
76
|
+
} catch {
|
|
77
|
+
return
|
|
78
|
+
}
|
|
79
|
+
for (const entry of children.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
80
|
+
if (entries.length >= limit) {
|
|
81
|
+
truncated = true
|
|
82
|
+
return
|
|
83
|
+
}
|
|
84
|
+
if (entry.isSymbolicLink()) continue
|
|
85
|
+
if (IGNORED_DIRS.has(entry.name)) continue
|
|
86
|
+
const abs = path.join(directory, entry.name)
|
|
87
|
+
if (entry.isDirectory()) {
|
|
88
|
+
await visit(abs)
|
|
89
|
+
continue
|
|
90
|
+
}
|
|
91
|
+
if (!entry.isFile()) continue
|
|
92
|
+
let size
|
|
93
|
+
try {
|
|
94
|
+
size = (await fs.stat(abs)).size
|
|
95
|
+
} catch {
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
entries.push({ path: relativeOf(root, abs), size })
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
await visit(root)
|
|
102
|
+
return { entries, truncated }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function scan(limits = {}) {
|
|
106
|
+
const maxFiles = limits.maxFiles ?? defaults.maxFiles
|
|
107
|
+
const maxFileBytes = limits.maxFileBytes ?? defaults.maxFileBytes
|
|
108
|
+
const files = new Map()
|
|
109
|
+
let truncated = false
|
|
110
|
+
let skipped = 0
|
|
111
|
+
|
|
112
|
+
const visit = async directory => {
|
|
113
|
+
if (files.size >= maxFiles) {
|
|
114
|
+
truncated = true
|
|
115
|
+
return
|
|
116
|
+
}
|
|
117
|
+
let entries
|
|
118
|
+
try {
|
|
119
|
+
entries = await fs.readdir(directory, { withFileTypes: true })
|
|
120
|
+
} catch {
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
124
|
+
if (files.size >= maxFiles) {
|
|
125
|
+
truncated = true
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
if (entry.isSymbolicLink()) continue
|
|
129
|
+
if (IGNORED_DIRS.has(entry.name)) continue
|
|
130
|
+
const abs = path.join(directory, entry.name)
|
|
131
|
+
if (entry.isDirectory()) {
|
|
132
|
+
await visit(abs)
|
|
133
|
+
continue
|
|
134
|
+
}
|
|
135
|
+
if (!entry.isFile()) continue
|
|
136
|
+
if (BINARY_EXTS.has(path.extname(entry.name).toLowerCase())) continue
|
|
137
|
+
let size
|
|
138
|
+
try {
|
|
139
|
+
size = (await fs.stat(abs)).size
|
|
140
|
+
} catch {
|
|
141
|
+
continue
|
|
142
|
+
}
|
|
143
|
+
if (size > maxFileBytes) {
|
|
144
|
+
skipped += 1
|
|
145
|
+
continue
|
|
146
|
+
}
|
|
147
|
+
let buffer
|
|
148
|
+
try {
|
|
149
|
+
buffer = await fs.readFile(abs)
|
|
150
|
+
} catch {
|
|
151
|
+
continue
|
|
152
|
+
}
|
|
153
|
+
if (!looksTextual(buffer)) {
|
|
154
|
+
skipped += 1
|
|
155
|
+
continue
|
|
156
|
+
}
|
|
157
|
+
const rel = relativeOf(root, abs)
|
|
158
|
+
files.set(rel, { sha256: hashBuffer(buffer), size, signature: signatureOf(rel, buffer) })
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
await visit(root)
|
|
163
|
+
return { files, truncated, skipped }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Anchor hashes: the normalized content signature, exactly as before. */
|
|
167
|
+
async function hashMany(rels) {
|
|
168
|
+
const hashes = new Map()
|
|
169
|
+
for (const rel of rels ?? []) {
|
|
170
|
+
try {
|
|
171
|
+
const buffer = await fs.readFile(absolute(rel))
|
|
172
|
+
hashes.set(rel, signatureOf(rel, buffer))
|
|
173
|
+
} catch {
|
|
174
|
+
// Missing or unreadable anchors keep no hash; callers leave them untouched.
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return hashes
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function describe(rel, limits = {}) {
|
|
181
|
+
const maxFileBytes = limits.maxFileBytes ?? defaults.maxFileBytes
|
|
182
|
+
const abs = absolute(rel)
|
|
183
|
+
let stat
|
|
184
|
+
try {
|
|
185
|
+
stat = await fs.stat(abs)
|
|
186
|
+
} catch (error) {
|
|
187
|
+
if (error && error.code === 'ENOENT') return { kind: 'missing' }
|
|
188
|
+
contentFail('IO_ERROR', `cannot stat "${rel}": ${error.message}`)
|
|
189
|
+
}
|
|
190
|
+
if (!stat.isFile()) return { kind: 'not-file', size: stat.size }
|
|
191
|
+
if (stat.size > maxFileBytes) return { kind: 'oversized', size: stat.size }
|
|
192
|
+
const buffer = await fs.readFile(abs)
|
|
193
|
+
if (!looksTextual(buffer)) return { kind: 'binary', size: stat.size }
|
|
194
|
+
return {
|
|
195
|
+
kind: 'text',
|
|
196
|
+
size: stat.size,
|
|
197
|
+
sha256: hashBuffer(buffer),
|
|
198
|
+
signature: signatureOf(rel, buffer),
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function readText(rel, limits = {}) {
|
|
203
|
+
const maxBytes = limits.maxBytes ?? defaults.maxFileBytes
|
|
204
|
+
const abs = absolute(rel)
|
|
205
|
+
let stat
|
|
206
|
+
try {
|
|
207
|
+
stat = await fs.stat(abs)
|
|
208
|
+
} catch {
|
|
209
|
+
return null
|
|
210
|
+
}
|
|
211
|
+
if (!stat.isFile() || stat.size > maxBytes) return null
|
|
212
|
+
const buffer = await fs.readFile(abs)
|
|
213
|
+
if (!looksTextual(buffer)) return null
|
|
214
|
+
return buffer.toString('utf8')
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function readRange(rel, range = {}) {
|
|
218
|
+
const offset = Number.isInteger(range.offset) && range.offset >= 0 ? range.offset : 0
|
|
219
|
+
const length = Number.isInteger(range.length) && range.length > 0 ? range.length : defaults.maxFileBytes
|
|
220
|
+
const buffer = await fs.readFile(absolute(rel))
|
|
221
|
+
const slice = buffer.subarray(offset, offset + length)
|
|
222
|
+
return { text: slice.toString('utf8'), offset, bytes: slice.length, eof: offset + slice.length >= buffer.length }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function stat(rel) {
|
|
226
|
+
try {
|
|
227
|
+
const info = await fs.stat(absolute(rel))
|
|
228
|
+
return {
|
|
229
|
+
type: info.isFile() ? 'file' : info.isDirectory() ? 'directory' : 'other',
|
|
230
|
+
size: info.size,
|
|
231
|
+
}
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (error && error.code === 'ENOENT') return null
|
|
234
|
+
contentFail('IO_ERROR', `cannot stat "${rel}": ${error.message}`)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return {
|
|
239
|
+
kind: 'local',
|
|
240
|
+
root,
|
|
241
|
+
hashMode: 'signature',
|
|
242
|
+
listTree,
|
|
243
|
+
scan,
|
|
244
|
+
hashMany,
|
|
245
|
+
describe,
|
|
246
|
+
readText,
|
|
247
|
+
readRange,
|
|
248
|
+
stat,
|
|
249
|
+
}
|
|
250
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Architecture map — deterministic graph exports (node 10).
|
|
3
|
+
*
|
|
4
|
+
* Mermaid source, a standalone SVG and a Markdown dossier digest, all generated
|
|
5
|
+
* from `.archmap/graph.json` without a browser or a Mermaid runtime. Files land in
|
|
6
|
+
* `.archmap/export/`; the graph itself is never modified.
|
|
7
|
+
*/
|
|
8
|
+
import { promises as fs } from 'node:fs'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { randomBytes } from 'node:crypto'
|
|
11
|
+
import { resolveWorkspace } from './workspace.js'
|
|
12
|
+
|
|
13
|
+
const FORMATS = Object.freeze({
|
|
14
|
+
mermaid: { file: 'architecture.mmd', label: 'Mermaid' },
|
|
15
|
+
svg: { file: 'architecture.svg', label: 'SVG' },
|
|
16
|
+
markdown: { file: 'architecture.md', label: 'Markdown' },
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
const NODE_W = 210
|
|
20
|
+
const NODE_H = 84
|
|
21
|
+
const GAP_X = 28
|
|
22
|
+
const GAP_Y = 30
|
|
23
|
+
const PAD = 28
|
|
24
|
+
|
|
25
|
+
function fail(code, message) {
|
|
26
|
+
const error = new Error(`${code}: ${message}`)
|
|
27
|
+
error.code = code
|
|
28
|
+
throw error
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function xml(value) {
|
|
32
|
+
return String(value ?? '')
|
|
33
|
+
.replace(/&/g, '&')
|
|
34
|
+
.replace(/</g, '<')
|
|
35
|
+
.replace(/>/g, '>')
|
|
36
|
+
.replace(/"/g, '"')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function mermaidLabel(value) {
|
|
40
|
+
return String(value ?? '')
|
|
41
|
+
.replace(/"/g, "'")
|
|
42
|
+
.replace(/\r?\n/g, '<br/>')
|
|
43
|
+
.replace(/</g, '<')
|
|
44
|
+
.replace(/>/g, '>')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function directionOf(graph) {
|
|
48
|
+
const direction = String(graph?.layout?.direction ?? 'LR').toUpperCase()
|
|
49
|
+
return direction === 'TB' || direction === 'TD' ? 'TD' : direction === 'RL' ? 'RL' : direction === 'BT' ? 'BT' : 'LR'
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function mermaidSource(graph) {
|
|
53
|
+
const lines = [`flowchart ${directionOf(graph)}`]
|
|
54
|
+
const groups = Array.isArray(graph.groups) ? graph.groups : []
|
|
55
|
+
const nodes = Array.isArray(graph.nodes) ? graph.nodes : []
|
|
56
|
+
const edges = Array.isArray(graph.edges) ? graph.edges : []
|
|
57
|
+
const groupIds = new Set(groups.map(group => group.id))
|
|
58
|
+
const nodeLine = node => {
|
|
59
|
+
const parts = [node.kind ?? 'module']
|
|
60
|
+
if (node.group) parts.push(node.group)
|
|
61
|
+
if (node.status) parts.push(node.status)
|
|
62
|
+
return ` ${node.id}["${mermaidLabel(node.title ?? node.id)}<br/><small>${mermaidLabel(parts.join(' · '))}</small>"]`
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
for (const group of groups) {
|
|
66
|
+
lines.push(` subgraph ${group.id}["${mermaidLabel(group.title ?? group.id)}"]`)
|
|
67
|
+
for (const node of nodes.filter(item => item.group === group.id)) lines.push(nodeLine(node))
|
|
68
|
+
lines.push(' end')
|
|
69
|
+
}
|
|
70
|
+
for (const node of nodes.filter(item => !item.group || !groupIds.has(item.group))) lines.push(nodeLine(node))
|
|
71
|
+
|
|
72
|
+
for (const edge of edges) {
|
|
73
|
+
const label = String(edge.label ?? '').trim()
|
|
74
|
+
const kind = String(edge.kind ?? '').trim()
|
|
75
|
+
const text = label || kind
|
|
76
|
+
lines.push(text
|
|
77
|
+
? ` ${edge.from} -->|"${mermaidLabel(text)}"| ${edge.to}`
|
|
78
|
+
: ` ${edge.from} --> ${edge.to}`)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const stale = nodes.filter(node => node.status === 'stale').map(node => node.id)
|
|
82
|
+
const proposed = nodes.filter(node => node.status === 'proposed').map(node => node.id)
|
|
83
|
+
if (stale.length > 0) {
|
|
84
|
+
lines.push(' classDef stale fill:#f6e7c1,stroke:#c58a1a,color:#6b4a00;')
|
|
85
|
+
lines.push(` class ${stale.join(',')} stale;`)
|
|
86
|
+
}
|
|
87
|
+
if (proposed.length > 0) {
|
|
88
|
+
lines.push(' classDef proposed fill:#fdecec,stroke:#d9534f,color:#6b1f1f;')
|
|
89
|
+
lines.push(` class ${proposed.join(',')} proposed;`)
|
|
90
|
+
}
|
|
91
|
+
return lines.join('\n') + '\n'
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function markdownSource(graph) {
|
|
95
|
+
const nodes = Array.isArray(graph.nodes) ? graph.nodes : []
|
|
96
|
+
const edges = Array.isArray(graph.edges) ? graph.edges : []
|
|
97
|
+
const groups = Array.isArray(graph.groups) ? graph.groups : []
|
|
98
|
+
const lines = [
|
|
99
|
+
'# Architecture map',
|
|
100
|
+
'',
|
|
101
|
+
`rev ${graph.rev} · ${nodes.length} nodes · ${edges.length} edges · ${groups.length} groups`,
|
|
102
|
+
'',
|
|
103
|
+
]
|
|
104
|
+
if (groups.length > 0) {
|
|
105
|
+
lines.push('## Groups', '')
|
|
106
|
+
for (const group of groups) lines.push(`- **${group.id}** — ${group.title ?? group.id}`)
|
|
107
|
+
lines.push('')
|
|
108
|
+
}
|
|
109
|
+
lines.push('## Nodes', '')
|
|
110
|
+
for (const node of nodes) {
|
|
111
|
+
lines.push(`### ${node.id} — ${node.title ?? node.id}`, '')
|
|
112
|
+
lines.push(`- kind: \`${node.kind ?? 'module'}\``)
|
|
113
|
+
lines.push(`- status: \`${node.status ?? 'fresh'}\``)
|
|
114
|
+
if (node.group) lines.push(`- group: \`${node.group}\``)
|
|
115
|
+
if (node.summary) lines.push(`- summary: ${node.summary}`)
|
|
116
|
+
if (Array.isArray(node.anchors) && node.anchors.length > 0) {
|
|
117
|
+
lines.push(`- anchors: ${node.anchors.map(anchor => `\`${anchor.path}${anchor.symbol ? `#${anchor.symbol}` : ''}\``).join(', ')}`)
|
|
118
|
+
}
|
|
119
|
+
lines.push('')
|
|
120
|
+
}
|
|
121
|
+
lines.push('## Edges', '')
|
|
122
|
+
if (edges.length === 0) lines.push('(none)')
|
|
123
|
+
for (const edge of edges) {
|
|
124
|
+
const label = edge.label ? ` — ${edge.label}` : ''
|
|
125
|
+
const kind = edge.kind ? ` (${edge.kind})` : ''
|
|
126
|
+
lines.push(`- \`${edge.id}\`: ${edge.from} → ${edge.to}${label}${kind}`)
|
|
127
|
+
}
|
|
128
|
+
return lines.join('\n') + '\n'
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function gridLayout(graph) {
|
|
132
|
+
const nodes = Array.isArray(graph.nodes) ? graph.nodes : []
|
|
133
|
+
const cols = Math.max(1, Math.min(3, Math.ceil(Math.sqrt(Math.max(1, nodes.length)))))
|
|
134
|
+
const rows = Math.max(1, Math.ceil(nodes.length / cols))
|
|
135
|
+
const positions = new Map()
|
|
136
|
+
nodes.forEach((node, index) => {
|
|
137
|
+
const col = index % cols
|
|
138
|
+
const row = Math.floor(index / cols)
|
|
139
|
+
positions.set(node.id, {
|
|
140
|
+
x: PAD + col * (NODE_W + GAP_X),
|
|
141
|
+
y: PAD + row * (NODE_H + GAP_Y),
|
|
142
|
+
w: NODE_W,
|
|
143
|
+
h: NODE_H,
|
|
144
|
+
})
|
|
145
|
+
})
|
|
146
|
+
const width = PAD * 2 + cols * NODE_W + (cols - 1) * GAP_X
|
|
147
|
+
const height = PAD * 2 + rows * NODE_H + (rows - 1) * GAP_Y
|
|
148
|
+
return { positions, width, height }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function svgSource(graph) {
|
|
152
|
+
const { positions, width, height } = gridLayout(graph)
|
|
153
|
+
const edges = Array.isArray(graph.edges) ? graph.edges : []
|
|
154
|
+
const nodes = Array.isArray(graph.nodes) ? graph.nodes : []
|
|
155
|
+
const palette = {
|
|
156
|
+
fresh: ['#eef4ff', '#6f93c9', '#22344f'],
|
|
157
|
+
stale: ['#f6e7c1', '#c58a1a', '#5d4300'],
|
|
158
|
+
proposed: ['#fdecec', '#d9534f', '#6b1f1f'],
|
|
159
|
+
}
|
|
160
|
+
const lines = [
|
|
161
|
+
`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="Architecture map">`,
|
|
162
|
+
' <defs>',
|
|
163
|
+
' <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">',
|
|
164
|
+
' <path d="M 0 0 L 10 5 L 0 10 z" fill="#7b8794"/>',
|
|
165
|
+
' </marker>',
|
|
166
|
+
' </defs>',
|
|
167
|
+
` <rect width="${width}" height="${height}" fill="#ffffff"/>`,
|
|
168
|
+
]
|
|
169
|
+
for (const edge of edges) {
|
|
170
|
+
const from = positions.get(edge.from)
|
|
171
|
+
const to = positions.get(edge.to)
|
|
172
|
+
if (!from || !to) continue
|
|
173
|
+
const x1 = from.x + from.w
|
|
174
|
+
const y1 = from.y + from.h / 2
|
|
175
|
+
const x2 = to.x
|
|
176
|
+
const y2 = to.y + to.h / 2
|
|
177
|
+
lines.push(` <line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="#7b8794" stroke-width="1.4" stroke-opacity="0.7" marker-end="url(#arrow)"/>`)
|
|
178
|
+
if (edge.label) {
|
|
179
|
+
lines.push(` <text x="${(x1 + x2) / 2}" y="${(y1 + y2) / 2 - 5}" text-anchor="middle" font-family="sans-serif" font-size="10" fill="#52606d">${xml(edge.label)}</text>`)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
for (const node of nodes) {
|
|
183
|
+
const box = positions.get(node.id)
|
|
184
|
+
if (!box) continue
|
|
185
|
+
const [fill, stroke, ink] = palette[node.status] ?? palette.fresh
|
|
186
|
+
lines.push(` <g id="${xml(node.id)}">`)
|
|
187
|
+
lines.push(` <rect x="${box.x}" y="${box.y}" width="${box.w}" height="${box.h}" rx="8" fill="${fill}" stroke="${stroke}" stroke-width="1.2"/>`)
|
|
188
|
+
lines.push(` <text x="${box.x + 12}" y="${box.y + 26}" font-family="sans-serif" font-size="13" font-weight="600" fill="${ink}">${xml(node.title ?? node.id)}</text>`)
|
|
189
|
+
lines.push(` <text x="${box.x + 12}" y="${box.y + 46}" font-family="sans-serif" font-size="10" fill="${ink}" opacity="0.7">${xml(node.kind ?? 'module')}${node.group ? ` · ${xml(node.group)}` : ''}${node.status ? ` · ${xml(node.status)}` : ''}</text>`)
|
|
190
|
+
lines.push(` <text x="${box.x + 12}" y="${box.y + 64}" font-family="ui-monospace, monospace" font-size="9" fill="${ink}" opacity="0.55">${xml(node.id)}</text>`)
|
|
191
|
+
lines.push(' </g>')
|
|
192
|
+
}
|
|
193
|
+
lines.push('</svg>')
|
|
194
|
+
return lines.join('\n') + '\n'
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function createExporter(deps = {}) {
|
|
198
|
+
const resolve = typeof deps.resolve === 'function'
|
|
199
|
+
? deps.resolve
|
|
200
|
+
: (rawWorkspace, context) => resolveWorkspace(rawWorkspace, context, { dir: deps.dir ?? '.archmap', ssh: deps.ssh })
|
|
201
|
+
|
|
202
|
+
async function run(rawWorkspace, input = {}, context) {
|
|
203
|
+
if (typeof deps.readGraph !== 'function') fail('UNAVAILABLE', 'graph reader is not available')
|
|
204
|
+
const format = String(input.format ?? '')
|
|
205
|
+
const spec = FORMATS[format]
|
|
206
|
+
if (!spec) fail('INVALID_FORMAT', 'format must be mermaid, svg or markdown')
|
|
207
|
+
const ws = await resolve(rawWorkspace, context)
|
|
208
|
+
const graph = await deps.readGraph(ws, context)
|
|
209
|
+
let content
|
|
210
|
+
if (format === 'mermaid') content = mermaidSource(graph)
|
|
211
|
+
else if (format === 'svg') content = svgSource(graph)
|
|
212
|
+
else content = markdownSource(graph)
|
|
213
|
+
const dir = path.join(ws.stateDir, 'export')
|
|
214
|
+
await fs.mkdir(dir, { recursive: true })
|
|
215
|
+
const file = path.join(dir, spec.file)
|
|
216
|
+
const temp = `${file}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`
|
|
217
|
+
await fs.writeFile(temp, content, 'utf8')
|
|
218
|
+
await fs.rename(temp, file)
|
|
219
|
+
const relative = path.relative(ws.pathBase, file).split(path.sep).join('/')
|
|
220
|
+
return {
|
|
221
|
+
text: `exported ${spec.label} to ${relative} (${Buffer.byteLength(content, 'utf8')} bytes)`,
|
|
222
|
+
path: relative,
|
|
223
|
+
bytes: Buffer.byteLength(content, 'utf8'),
|
|
224
|
+
format,
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return { export: run, formats: Object.keys(FORMATS) }
|
|
228
|
+
}
|