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,707 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Architecture map — graph store (node 2).
|
|
3
|
+
*
|
|
4
|
+
* A workspace owns one `graph.json` with a monotonically increasing `rev`.
|
|
5
|
+
* Reads are bounded; writes are validated, serialized per workspace, backed up
|
|
6
|
+
* before replacement, and committed with a temporary file + rename.
|
|
7
|
+
*
|
|
8
|
+
* Plain ESM; uses Node built-ins only so the Host half needs no runtime
|
|
9
|
+
* dependency beyond DSH itself.
|
|
10
|
+
*/
|
|
11
|
+
import { promises as fs } from 'node:fs'
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
import { randomBytes } from 'node:crypto'
|
|
14
|
+
import { normalizeDataDir, resolveWorkspace } from './workspace.js'
|
|
15
|
+
|
|
16
|
+
export const GRAPH_SCHEMA = 1
|
|
17
|
+
|
|
18
|
+
const ID_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/
|
|
19
|
+
const NODE_KINDS = new Set(['entry', 'module', 'service', 'store', 'external', 'concept'])
|
|
20
|
+
const EDGE_KINDS = new Set(['call', 'data', 'dependency', 'containment'])
|
|
21
|
+
const STATUSES = new Set(['fresh', 'stale', 'proposed'])
|
|
22
|
+
|
|
23
|
+
const NODE_FIELDS = new Set(['id', 'title', 'kind', 'group', 'summary', 'anchors', 'status', 'style', 'notes'])
|
|
24
|
+
const NODE_PATCH_FIELDS = new Set(['title', 'kind', 'group', 'summary', 'anchors', 'status', 'style', 'notes'])
|
|
25
|
+
const EDGE_FIELDS = new Set(['id', 'from', 'to', 'label', 'kind', 'status'])
|
|
26
|
+
const EDGE_PATCH_FIELDS = new Set(['from', 'to', 'label', 'kind', 'status'])
|
|
27
|
+
const GROUP_FIELDS = new Set(['id', 'title', 'kind'])
|
|
28
|
+
|
|
29
|
+
const OP_FIELDS = {
|
|
30
|
+
add_node: new Set(['op', 'node']),
|
|
31
|
+
update_node: new Set(['op', 'id', 'patch']),
|
|
32
|
+
remove_node: new Set(['op', 'id', 'cascade']),
|
|
33
|
+
add_edge: new Set(['op', 'edge']),
|
|
34
|
+
update_edge: new Set(['op', 'id', 'patch']),
|
|
35
|
+
remove_edge: new Set(['op', 'id']),
|
|
36
|
+
set_group: new Set(['op', 'group']),
|
|
37
|
+
remove_group: new Set(['op', 'id']),
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const DEFAULTS = Object.freeze({
|
|
41
|
+
dir: '.archmap',
|
|
42
|
+
maxNodes: 400,
|
|
43
|
+
maxEdges: 1200,
|
|
44
|
+
maxGroups: 100,
|
|
45
|
+
maxSummary: 500,
|
|
46
|
+
maxAnchors: 20,
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
const locks = new Map()
|
|
50
|
+
|
|
51
|
+
/** Throw a coded error the tool layer can surface verbatim to the model. */
|
|
52
|
+
function fail(code, message) {
|
|
53
|
+
const error = new Error(`${code}: ${message}`)
|
|
54
|
+
error.code = code
|
|
55
|
+
throw error
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isPlainObject(value) {
|
|
59
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function assertId(value, where) {
|
|
63
|
+
if (typeof value !== 'string' || !ID_PATTERN.test(value)) {
|
|
64
|
+
fail('INVALID_GRAPH', `${where} must match ${ID_PATTERN}`)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function assertText(value, where, max) {
|
|
69
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
70
|
+
fail('INVALID_GRAPH', `${where} must be a non-empty string`)
|
|
71
|
+
}
|
|
72
|
+
if (value.length > max) {
|
|
73
|
+
fail('LIMIT_EXCEEDED', `${where} is ${value.length} characters; the limit is ${max}`)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function assertKnownKeys(value, allowed, where) {
|
|
78
|
+
for (const key of Object.keys(value)) {
|
|
79
|
+
if (!allowed.has(key)) {
|
|
80
|
+
fail('INVALID_GRAPH', `${where}.${key} is not a recognized field (expected: ${[...allowed].join(', ')})`)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function assertRelativeAnchor(anchor, where) {
|
|
86
|
+
if (!isPlainObject(anchor)) fail('INVALID_GRAPH', `${where} must be an object { path, symbol?, hash? }`)
|
|
87
|
+
if (typeof anchor.path !== 'string' || anchor.path.trim() === '') {
|
|
88
|
+
fail('INVALID_GRAPH', `${where}.path must be a non-empty string`)
|
|
89
|
+
}
|
|
90
|
+
if (path.isAbsolute(anchor.path) || anchor.path.includes('\\')) {
|
|
91
|
+
fail('PATH_ESCAPE', `${where}.path must be a workspace-relative POSIX path`)
|
|
92
|
+
}
|
|
93
|
+
const segments = anchor.path.split('/')
|
|
94
|
+
if (segments.some(segment => segment === '' || segment === '.' || segment === '..')) {
|
|
95
|
+
fail('PATH_ESCAPE', `${where}.path must not contain empty, "." or ".." segments`)
|
|
96
|
+
}
|
|
97
|
+
if (anchor.symbol !== undefined && typeof anchor.symbol !== 'string') {
|
|
98
|
+
fail('INVALID_GRAPH', `${where}.symbol must be a string when present`)
|
|
99
|
+
}
|
|
100
|
+
if (anchor.hash !== undefined && typeof anchor.hash !== 'string') {
|
|
101
|
+
fail('INVALID_GRAPH', `${where}.hash must be a string when present`)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function normalizeNode(raw, where = 'node') {
|
|
106
|
+
if (!isPlainObject(raw)) fail('INVALID_GRAPH', `${where} must be an object; add_node expects { op: "add_node", node: { id, title, ... } }`)
|
|
107
|
+
assertKnownKeys(raw, NODE_FIELDS, where)
|
|
108
|
+
return {
|
|
109
|
+
id: raw.id,
|
|
110
|
+
title: raw.title,
|
|
111
|
+
kind: raw.kind ?? 'module',
|
|
112
|
+
...(raw.group === undefined ? {} : { group: raw.group }),
|
|
113
|
+
...(raw.summary === undefined ? {} : { summary: raw.summary }),
|
|
114
|
+
anchors: raw.anchors ?? [],
|
|
115
|
+
status: raw.status ?? 'fresh',
|
|
116
|
+
...(raw.style === undefined ? {} : { style: raw.style }),
|
|
117
|
+
...(raw.notes === undefined ? {} : { notes: raw.notes }),
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function normalizeEdge(raw, where = 'edge') {
|
|
122
|
+
if (!isPlainObject(raw)) fail('INVALID_GRAPH', `${where} must be an object; add_edge expects { op: "add_edge", edge: { id, from, to, ... } }`)
|
|
123
|
+
assertKnownKeys(raw, EDGE_FIELDS, where)
|
|
124
|
+
return {
|
|
125
|
+
id: raw.id,
|
|
126
|
+
from: raw.from,
|
|
127
|
+
to: raw.to,
|
|
128
|
+
...(raw.label === undefined ? {} : { label: raw.label }),
|
|
129
|
+
kind: raw.kind ?? 'dependency',
|
|
130
|
+
status: raw.status ?? 'fresh',
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function normalizeGroup(raw, where = 'group') {
|
|
135
|
+
if (!isPlainObject(raw)) fail('INVALID_GRAPH', `${where} must be an object; set_group expects { op: "set_group", group: { id, title } }`)
|
|
136
|
+
assertKnownKeys(raw, GROUP_FIELDS, where)
|
|
137
|
+
return {
|
|
138
|
+
id: raw.id,
|
|
139
|
+
title: raw.title,
|
|
140
|
+
...(raw.kind === undefined ? {} : { kind: raw.kind }),
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function emptyGraph() {
|
|
145
|
+
return {
|
|
146
|
+
schema: GRAPH_SCHEMA,
|
|
147
|
+
rev: 0,
|
|
148
|
+
updatedAt: null,
|
|
149
|
+
layout: { mode: 'layered', direction: 'LR' },
|
|
150
|
+
groups: [],
|
|
151
|
+
nodes: [],
|
|
152
|
+
edges: [],
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Validate a complete graph and return it unchanged. */
|
|
157
|
+
export function validateGraph(graph, limits = DEFAULTS) {
|
|
158
|
+
if (!isPlainObject(graph)) fail('INVALID_GRAPH', 'graph must be an object')
|
|
159
|
+
if (graph.schema !== GRAPH_SCHEMA) {
|
|
160
|
+
fail('INVALID_GRAPH', `graph.schema must be ${GRAPH_SCHEMA}`)
|
|
161
|
+
}
|
|
162
|
+
if (!Number.isInteger(graph.rev) || graph.rev < 0) {
|
|
163
|
+
fail('INVALID_GRAPH', 'graph.rev must be a non-negative integer')
|
|
164
|
+
}
|
|
165
|
+
if (!Array.isArray(graph.groups) || !Array.isArray(graph.nodes) || !Array.isArray(graph.edges)) {
|
|
166
|
+
fail('INVALID_GRAPH', 'graph.groups, graph.nodes and graph.edges must be arrays')
|
|
167
|
+
}
|
|
168
|
+
if (graph.nodes.length > limits.maxNodes) {
|
|
169
|
+
fail('LIMIT_EXCEEDED', `graph has ${graph.nodes.length} nodes; the limit is ${limits.maxNodes}`)
|
|
170
|
+
}
|
|
171
|
+
if (graph.edges.length > limits.maxEdges) {
|
|
172
|
+
fail('LIMIT_EXCEEDED', `graph has ${graph.edges.length} edges; the limit is ${limits.maxEdges}`)
|
|
173
|
+
}
|
|
174
|
+
if (graph.groups.length > limits.maxGroups) {
|
|
175
|
+
fail('LIMIT_EXCEEDED', `graph has ${graph.groups.length} groups; the limit is ${limits.maxGroups}`)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const ids = new Set()
|
|
179
|
+
const groupIds = new Set()
|
|
180
|
+
for (const group of graph.groups) {
|
|
181
|
+
if (!isPlainObject(group)) fail('INVALID_GRAPH', 'group must be an object')
|
|
182
|
+
assertId(group.id, 'group.id')
|
|
183
|
+
if (ids.has(group.id)) fail('INVALID_GRAPH', `duplicate id "${group.id}"`)
|
|
184
|
+
ids.add(group.id)
|
|
185
|
+
groupIds.add(group.id)
|
|
186
|
+
assertText(group.title, `group ${group.id}.title`, 200)
|
|
187
|
+
if (group.kind !== undefined && typeof group.kind !== 'string') {
|
|
188
|
+
fail('INVALID_GRAPH', `group ${group.id}.kind must be a string when present`)
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const nodeIds = new Set()
|
|
193
|
+
for (const node of graph.nodes) {
|
|
194
|
+
if (!isPlainObject(node)) fail('INVALID_GRAPH', 'node must be an object')
|
|
195
|
+
assertId(node.id, 'node.id')
|
|
196
|
+
if (ids.has(node.id)) fail('INVALID_GRAPH', `duplicate id "${node.id}"`)
|
|
197
|
+
ids.add(node.id)
|
|
198
|
+
nodeIds.add(node.id)
|
|
199
|
+
assertText(node.title, `node ${node.id}.title`, 200)
|
|
200
|
+
if (!NODE_KINDS.has(node.kind)) {
|
|
201
|
+
fail('INVALID_GRAPH', `node ${node.id}.kind must be one of ${[...NODE_KINDS].join(', ')}`)
|
|
202
|
+
}
|
|
203
|
+
if (node.group !== undefined && !groupIds.has(node.group)) {
|
|
204
|
+
fail('INVALID_GRAPH', `node ${node.id}.group "${node.group}" does not exist`)
|
|
205
|
+
}
|
|
206
|
+
if (node.summary !== undefined) {
|
|
207
|
+
if (typeof node.summary !== 'string') fail('INVALID_GRAPH', `node ${node.id}.summary must be a string`)
|
|
208
|
+
if (node.summary.length > limits.maxSummary) {
|
|
209
|
+
fail('LIMIT_EXCEEDED', `node ${node.id}.summary is ${node.summary.length} characters; the limit is ${limits.maxSummary}`)
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (!Array.isArray(node.anchors)) fail('INVALID_GRAPH', `node ${node.id}.anchors must be an array`)
|
|
213
|
+
if (node.anchors.length > limits.maxAnchors) {
|
|
214
|
+
fail('LIMIT_EXCEEDED', `node ${node.id} has ${node.anchors.length} anchors; the limit is ${limits.maxAnchors}`)
|
|
215
|
+
}
|
|
216
|
+
for (const [index, anchor] of node.anchors.entries()) {
|
|
217
|
+
assertRelativeAnchor(anchor, `node ${node.id}.anchors[${index}]`)
|
|
218
|
+
}
|
|
219
|
+
if (!STATUSES.has(node.status)) {
|
|
220
|
+
fail('INVALID_GRAPH', `node ${node.id}.status must be one of ${[...STATUSES].join(', ')}`)
|
|
221
|
+
}
|
|
222
|
+
if (node.style !== undefined && !isPlainObject(node.style)) {
|
|
223
|
+
fail('INVALID_GRAPH', `node ${node.id}.style must be an object when present`)
|
|
224
|
+
}
|
|
225
|
+
if (node.notes !== undefined && typeof node.notes !== 'string') {
|
|
226
|
+
fail('INVALID_GRAPH', `node ${node.id}.notes must be a string when present`)
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
for (const edge of graph.edges) {
|
|
231
|
+
if (!isPlainObject(edge)) fail('INVALID_GRAPH', 'edge must be an object')
|
|
232
|
+
assertId(edge.id, 'edge.id')
|
|
233
|
+
if (ids.has(edge.id)) fail('INVALID_GRAPH', `duplicate id "${edge.id}"`)
|
|
234
|
+
ids.add(edge.id)
|
|
235
|
+
if (!nodeIds.has(edge.from)) fail('INVALID_GRAPH', `edge ${edge.id}.from "${edge.from}" does not exist`)
|
|
236
|
+
if (!nodeIds.has(edge.to)) fail('INVALID_GRAPH', `edge ${edge.id}.to "${edge.to}" does not exist`)
|
|
237
|
+
if (edge.from === edge.to && edge.kind !== 'containment') {
|
|
238
|
+
fail('INVALID_GRAPH', `edge ${edge.id} is a self-loop; only containment may self-reference`)
|
|
239
|
+
}
|
|
240
|
+
if (!EDGE_KINDS.has(edge.kind)) {
|
|
241
|
+
fail('INVALID_GRAPH', `edge ${edge.id}.kind must be one of ${[...EDGE_KINDS].join(', ')}`)
|
|
242
|
+
}
|
|
243
|
+
if (edge.label !== undefined) {
|
|
244
|
+
if (typeof edge.label !== 'string') fail('INVALID_GRAPH', `edge ${edge.id}.label must be a string`)
|
|
245
|
+
if (edge.label.length > 200) fail('LIMIT_EXCEEDED', `edge ${edge.id}.label is too long`)
|
|
246
|
+
}
|
|
247
|
+
if (!STATUSES.has(edge.status)) {
|
|
248
|
+
fail('INVALID_GRAPH', `edge ${edge.id}.status must be one of ${[...STATUSES].join(', ')}`)
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return graph
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Apply ordered patch operations to a clone of the graph. */
|
|
256
|
+
export function applyOps(graph, ops, limits = DEFAULTS) {
|
|
257
|
+
if (!Array.isArray(ops) || ops.length === 0) {
|
|
258
|
+
fail('INVALID_OP', 'ops must be a non-empty array')
|
|
259
|
+
}
|
|
260
|
+
const draft = structuredClone(graph)
|
|
261
|
+
const findNode = id => draft.nodes.find(node => node.id === id)
|
|
262
|
+
const findEdge = id => draft.edges.find(edge => edge.id === id)
|
|
263
|
+
const findGroup = id => draft.groups.find(group => group.id === id)
|
|
264
|
+
|
|
265
|
+
for (const [index, op] of ops.entries()) {
|
|
266
|
+
const where = `ops[${index}]`
|
|
267
|
+
if (!isPlainObject(op) || typeof op.op !== 'string') {
|
|
268
|
+
fail('INVALID_OP', `${where} must be an object with an "op" string`)
|
|
269
|
+
}
|
|
270
|
+
const allowedKeys = OP_FIELDS[op.op]
|
|
271
|
+
if (allowedKeys === undefined) {
|
|
272
|
+
fail('INVALID_OP', `${where}: unknown op "${op.op}"`)
|
|
273
|
+
}
|
|
274
|
+
assertKnownKeys(op, allowedKeys, where)
|
|
275
|
+
switch (op.op) {
|
|
276
|
+
case 'add_node': {
|
|
277
|
+
const node = normalizeNode(op.node, `${where}.node`)
|
|
278
|
+
if (findNode(node.id) || findEdge(node.id) || findGroup(node.id)) {
|
|
279
|
+
fail('INVALID_OP', `${where}: id "${node.id}" already exists`)
|
|
280
|
+
}
|
|
281
|
+
draft.nodes.push(node)
|
|
282
|
+
break
|
|
283
|
+
}
|
|
284
|
+
case 'update_node': {
|
|
285
|
+
if (op.id === undefined) fail('INVALID_OP', `${where}.id is required for update_node; expected { op: "update_node", id, patch: {...} }`)
|
|
286
|
+
assertId(op.id, `${where}.id`)
|
|
287
|
+
const node = findNode(op.id)
|
|
288
|
+
if (!node) fail('NOT_FOUND', `${where}: node "${op.id}" does not exist`)
|
|
289
|
+
if (!isPlainObject(op.patch)) {
|
|
290
|
+
fail('INVALID_OP', `${where}.patch must be an object; expected { op: "update_node", id: "${op.id}", patch: {...} }`)
|
|
291
|
+
}
|
|
292
|
+
assertKnownKeys(op.patch, NODE_PATCH_FIELDS, `${where}.patch`)
|
|
293
|
+
Object.assign(node, op.patch)
|
|
294
|
+
break
|
|
295
|
+
}
|
|
296
|
+
case 'remove_node': {
|
|
297
|
+
assertId(op.id, `${where}.id`)
|
|
298
|
+
const index = draft.nodes.findIndex(node => node.id === op.id)
|
|
299
|
+
if (index < 0) fail('NOT_FOUND', `${where}: node "${op.id}" does not exist`)
|
|
300
|
+
const related = draft.edges.filter(edge => edge.from === op.id || edge.to === op.id)
|
|
301
|
+
if (related.length > 0 && op.cascade !== true) {
|
|
302
|
+
fail('INVALID_OP', `${where}: node "${op.id}" still has ${related.length} edge(s); pass cascade: true`)
|
|
303
|
+
}
|
|
304
|
+
draft.edges = draft.edges.filter(edge => edge.from !== op.id && edge.to !== op.id)
|
|
305
|
+
draft.nodes.splice(index, 1)
|
|
306
|
+
break
|
|
307
|
+
}
|
|
308
|
+
case 'add_edge': {
|
|
309
|
+
const edge = normalizeEdge(op.edge, `${where}.edge`)
|
|
310
|
+
if (findNode(edge.id) || findEdge(edge.id) || findGroup(edge.id)) {
|
|
311
|
+
fail('INVALID_OP', `${where}: id "${edge.id}" already exists`)
|
|
312
|
+
}
|
|
313
|
+
draft.edges.push(edge)
|
|
314
|
+
break
|
|
315
|
+
}
|
|
316
|
+
case 'update_edge': {
|
|
317
|
+
if (op.id === undefined) fail('INVALID_OP', `${where}.id is required for update_edge; expected { op: "update_edge", id, patch: {...} }`)
|
|
318
|
+
assertId(op.id, `${where}.id`)
|
|
319
|
+
const edge = findEdge(op.id)
|
|
320
|
+
if (!edge) fail('NOT_FOUND', `${where}: edge "${op.id}" does not exist`)
|
|
321
|
+
if (!isPlainObject(op.patch)) {
|
|
322
|
+
fail('INVALID_OP', `${where}.patch must be an object; expected { op: "update_edge", id: "${op.id}", patch: {...} }`)
|
|
323
|
+
}
|
|
324
|
+
assertKnownKeys(op.patch, EDGE_PATCH_FIELDS, `${where}.patch`)
|
|
325
|
+
Object.assign(edge, op.patch)
|
|
326
|
+
break
|
|
327
|
+
}
|
|
328
|
+
case 'remove_edge': {
|
|
329
|
+
assertId(op.id, `${where}.id`)
|
|
330
|
+
const index = draft.edges.findIndex(edge => edge.id === op.id)
|
|
331
|
+
if (index < 0) fail('NOT_FOUND', `${where}: edge "${op.id}" does not exist`)
|
|
332
|
+
draft.edges.splice(index, 1)
|
|
333
|
+
break
|
|
334
|
+
}
|
|
335
|
+
case 'set_group': {
|
|
336
|
+
const group = normalizeGroup(op.group, `${where}.group`)
|
|
337
|
+
const existing = findGroup(group.id)
|
|
338
|
+
if (existing) Object.assign(existing, group)
|
|
339
|
+
else draft.groups.push(group)
|
|
340
|
+
break
|
|
341
|
+
}
|
|
342
|
+
case 'remove_group': {
|
|
343
|
+
assertId(op.id, `${where}.id`)
|
|
344
|
+
const index = draft.groups.findIndex(group => group.id === op.id)
|
|
345
|
+
if (index < 0) fail('NOT_FOUND', `${where}: group "${op.id}" does not exist`)
|
|
346
|
+
const members = draft.nodes.filter(node => node.group === op.id)
|
|
347
|
+
if (members.length > 0) {
|
|
348
|
+
fail('INVALID_OP', `${where}: group "${op.id}" still has ${members.length} node(s)`)
|
|
349
|
+
}
|
|
350
|
+
draft.groups.splice(index, 1)
|
|
351
|
+
break
|
|
352
|
+
}
|
|
353
|
+
default:
|
|
354
|
+
fail('INVALID_OP', `${where}: unknown op "${op.op}"`)
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
validateGraph(draft, limits)
|
|
358
|
+
return draft
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function diffGraphs(before, after) {
|
|
362
|
+
const changed = (beforeItems, afterItems) => {
|
|
363
|
+
const beforeMap = new Map(beforeItems.map(item => [item.id, JSON.stringify(item)]))
|
|
364
|
+
const afterMap = new Map(afterItems.map(item => [item.id, item]))
|
|
365
|
+
const added = []
|
|
366
|
+
const updated = []
|
|
367
|
+
const removed = []
|
|
368
|
+
for (const [id, value] of afterMap) {
|
|
369
|
+
if (!beforeMap.has(id)) added.push(id)
|
|
370
|
+
else if (beforeMap.get(id) !== JSON.stringify(value)) updated.push(id)
|
|
371
|
+
}
|
|
372
|
+
for (const id of beforeMap.keys()) {
|
|
373
|
+
if (!afterMap.has(id)) removed.push(id)
|
|
374
|
+
}
|
|
375
|
+
return { added, updated, removed }
|
|
376
|
+
}
|
|
377
|
+
return {
|
|
378
|
+
nodes: changed(before.nodes, after.nodes),
|
|
379
|
+
edges: changed(before.edges, after.edges),
|
|
380
|
+
groups: changed(before.groups, after.groups),
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function countChanges(diff) {
|
|
385
|
+
return Object.values(diff).reduce((total, part) => total + part.added.length + part.updated.length + part.removed.length, 0)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function formatCounts(counts) {
|
|
389
|
+
return `${counts.nodes} node${counts.nodes === 1 ? '' : 's'} · ${counts.edges} edge${counts.edges === 1 ? '' : 's'} · ${counts.groups} group${counts.groups === 1 ? '' : 's'}`
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function graphCounts(graph) {
|
|
393
|
+
return { nodes: graph.nodes.length, edges: graph.edges.length, groups: graph.groups.length }
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function clip(text, max) {
|
|
397
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function findTarget(graph, target) {
|
|
401
|
+
if (target === undefined || target === '' || target === 'overview') return { kind: 'overview' }
|
|
402
|
+
const match = /^(node|edge|group):(.+)$/.exec(target)
|
|
403
|
+
if (!match) {
|
|
404
|
+
fail('INVALID_OP', 'target must be overview, node:<id>, edge:<id> or group:<id>')
|
|
405
|
+
}
|
|
406
|
+
const [, kind, id] = match
|
|
407
|
+
if (kind === 'node') {
|
|
408
|
+
const node = graph.nodes.find(item => item.id === id)
|
|
409
|
+
if (!node) fail('NOT_FOUND', `node "${id}" does not exist`)
|
|
410
|
+
return { kind, value: node }
|
|
411
|
+
}
|
|
412
|
+
if (kind === 'edge') {
|
|
413
|
+
const edge = graph.edges.find(item => item.id === id)
|
|
414
|
+
if (!edge) fail('NOT_FOUND', `edge "${id}" does not exist`)
|
|
415
|
+
return { kind, value: edge }
|
|
416
|
+
}
|
|
417
|
+
const group = graph.groups.find(item => item.id === id)
|
|
418
|
+
if (!group) fail('NOT_FOUND', `group "${id}" does not exist`)
|
|
419
|
+
return { kind, value: group }
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function titleOf(graph, id) {
|
|
423
|
+
return graph.nodes.find(node => node.id === id)?.title ?? id
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function renderOverview(graph, limit, include) {
|
|
427
|
+
const lines = [
|
|
428
|
+
`rev ${graph.rev} · ${formatCounts(graphCounts(graph))}`,
|
|
429
|
+
]
|
|
430
|
+
const groups = graph.groups.slice(0, limit)
|
|
431
|
+
if (groups.length > 0) {
|
|
432
|
+
lines.push('groups:')
|
|
433
|
+
for (const group of groups) lines.push(` ${group.id} "${group.title}"`)
|
|
434
|
+
if (graph.groups.length > groups.length) lines.push(` … ${graph.groups.length - groups.length} more groups`)
|
|
435
|
+
}
|
|
436
|
+
if (graph.nodes.length === 0) {
|
|
437
|
+
lines.push('nodes: (none)')
|
|
438
|
+
lines.push('Use arch_graph_patch with baseRev ' + graph.rev + ' and add_node/add_edge operations.')
|
|
439
|
+
} else {
|
|
440
|
+
lines.push('nodes:')
|
|
441
|
+
const nodes = graph.nodes.slice(0, limit)
|
|
442
|
+
for (const node of nodes) {
|
|
443
|
+
const parts = [` ${node.id} "${node.title}"`, node.kind]
|
|
444
|
+
if (node.group !== undefined) parts.push(`group ${node.group}`)
|
|
445
|
+
parts.push(node.status)
|
|
446
|
+
lines.push(parts.join(' · '))
|
|
447
|
+
if (include.includes('summary') && node.summary) lines.push(` ${clip(node.summary, 160)}`)
|
|
448
|
+
}
|
|
449
|
+
if (graph.nodes.length > nodes.length) lines.push(` … ${graph.nodes.length - nodes.length} more nodes`)
|
|
450
|
+
}
|
|
451
|
+
if (graph.edges.length > 0) {
|
|
452
|
+
lines.push('edges:')
|
|
453
|
+
const edges = graph.edges.slice(0, Math.min(limit, 60))
|
|
454
|
+
for (const edge of edges) {
|
|
455
|
+
lines.push(` ${edge.id} ${edge.from} "${titleOf(graph, edge.from)}" -> ${edge.to} "${titleOf(graph, edge.to)}"${edge.label ? ` · ${edge.label}` : ''} (${edge.kind})`)
|
|
456
|
+
}
|
|
457
|
+
if (graph.edges.length > edges.length) lines.push(` … ${graph.edges.length - edges.length} more edges`)
|
|
458
|
+
} else {
|
|
459
|
+
lines.push('edges: (none)')
|
|
460
|
+
}
|
|
461
|
+
return lines.join('\n')
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function renderNode(graph, node, options) {
|
|
465
|
+
const { include, depth, limit } = options
|
|
466
|
+
const lines = [
|
|
467
|
+
`rev ${graph.rev} · node ${node.id} "${node.title}"`,
|
|
468
|
+
`kind: ${node.kind}${node.group ? ` · group: ${node.group}` : ''} · status: ${node.status}`,
|
|
469
|
+
]
|
|
470
|
+
if (include.includes('summary') && node.summary) lines.push(`summary: ${clip(node.summary, 600)}`)
|
|
471
|
+
if (include.includes('anchors') && node.anchors.length > 0) {
|
|
472
|
+
lines.push('anchors:')
|
|
473
|
+
for (const anchor of node.anchors) {
|
|
474
|
+
lines.push(` ${anchor.path}${anchor.symbol ? `#${anchor.symbol}` : ''}${anchor.hash ? ` @${anchor.hash}` : ''}`)
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
if (include.includes('notes') && node.notes) lines.push(`notes: ${node.notes}`)
|
|
478
|
+
if (include.includes('edges')) {
|
|
479
|
+
const edges = graph.edges.filter(edge => edge.from === node.id || edge.to === node.id)
|
|
480
|
+
if (edges.length > 0) {
|
|
481
|
+
lines.push('edges:')
|
|
482
|
+
for (const edge of edges.slice(0, limit)) {
|
|
483
|
+
lines.push(` ${edge.id} ${edge.from} "${titleOf(graph, edge.from)}" -> ${edge.to} "${titleOf(graph, edge.to)}"${edge.label ? ` · ${edge.label}` : ''} (${edge.kind})`)
|
|
484
|
+
}
|
|
485
|
+
if (edges.length > limit) lines.push(` … ${edges.length - limit} more edges`)
|
|
486
|
+
} else {
|
|
487
|
+
lines.push('edges: (none)')
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (depth > 0) {
|
|
491
|
+
const seen = new Set([node.id])
|
|
492
|
+
let frontier = [node.id]
|
|
493
|
+
const neighbors = []
|
|
494
|
+
for (let level = 0; level < depth; level += 1) {
|
|
495
|
+
const next = []
|
|
496
|
+
for (const id of frontier) {
|
|
497
|
+
for (const edge of graph.edges) {
|
|
498
|
+
const other = edge.from === id ? edge.to : edge.to === id ? edge.from : undefined
|
|
499
|
+
if (other === undefined || seen.has(other)) continue
|
|
500
|
+
seen.add(other)
|
|
501
|
+
next.push(other)
|
|
502
|
+
neighbors.push(graph.nodes.find(candidate => candidate.id === other))
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
frontier = next
|
|
506
|
+
}
|
|
507
|
+
const shown = neighbors.filter(Boolean).slice(0, limit)
|
|
508
|
+
if (shown.length > 0) {
|
|
509
|
+
lines.push(`neighbors (depth ${depth}):`)
|
|
510
|
+
for (const neighbor of shown) lines.push(` ${neighbor.id} "${neighbor.title}" (${neighbor.kind})`)
|
|
511
|
+
if (neighbors.length > shown.length) lines.push(` … ${neighbors.length - shown.length} more neighbors`)
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
return lines.join('\n')
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function renderEdge(graph, edge) {
|
|
518
|
+
return [
|
|
519
|
+
`rev ${graph.rev} · edge ${edge.id}${edge.label ? ` "${edge.label}"` : ''} (${edge.kind}) · ${edge.status}`,
|
|
520
|
+
`${edge.from} "${titleOf(graph, edge.from)}" -> ${edge.to} "${titleOf(graph, edge.to)}"`,
|
|
521
|
+
].join('\n')
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function renderGroup(graph, group, limit) {
|
|
525
|
+
const members = graph.nodes.filter(node => node.group === group.id)
|
|
526
|
+
const lines = [
|
|
527
|
+
`rev ${graph.rev} · group ${group.id} "${group.title}" · ${members.length} node${members.length === 1 ? '' : 's'}`,
|
|
528
|
+
]
|
|
529
|
+
if (members.length > 0) {
|
|
530
|
+
lines.push('nodes:')
|
|
531
|
+
for (const node of members.slice(0, limit)) lines.push(` ${node.id} "${node.title}" (${node.kind})`)
|
|
532
|
+
if (members.length > limit) lines.push(` … ${members.length - limit} more nodes`)
|
|
533
|
+
}
|
|
534
|
+
return lines.join('\n')
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function formatDiff(diff) {
|
|
538
|
+
const parts = []
|
|
539
|
+
for (const [kind, part] of Object.entries(diff)) {
|
|
540
|
+
for (const id of part.added) parts.push(`+ ${kind.slice(0, -1)} ${id}`)
|
|
541
|
+
for (const id of part.updated) parts.push(`~ ${kind.slice(0, -1)} ${id}`)
|
|
542
|
+
for (const id of part.removed) parts.push(`- ${kind.slice(0, -1)} ${id}`)
|
|
543
|
+
}
|
|
544
|
+
return parts.length > 0 ? parts.join('\n') : 'no changes'
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/** Serialize one workspace's writes; reads do not take the lock. */
|
|
548
|
+
async function withLock(key, task) {
|
|
549
|
+
while (locks.has(key)) await locks.get(key)
|
|
550
|
+
let release
|
|
551
|
+
const gate = new Promise(resolve => { release = resolve })
|
|
552
|
+
locks.set(key, gate)
|
|
553
|
+
try {
|
|
554
|
+
return await task()
|
|
555
|
+
} finally {
|
|
556
|
+
locks.delete(key)
|
|
557
|
+
release()
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
export function createGraphStore(config = {}) {
|
|
562
|
+
const limits = { ...DEFAULTS }
|
|
563
|
+
for (const key of Object.keys(DEFAULTS)) {
|
|
564
|
+
if (config[key] !== undefined) limits[key] = config[key]
|
|
565
|
+
}
|
|
566
|
+
limits.dir = normalizeDataDir(limits.dir)
|
|
567
|
+
for (const key of ['maxNodes', 'maxEdges', 'maxGroups', 'maxSummary', 'maxAnchors']) {
|
|
568
|
+
if (!Number.isInteger(limits[key]) || limits[key] <= 0) limits[key] = DEFAULTS[key]
|
|
569
|
+
}
|
|
570
|
+
const resolveConfig = { dir: limits.dir, ssh: config.ssh }
|
|
571
|
+
|
|
572
|
+
async function resolve(rawWorkspace, context) {
|
|
573
|
+
return resolveWorkspace(rawWorkspace, context, resolveConfig)
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
async function readGraphAt(ws) {
|
|
577
|
+
const file = path.join(ws.stateDir, 'graph.json')
|
|
578
|
+
let text
|
|
579
|
+
try {
|
|
580
|
+
text = await fs.readFile(file, 'utf8')
|
|
581
|
+
} catch (error) {
|
|
582
|
+
if (error && error.code === 'ENOENT') return emptyGraph()
|
|
583
|
+
fail('IO_ERROR', `cannot read ${file}: ${error.message}`)
|
|
584
|
+
}
|
|
585
|
+
let parsed
|
|
586
|
+
try {
|
|
587
|
+
parsed = JSON.parse(text)
|
|
588
|
+
} catch (error) {
|
|
589
|
+
fail('GRAPH_CORRUPT', `graph.json is not valid JSON (${error.message}); a backup may exist at graph.bak.json`)
|
|
590
|
+
}
|
|
591
|
+
return validateGraph(parsed, limits)
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
async function readGraph(rawWorkspace, context) {
|
|
595
|
+
return readGraphAt(await resolve(rawWorkspace, context))
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
async function writeGraph(ws, graph) {
|
|
599
|
+
await fs.mkdir(ws.stateDir, { recursive: true })
|
|
600
|
+
const file = path.join(ws.stateDir, 'graph.json')
|
|
601
|
+
const backup = path.join(ws.stateDir, 'graph.bak.json')
|
|
602
|
+
try {
|
|
603
|
+
await fs.copyFile(file, backup)
|
|
604
|
+
} catch (error) {
|
|
605
|
+
if (!error || error.code !== 'ENOENT') throw error
|
|
606
|
+
}
|
|
607
|
+
const temp = path.join(ws.stateDir, `graph.tmp-${process.pid}-${randomBytes(6).toString('hex')}.json`)
|
|
608
|
+
await fs.writeFile(temp, JSON.stringify(graph, null, 2) + '\n', 'utf8')
|
|
609
|
+
await fs.rename(temp, file)
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
async function get(rawWorkspace, query = {}, context) {
|
|
613
|
+
const ws = await resolve(rawWorkspace, context)
|
|
614
|
+
const graph = await readGraphAt(ws)
|
|
615
|
+
const limit = Math.min(Math.max(Number.isInteger(query.limit) ? query.limit : 50, 1), 200)
|
|
616
|
+
const include = Array.isArray(query.include) ? query.include : []
|
|
617
|
+
const depth = Math.min(Math.max(Number.isInteger(query.depth) ? query.depth : 1, 0), 3)
|
|
618
|
+
const target = findTarget(graph, query.target)
|
|
619
|
+
const counts = graphCounts(graph)
|
|
620
|
+
let text
|
|
621
|
+
if (target.kind === 'overview') {
|
|
622
|
+
text = renderOverview(graph, limit, include)
|
|
623
|
+
} else if (target.kind === 'node') {
|
|
624
|
+
text = renderNode(graph, target.value, { include: include.length > 0 ? include : ['summary', 'anchors', 'edges'], depth, limit })
|
|
625
|
+
} else if (target.kind === 'edge') {
|
|
626
|
+
text = renderEdge(graph, target.value)
|
|
627
|
+
} else {
|
|
628
|
+
text = renderGroup(graph, target.value, limit)
|
|
629
|
+
}
|
|
630
|
+
return { rev: graph.rev, counts, text }
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Fill missing anchor hashes (and optionally refresh all of them) from the
|
|
635
|
+
* current files. Existing hashes are preserved unless refreshAnchors is true,
|
|
636
|
+
* so a status-only patch cannot silently hide a stale anchor. The content
|
|
637
|
+
* source owns the hash algorithm, so a remote project can use the remote
|
|
638
|
+
* digest instead of a local file read.
|
|
639
|
+
*/
|
|
640
|
+
async function refreshAnchorHashes(ws, graph, refreshAll) {
|
|
641
|
+
const wanted = new Set()
|
|
642
|
+
for (const node of graph.nodes) {
|
|
643
|
+
for (const anchor of node.anchors ?? []) {
|
|
644
|
+
if (refreshAll || anchor.hash === undefined) wanted.add(anchor.path)
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
const hashes = wanted.size > 0 && ws.content && typeof ws.content.hashMany === 'function'
|
|
648
|
+
? await ws.content.hashMany([...wanted])
|
|
649
|
+
: new Map()
|
|
650
|
+
let updated = 0
|
|
651
|
+
graph.nodes = graph.nodes.map(node => ({
|
|
652
|
+
...node,
|
|
653
|
+
anchors: (node.anchors ?? []).map(anchor => {
|
|
654
|
+
if (!refreshAll && anchor.hash !== undefined) return anchor
|
|
655
|
+
const hash = hashes.get(anchor.path)
|
|
656
|
+
if (typeof hash !== 'string') return anchor
|
|
657
|
+
updated += 1
|
|
658
|
+
return { ...anchor, hash }
|
|
659
|
+
}),
|
|
660
|
+
}))
|
|
661
|
+
return updated
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
async function patch(rawWorkspace, input = {}, context) {
|
|
665
|
+
const ws = await resolve(rawWorkspace, context)
|
|
666
|
+
return withLock(ws.stateDir, async () => {
|
|
667
|
+
const current = await readGraphAt(ws)
|
|
668
|
+
if (!Number.isInteger(input.baseRev) || input.baseRev < 0) {
|
|
669
|
+
fail('INVALID_OP', 'baseRev must be a non-negative integer')
|
|
670
|
+
}
|
|
671
|
+
if (input.baseRev !== current.rev) {
|
|
672
|
+
fail('STALE_REV', `baseRev ${input.baseRev} does not match current rev ${current.rev}; call arch_graph_get again`)
|
|
673
|
+
}
|
|
674
|
+
const next = applyOps(current, input.ops, limits)
|
|
675
|
+
const diff = diffGraphs(current, next)
|
|
676
|
+
const changes = countChanges(diff)
|
|
677
|
+
if (input.apply === false) {
|
|
678
|
+
return {
|
|
679
|
+
rev: current.rev,
|
|
680
|
+
counts: graphCounts(current),
|
|
681
|
+
text: `validated ${input.ops.length} op(s), ${changes} change(s); no write (rev stays ${current.rev})\n${formatDiff(diff)}`,
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
const refreshed = await refreshAnchorHashes(ws, next, input.refreshAnchors === true)
|
|
685
|
+
next.rev = current.rev + 1
|
|
686
|
+
next.updatedAt = new Date().toISOString()
|
|
687
|
+
await writeGraph(ws, next)
|
|
688
|
+
const refreshLine = refreshed > 0 ? `\nanchors refreshed: ${refreshed}` : ''
|
|
689
|
+
return {
|
|
690
|
+
rev: next.rev,
|
|
691
|
+
counts: graphCounts(next),
|
|
692
|
+
text: `rev ${current.rev} -> ${next.rev} · applied ${input.ops.length} op(s), ${changes} change(s)\n${formatDiff(diff)}\n${formatCounts(graphCounts(next))}${refreshLine}`,
|
|
693
|
+
}
|
|
694
|
+
})
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
return { get, patch, readGraph, validateGraph, limits, dir: limits.dir }
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** Resolve the workspace from a tool call, falling back to the session cwd. */
|
|
701
|
+
export function workspaceOf(args, exec) {
|
|
702
|
+
const explicit = args && typeof args.workspace === 'string' ? args.workspace.trim() : ''
|
|
703
|
+
if (explicit !== '') return explicit
|
|
704
|
+
const cwd = exec?.agent?.session?.header?.cwd
|
|
705
|
+
if (typeof cwd === 'string' && cwd !== '') return cwd
|
|
706
|
+
fail('WORKSPACE_REQUIRED', 'pass a workspace path or open a session with a working directory')
|
|
707
|
+
}
|