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.
Files changed (43) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/CODE_OF_CONDUCT.md +7 -0
  3. package/CONTRIBUTING.md +24 -0
  4. package/LICENSE +21 -0
  5. package/README.md +264 -2
  6. package/README.zh.md +247 -0
  7. package/THIRD_PARTY_NOTICES.md +36 -0
  8. package/client.js +1171 -0
  9. package/cordis.patch.yml +5 -0
  10. package/docs/DETAIL.md +76 -0
  11. package/docs/DETAIL.zh.md +76 -0
  12. package/docs/preview.svg +50 -0
  13. package/icon.svg +9 -0
  14. package/index.js +1 -0
  15. package/locale/en.json +7 -0
  16. package/locale/zh.json +7 -0
  17. package/package.json +68 -4
  18. package/skills/architecture-map/SKILL.md +75 -0
  19. package/skills/architecture-map/references/bootstrap.md +100 -0
  20. package/skills/architecture-map/references/discussion.md +71 -0
  21. package/skills/architecture-map/references/incremental.md +80 -0
  22. package/skills/architecture-map/references/schema.md +94 -0
  23. package/src/README.md +34 -0
  24. package/src/host/content/index.js +20 -0
  25. package/src/host/content/local.js +250 -0
  26. package/src/host/export.js +228 -0
  27. package/src/host/graph.js +707 -0
  28. package/src/host/memory.js +364 -0
  29. package/src/host/plugin.js +1125 -0
  30. package/src/host/projects.js +241 -0
  31. package/src/host/remote/commands.js +227 -0
  32. package/src/host/remote/consent.js +216 -0
  33. package/src/host/remote/content.js +391 -0
  34. package/src/host/remote/indexer.js +180 -0
  35. package/src/host/remote/maintainer.js +85 -0
  36. package/src/host/remote/ssh.js +287 -0
  37. package/src/host/remote/state.js +65 -0
  38. package/src/host/remote/tools.js +162 -0
  39. package/src/host/signature.js +42 -0
  40. package/src/host/workspace.js +131 -0
  41. package/vendor/elkjs.LICENSE +264 -0
  42. package/vendor/mermaid.LICENSE +21 -0
  43. package/vendor/mermaid.esm.min.mjs +4343 -0
@@ -0,0 +1,1125 @@
1
+ /**
2
+ * Architecture map — Host half.
3
+ *
4
+ * Node 1: `arch_hello` + `/arch` command (skeleton verification).
5
+ * Node 2: `arch_graph_get` / `arch_graph_patch` over a workspace-owned
6
+ * `.archmap/graph.json` with a revision, validation, and atomic writes.
7
+ */
8
+ import { createReadStream, readFileSync } from 'node:fs'
9
+ import { randomUUID } from 'node:crypto'
10
+ import { stat } from 'node:fs/promises'
11
+ import path from 'node:path'
12
+ import { fileURLToPath } from 'node:url'
13
+ import { createGraphStore, workspaceOf } from './graph.js'
14
+ import { createMemoryStore } from './memory.js'
15
+ import { createExporter } from './export.js'
16
+ import { resolveWorkspace } from './workspace.js'
17
+ import { createConsentGate } from './remote/consent.js'
18
+ import { createRemoteTools } from './remote/tools.js'
19
+ import { createRemoteIndexer } from './remote/indexer.js'
20
+ import { createRemoteCommands } from './remote/commands.js'
21
+ import { createMaintainer, buildMaintainerPrompt } from './remote/maintainer.js'
22
+
23
+ export const name = 'architecture-map'
24
+
25
+ /** Local asset route for the vendored Mermaid runtime; the Host serves it, never a CDN. */
26
+ const RUNTIME_PATH = '/x-dsh-architecture-map'
27
+ const VENDOR_PREFIX = `${RUNTIME_PATH}/vendor`
28
+ const VENDOR_DIR = fileURLToPath(new URL('../../vendor/', import.meta.url))
29
+ const SKILL_DIR = fileURLToPath(new URL('../../skills/architecture-map/', import.meta.url))
30
+
31
+ const VENDOR_MIME = {
32
+ '.mjs': 'text/javascript; charset=utf-8',
33
+ '.js': 'text/javascript; charset=utf-8',
34
+ '.license': 'text/plain; charset=utf-8',
35
+ }
36
+
37
+ /**
38
+ * Serve one allow-listed file from the vendored Mermaid directory.
39
+ * Mirrors the static-asset approach used by dsh-mermaid-plus (MIT).
40
+ */
41
+ async function serveVendorFile(request, response) {
42
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
43
+ response.writeHead(405, { 'content-type': 'text/plain; charset=utf-8', allow: 'GET, HEAD' })
44
+ response.end('Method Not Allowed')
45
+ return
46
+ }
47
+ let pathname
48
+ try {
49
+ pathname = decodeURIComponent(new URL(request.url ?? '/', 'http://dsh.invalid').pathname)
50
+ } catch {
51
+ response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
52
+ response.end('Bad Request')
53
+ return
54
+ }
55
+ const prefix = `${VENDOR_PREFIX}/`
56
+ const name = pathname.startsWith(prefix) ? pathname.slice(prefix.length) : ''
57
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) || name.includes('/')) {
58
+ response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' })
59
+ response.end('Not Found')
60
+ return
61
+ }
62
+ const file = path.join(VENDOR_DIR, name)
63
+ let info
64
+ try {
65
+ info = await stat(file)
66
+ } catch {
67
+ response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' })
68
+ response.end('Not Found')
69
+ return
70
+ }
71
+ if (!info.isFile()) {
72
+ response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' })
73
+ response.end('Not Found')
74
+ return
75
+ }
76
+ const headers = {
77
+ 'content-type': VENDOR_MIME[path.extname(name).toLowerCase()] ?? 'application/octet-stream',
78
+ 'content-length': info.size,
79
+ 'cache-control': 'no-store',
80
+ 'x-content-type-options': 'nosniff',
81
+ }
82
+ if (request.method === 'HEAD') {
83
+ response.writeHead(200, headers)
84
+ response.end()
85
+ return
86
+ }
87
+ response.writeHead(200, headers)
88
+ createReadStream(file).pipe(response)
89
+ }
90
+
91
+ /**
92
+ * Read the bundled skill body (frontmatter stripped). The skill file is the
93
+ * single source of truth; the Host registers it as an embedded runtime skill so
94
+ * a new session sees `architecture-map` in its skill catalog.
95
+ */
96
+ function readSkillContent() {
97
+ try {
98
+ const raw = readFileSync(path.join(SKILL_DIR, 'SKILL.md'), 'utf8')
99
+ return raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').replace(/^\n+/, '')
100
+ } catch {
101
+ return undefined
102
+ }
103
+ }
104
+
105
+ /** Known third-party Mermaid fence providers that would collide on the `mermaid` key. */
106
+ const OTHER_MERMAID_PLUGINS = new Set(['dsh-mermaid-plus'])
107
+
108
+ /** Detect a known Mermaid fence provider through the loader, when inspectable. */
109
+ function hasOtherMermaidPlugin(ctx) {
110
+ try {
111
+ const loader = ctx?.loader ?? (typeof ctx.get === 'function' ? ctx.get('loader') : undefined)
112
+ const entries = loader?.entries?.() ?? []
113
+ return entries.some(entry => {
114
+ const name = entry?.options?.name ?? entry?.name
115
+ return OTHER_MERMAID_PLUGINS.has(name)
116
+ })
117
+ } catch {
118
+ return false
119
+ }
120
+ }
121
+
122
+ /** Report whether the browser half may render Mermaid fences. */
123
+ function serveMermaidConfig(renderMermaid, mode) {
124
+ return (request, response) => {
125
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
126
+ response.writeHead(405, { 'content-type': 'text/plain; charset=utf-8', allow: 'GET, HEAD' })
127
+ response.end('Method Not Allowed')
128
+ return
129
+ }
130
+ response.writeHead(200, {
131
+ 'content-type': 'application/json; charset=utf-8',
132
+ 'cache-control': 'no-store',
133
+ })
134
+ response.end(JSON.stringify({ mermaid: renderMermaid, mode }))
135
+ }
136
+ }
137
+
138
+
139
+ /** Services this plugin needs before it activates. */
140
+ export const inject = ['tools', 'commands']
141
+
142
+ const SYNC_OUTPUT = {
143
+ schema: {
144
+ type: 'object',
145
+ additionalProperties: false,
146
+ properties: {
147
+ text: { type: 'string' },
148
+ counts: {
149
+ type: 'object',
150
+ additionalProperties: false,
151
+ properties: {
152
+ scanned: { type: 'integer' },
153
+ added: { type: 'integer' },
154
+ changed: { type: 'integer' },
155
+ cosmetic: { type: 'integer' },
156
+ deleted: { type: 'integer' },
157
+ affected: { type: 'integer' },
158
+ marked: { type: 'integer' },
159
+ },
160
+ required: ['scanned', 'added', 'changed', 'cosmetic', 'deleted', 'affected', 'marked'],
161
+ },
162
+ },
163
+ required: ['text', 'counts'],
164
+ },
165
+ render: (_args, value) => [{ type: 'text', text: value.text }],
166
+ }
167
+
168
+ const COMMIT_OUTPUT = {
169
+ schema: {
170
+ type: 'object',
171
+ additionalProperties: false,
172
+ properties: {
173
+ text: { type: 'string' },
174
+ committed: { type: 'integer' },
175
+ removed: { type: 'integer' },
176
+ },
177
+ required: ['text', 'committed', 'removed'],
178
+ },
179
+ render: (_args, value) => [{ type: 'text', text: value.text }],
180
+ }
181
+
182
+ const DOC_GET_OUTPUT = {
183
+ schema: {
184
+ type: 'object',
185
+ additionalProperties: false,
186
+ properties: {
187
+ text: { type: 'string' },
188
+ found: { type: 'boolean' },
189
+ },
190
+ required: ['text', 'found'],
191
+ },
192
+ render: (_args, value) => [{ type: 'text', text: value.text }],
193
+ }
194
+
195
+ const DOC_PUT_OUTPUT = {
196
+ schema: {
197
+ type: 'object',
198
+ additionalProperties: false,
199
+ properties: {
200
+ text: { type: 'string' },
201
+ bytes: { type: 'integer' },
202
+ },
203
+ required: ['text', 'bytes'],
204
+ },
205
+ render: (_args, value) => [{ type: 'text', text: value.text }],
206
+ }
207
+
208
+ const EXPORT_OUTPUT = {
209
+ schema: {
210
+ type: 'object',
211
+ additionalProperties: false,
212
+ properties: {
213
+ text: { type: 'string' },
214
+ path: { type: 'string' },
215
+ bytes: { type: 'integer' },
216
+ format: { type: 'string' },
217
+ },
218
+ required: ['text', 'path', 'bytes', 'format'],
219
+ },
220
+ render: (_args, value) => [{ type: 'text', text: value.text }],
221
+ }
222
+
223
+ const DISCUSS_OUTPUT = {
224
+ schema: {
225
+ type: 'object',
226
+ additionalProperties: false,
227
+ properties: {
228
+ text: { type: 'string' },
229
+ name: { type: 'string' },
230
+ mode: { type: 'string' },
231
+ target: { type: 'string' },
232
+ childId: { type: 'string' },
233
+ },
234
+ required: ['text', 'name', 'mode', 'target', 'childId'],
235
+ },
236
+ render: (_args, value) => [{ type: 'text', text: value.text }],
237
+ }
238
+
239
+ const GRAPH_OUTPUT = {
240
+ schema: {
241
+ type: 'object',
242
+ additionalProperties: false,
243
+ properties: {
244
+ text: { type: 'string' },
245
+ rev: { type: 'integer' },
246
+ counts: {
247
+ type: 'object',
248
+ additionalProperties: false,
249
+ properties: {
250
+ nodes: { type: 'integer' },
251
+ edges: { type: 'integer' },
252
+ groups: { type: 'integer' },
253
+ },
254
+ required: ['nodes', 'edges', 'groups'],
255
+ },
256
+ },
257
+ required: ['text', 'rev', 'counts'],
258
+ },
259
+ render: (_args, value) => [{ type: 'text', text: value.text }],
260
+ }
261
+
262
+ const REMOTE_TEXT_OUTPUT = {
263
+ schema: {
264
+ type: 'object',
265
+ additionalProperties: false,
266
+ properties: {
267
+ text: { type: 'string' },
268
+ },
269
+ required: ['text'],
270
+ },
271
+ render: (_args, value) => [{ type: 'text', text: value.text }],
272
+ }
273
+
274
+ /**
275
+ * Register the M0/M1 tools and the `/arch` command.
276
+ * @param {import('@deepseek-ai/cordis').Context} ctx - Host plugin context.
277
+ * @param {Record<string, unknown>} [config] - Plugin row configuration.
278
+ * @returns {void}
279
+ */
280
+ export function apply(ctx, config = {}) {
281
+ const mermaidMode = config?.renderMermaid ?? 'auto'
282
+ const renderMermaid = mermaidMode === true || mermaidMode === 'on'
283
+ ? true
284
+ : mermaidMode === false || mermaidMode === 'off'
285
+ ? false
286
+ : mermaidMode === 'auto'
287
+ ? !hasOtherMermaidPlugin(ctx)
288
+ : true
289
+ let agents = null
290
+ let subagents = null
291
+ const store = createGraphStore(config)
292
+ const markStaleNodes = async (workspace, ids, context) => {
293
+ for (let attempt = 0; attempt < 3; attempt += 1) {
294
+ const graph = await store.readGraph(workspace, context)
295
+ const wanted = [...new Set(ids)].filter(id => graph.nodes.some(node => node.id === id && node.status !== 'stale'))
296
+ if (wanted.length === 0) return { marked: [], rev: graph.rev }
297
+ try {
298
+ const result = await store.patch(workspace, {
299
+ baseRev: graph.rev,
300
+ ops: wanted.map(id => ({ op: 'update_node', id, patch: { status: 'stale' } })),
301
+ }, context)
302
+ return { marked: wanted, rev: result.rev }
303
+ } catch (error) {
304
+ if (!String(error?.message).includes('STALE_REV') || attempt === 2) throw error
305
+ }
306
+ }
307
+ return { marked: [], rev: 0 }
308
+ }
309
+ const memory = createMemoryStore(config, { readGraph: store.readGraph, markStale: markStaleNodes })
310
+ const exporter = createExporter({
311
+ readGraph: store.readGraph,
312
+ resolve: (raw, context) => resolveWorkspace(raw, context, config),
313
+ })
314
+
315
+ // Remote content is gated by a blocking user question. The service is
316
+ // optional: a profile without userQuestions fails closed and remote reads
317
+ // stay unavailable until an explicit grant path exists.
318
+ let userQuestions = null
319
+ ctx.inject(['userQuestions'], scope => {
320
+ userQuestions = scope.userQuestions
321
+ return () => { userQuestions = null }
322
+ })
323
+ const consent = createConsentGate({ getUserQuestions: () => userQuestions })
324
+ const maintainer = createMaintainer({
325
+ consent,
326
+ startChild: async ({ ws, agent, counts }) => {
327
+ if (subagents === null) throw new Error('remote maintenance needs the subagents service')
328
+ const childId = randomUUID()
329
+ discussionIds.add(childId)
330
+ discussionRemoteIds.add(childId)
331
+ const activation = await subagents.startActivation({
332
+ provider: 'spawn',
333
+ childId,
334
+ label: `Maintain remote ${ws.id}`,
335
+ name: `remote-${ws.id}-maint`,
336
+ prompt: [{ type: 'text', text: buildMaintainerPrompt(ws, counts) }],
337
+ parent: agent,
338
+ delivery: 'caller',
339
+ })
340
+ restrictDiscussionChildSoon(activation.childId, REMOTE_DISCUSSION_DENY)
341
+ void activation.result.catch(() => {})
342
+ return activation
343
+ },
344
+ })
345
+ const remoteIndexer = createRemoteIndexer({ memory, maintainer })
346
+ const remoteTools = createRemoteTools({
347
+ config,
348
+ consent,
349
+ onUse: (ws, context) => remoteIndexer.track(ws, context),
350
+ })
351
+ const remoteCommands = createRemoteCommands({ config, consent, indexer: remoteIndexer, maintainer })
352
+ if (typeof ctx.effect === 'function') {
353
+ ctx.effect(() => () => remoteIndexer.dispose(), 'architecture-map: remote indexer timers')
354
+ }
355
+
356
+ ctx.tools.register({
357
+ name: 'arch_hello',
358
+ description:
359
+ 'Return a diagnostic hello message. Use this once to confirm the Architecture map plugin is installed and active.',
360
+ parameters: {
361
+ type: 'object',
362
+ additionalProperties: false,
363
+ properties: {},
364
+ },
365
+ output: {
366
+ schema: {
367
+ type: 'object',
368
+ additionalProperties: false,
369
+ properties: {
370
+ message: { type: 'string' },
371
+ },
372
+ required: ['message'],
373
+ },
374
+ render: (_args, value) => [{ type: 'text', text: value.message }],
375
+ },
376
+ async execute() {
377
+ return { message: 'hello from architecture map' }
378
+ },
379
+ })
380
+
381
+ ctx.tools.register({
382
+ name: 'arch_graph_get',
383
+ description:
384
+ 'Read the architecture graph for a workspace. Start with the overview, then read one node before editing it. '
385
+ + 'Returns the current rev and a bounded text summary. Use the rev in the next arch_graph_patch call.',
386
+ parameters: {
387
+ type: 'object',
388
+ additionalProperties: false,
389
+ properties: {
390
+ target: {
391
+ type: 'string',
392
+ description: 'overview (default) | node:<id> | edge:<id> | group:<id>',
393
+ },
394
+ depth: {
395
+ type: 'integer',
396
+ minimum: 0,
397
+ maximum: 3,
398
+ description: 'Neighbor hops for node targets; default 1.',
399
+ },
400
+ include: {
401
+ type: 'array',
402
+ items: { type: 'string', enum: ['summary', 'anchors', 'notes', 'edges'] },
403
+ description: 'Fields to include. Overview defaults to none; a node defaults to summary, anchors and edges.',
404
+ },
405
+ limit: {
406
+ type: 'integer',
407
+ minimum: 1,
408
+ maximum: 200,
409
+ description: 'Maximum items per list; default 50.',
410
+ },
411
+ workspace: {
412
+ type: 'string',
413
+ description: 'Absolute local workspace root or remote:<id>; defaults to the session working directory.',
414
+ },
415
+ },
416
+ },
417
+ output: GRAPH_OUTPUT,
418
+ async execute(args, exec) {
419
+ return store.get(workspaceOf(args, exec), args, exec)
420
+ },
421
+ })
422
+
423
+ ctx.tools.register({
424
+ name: 'arch_graph_patch',
425
+ description:
426
+ 'Apply a validated batch edit to the architecture graph. Pass the latest baseRev (0 for a new graph). '
427
+ + 'Use apply:false to validate and preview without writing. Add nodes before edges that reference them. '
428
+ + 'Missing anchor hashes are filled from disk; refreshAnchors:true recomputes all anchor hashes after review.',
429
+ parameters: {
430
+ type: 'object',
431
+ additionalProperties: false,
432
+ properties: {
433
+ baseRev: {
434
+ type: 'integer',
435
+ minimum: 0,
436
+ description: 'Current graph rev; use 0 when the graph does not exist yet.',
437
+ },
438
+ ops: {
439
+ type: 'array',
440
+ items: { type: 'object', additionalProperties: true },
441
+ description: 'Ordered operations. Shapes: {op:"add_node", node:{id,title,kind,summary?,anchors?:[{path,symbol?,hash?}]}}; {op:"update_node", id, patch:{...}}; {op:"remove_node", id, cascade?}; {op:"add_edge", edge:{id,from,to,label?,kind?}}; {op:"update_edge", id, patch:{...}}; {op:"remove_edge", id}; {op:"set_group", group:{id,title}}; {op:"remove_group", id}.',
442
+ },
443
+ apply: {
444
+ type: 'boolean',
445
+ description: 'false validates and returns a diff without writing; default true.',
446
+ },
447
+ refreshAnchors: {
448
+ type: 'boolean',
449
+ description: 'Recompute every anchor hash from the current files after applying. Use after reviewing a stale node; default false (only missing hashes are filled).',
450
+ },
451
+ workspace: {
452
+ type: 'string',
453
+ description: 'Absolute local workspace root or remote:<id>; defaults to the session working directory.',
454
+ },
455
+ },
456
+ required: ['baseRev', 'ops'],
457
+ },
458
+ output: GRAPH_OUTPUT,
459
+ async execute(args, exec) {
460
+ return store.patch(workspaceOf(args, exec), args, exec)
461
+ },
462
+ })
463
+
464
+ ctx.tools.register({
465
+ name: 'arch_sync',
466
+ description:
467
+ 'Compare the workspace against .archmap/manifest.json. Use full:true when no manifest exists. '
468
+ + 'Returns only added/changed/deleted workspace-relative files and the graph nodes whose anchors they affect. '
469
+ + 'Changed files are classified as code or format/comment-only via a normalized signature; only code changes '
470
+ + 'affect nodes. By default this tool writes nothing; markStale:true marks affected nodes stale. '
471
+ + 'It never writes the manifest; call arch_manifest_commit after analysis.',
472
+ parameters: {
473
+ type: 'object',
474
+ additionalProperties: false,
475
+ properties: {
476
+ full: {
477
+ type: 'boolean',
478
+ description: 'Ignore the manifest and list every scannable file; use for the first pass.',
479
+ },
480
+ paths: {
481
+ type: 'array',
482
+ items: { type: 'string' },
483
+ description: 'Optional workspace-relative files to limit the comparison to.',
484
+ },
485
+ markStale: {
486
+ type: 'boolean',
487
+ description: 'When true, mark affected nodes stale (writes the graph and bumps its rev). Default false: report only.',
488
+ },
489
+ workspace: {
490
+ type: 'string',
491
+ description: 'Absolute local workspace root or remote:<id>; defaults to the session working directory.',
492
+ },
493
+ },
494
+ },
495
+ output: SYNC_OUTPUT,
496
+ async execute(args, exec) {
497
+ return memory.sync(workspaceOf(args, exec), args, exec)
498
+ },
499
+ })
500
+
501
+ ctx.tools.register({
502
+ name: 'arch_manifest_commit',
503
+ description:
504
+ 'Record workspace-relative files as analyzed in .archmap/manifest.json. Call after reading them and updating '
505
+ + 'their dossier documents. Missing or unreadable files are removed from the manifest.',
506
+ parameters: {
507
+ type: 'object',
508
+ additionalProperties: false,
509
+ properties: {
510
+ paths: {
511
+ type: 'array',
512
+ items: { type: 'string' },
513
+ description: 'Workspace-relative files that have been analyzed.',
514
+ },
515
+ workspace: {
516
+ type: 'string',
517
+ description: 'Absolute local workspace root or remote:<id>; defaults to the session working directory.',
518
+ },
519
+ },
520
+ required: ['paths'],
521
+ },
522
+ output: COMMIT_OUTPUT,
523
+ async execute(args, exec) {
524
+ return memory.commit(workspaceOf(args, exec), args, exec)
525
+ },
526
+ })
527
+
528
+ ctx.tools.register({
529
+ name: 'arch_doc_get',
530
+ description:
531
+ 'Read one architecture dossier document. Valid ids: overview, modules/<id>, notes/<id>.',
532
+ parameters: {
533
+ type: 'object',
534
+ additionalProperties: false,
535
+ properties: {
536
+ id: {
537
+ type: 'string',
538
+ description: 'overview | modules/<id> | notes/<id>',
539
+ },
540
+ workspace: {
541
+ type: 'string',
542
+ description: 'Absolute local workspace root or remote:<id>; defaults to the session working directory.',
543
+ },
544
+ },
545
+ required: ['id'],
546
+ },
547
+ output: DOC_GET_OUTPUT,
548
+ async execute(args, exec) {
549
+ return memory.getDoc(workspaceOf(args, exec), args.id, exec)
550
+ },
551
+ })
552
+
553
+ ctx.tools.register({
554
+ name: 'arch_doc_put',
555
+ description:
556
+ 'Write an architecture dossier document. Valid ids: overview, modules/<id>, notes/<id>. '
557
+ + 'Use mode:append for node notes; overwrite is the default.',
558
+ parameters: {
559
+ type: 'object',
560
+ additionalProperties: false,
561
+ properties: {
562
+ id: {
563
+ type: 'string',
564
+ description: 'overview | modules/<id> | notes/<id>',
565
+ },
566
+ content: {
567
+ type: 'string',
568
+ description: 'Markdown content. The document is capped at 32 KiB.',
569
+ },
570
+ mode: {
571
+ type: 'string',
572
+ enum: ['overwrite', 'append'],
573
+ description: 'append adds a blank line plus the content; default overwrite.',
574
+ },
575
+ workspace: {
576
+ type: 'string',
577
+ description: 'Absolute local workspace root or remote:<id>; defaults to the session working directory.',
578
+ },
579
+ },
580
+ required: ['id', 'content'],
581
+ },
582
+ output: DOC_PUT_OUTPUT,
583
+ async execute(args, exec) {
584
+ return memory.putDoc(workspaceOf(args, exec), args, exec)
585
+ },
586
+ })
587
+
588
+ ctx.tools.register({
589
+ name: 'arch_export',
590
+ description:
591
+ 'Export the canonical architecture graph to .archmap/export/. Formats: mermaid (flowchart source), '
592
+ + 'svg (standalone diagram) and markdown (dossier digest). Deterministic; does not modify the graph.',
593
+ parameters: {
594
+ type: 'object',
595
+ additionalProperties: false,
596
+ properties: {
597
+ format: {
598
+ type: 'string',
599
+ enum: ['mermaid', 'svg', 'markdown'],
600
+ description: 'mermaid: flowchart source; svg: standalone diagram; markdown: dossier digest.',
601
+ },
602
+ workspace: {
603
+ type: 'string',
604
+ description: 'Absolute local workspace root or remote:<id>; defaults to the session working directory.',
605
+ },
606
+ },
607
+ required: ['format'],
608
+ },
609
+ output: EXPORT_OUTPUT,
610
+ async execute(args, exec) {
611
+ return exporter.export(workspaceOf(args, exec), args, exec)
612
+ },
613
+ })
614
+
615
+ ctx.tools.register({
616
+ name: 'arch_remote_list',
617
+ description:
618
+ 'List local and remote architecture projects registered in this workspace\'s .archmap/index.json. '
619
+ + 'Metadata only: no remote file content and no consent question.',
620
+ parameters: {
621
+ type: 'object',
622
+ additionalProperties: false,
623
+ properties: {
624
+ workspace: {
625
+ type: 'string',
626
+ description: 'Absolute local hub workspace or remote:<id>; defaults to the session working directory.',
627
+ },
628
+ },
629
+ },
630
+ output: REMOTE_TEXT_OUTPUT,
631
+ async execute(args, exec) {
632
+ return remoteTools.list(args, exec)
633
+ },
634
+ })
635
+
636
+ ctx.tools.register({
637
+ name: 'arch_remote_status',
638
+ description:
639
+ 'Report a remote project\'s SSH target, vcs, HEAD/dirty state or non-git digest, and consent scope. '
640
+ + 'Reads metadata only; no file content and no consent question.',
641
+ parameters: {
642
+ type: 'object',
643
+ additionalProperties: false,
644
+ properties: {
645
+ id: {
646
+ type: 'string',
647
+ pattern: '^[a-z][a-z0-9_-]{0,63}$',
648
+ description: 'Registered remote project id.',
649
+ },
650
+ },
651
+ required: ['id'],
652
+ },
653
+ output: REMOTE_TEXT_OUTPUT,
654
+ async execute(args, exec) {
655
+ return remoteTools.status(args, exec)
656
+ },
657
+ })
658
+
659
+ ctx.tools.register({
660
+ name: 'arch_remote_tree',
661
+ description:
662
+ 'List paths in a remote project without reading file contents. Requires remote content consent; '
663
+ + 'the first call asks the user. Read-only.',
664
+ parameters: {
665
+ type: 'object',
666
+ additionalProperties: false,
667
+ properties: {
668
+ id: {
669
+ type: 'string',
670
+ pattern: '^[a-z][a-z0-9_-]{0,63}$',
671
+ description: 'Registered remote project id.',
672
+ },
673
+ maxEntries: {
674
+ type: 'integer',
675
+ minimum: 1,
676
+ maximum: 2000,
677
+ description: 'Maximum paths to print; default 500.',
678
+ },
679
+ },
680
+ required: ['id'],
681
+ },
682
+ output: REMOTE_TEXT_OUTPUT,
683
+ async execute(args, exec) {
684
+ return remoteTools.tree(args, exec)
685
+ },
686
+ })
687
+
688
+ ctx.tools.register({
689
+ name: 'arch_remote_read',
690
+ description:
691
+ 'Read one remote file with line numbers. Requires remote content consent. '
692
+ + 'Use arch_remote_grep to locate code, then read ranges with offset/limit. Read-only.',
693
+ parameters: {
694
+ type: 'object',
695
+ additionalProperties: false,
696
+ properties: {
697
+ id: {
698
+ type: 'string',
699
+ pattern: '^[a-z][a-z0-9_-]{0,63}$',
700
+ description: 'Registered remote project id.',
701
+ },
702
+ path: {
703
+ type: 'string',
704
+ description: 'Remote-root-relative POSIX path.',
705
+ },
706
+ offset: {
707
+ type: 'integer',
708
+ minimum: 1,
709
+ description: 'First line, 1-based; default 1.',
710
+ },
711
+ limit: {
712
+ type: 'integer',
713
+ minimum: 1,
714
+ maximum: 400,
715
+ description: 'Maximum lines; default 200.',
716
+ },
717
+ },
718
+ required: ['id', 'path'],
719
+ },
720
+ output: REMOTE_TEXT_OUTPUT,
721
+ async execute(args, exec) {
722
+ return remoteTools.read(args, exec)
723
+ },
724
+ })
725
+
726
+ ctx.tools.register({
727
+ name: 'arch_remote_grep',
728
+ description:
729
+ 'Search remote project files with rg (or grep when rg is unavailable). Requires remote content consent. '
730
+ + 'Read-only; results are capped.',
731
+ parameters: {
732
+ type: 'object',
733
+ additionalProperties: false,
734
+ properties: {
735
+ id: {
736
+ type: 'string',
737
+ pattern: '^[a-z][a-z0-9_-]{0,63}$',
738
+ description: 'Registered remote project id.',
739
+ },
740
+ pattern: {
741
+ type: 'string',
742
+ description: 'Regular expression passed to rg/grep.',
743
+ },
744
+ path: {
745
+ type: 'string',
746
+ description: 'Optional remote-root-relative directory to search; defaults to the whole root.',
747
+ },
748
+ include: {
749
+ type: 'string',
750
+ description: 'Optional glob (for example "*.ts").',
751
+ },
752
+ context: {
753
+ type: 'integer',
754
+ minimum: 0,
755
+ maximum: 5,
756
+ description: 'Context lines around a match; default 0.',
757
+ },
758
+ maxResults: {
759
+ type: 'integer',
760
+ minimum: 1,
761
+ maximum: 200,
762
+ description: 'Maximum matches; default 100.',
763
+ },
764
+ },
765
+ required: ['id', 'pattern'],
766
+ },
767
+ output: REMOTE_TEXT_OUTPUT,
768
+ async execute(args, exec) {
769
+ return remoteTools.grep(args, exec)
770
+ },
771
+ })
772
+
773
+ // Per-node side conversations are optional: a minimal profile may not
774
+ // compose the subagent service. When it is present, register the tool.
775
+ ctx.inject(['agents'], scope => {
776
+ agents = scope.agents
777
+ return () => { agents = null }
778
+ })
779
+
780
+ /** Best-effort child restriction: no shell and no generic source-file writes. */
781
+ const DISCUSSION_DENY = ['bash', 'pwsh', 'terminal', 'write', 'edit', 'str_replace_editor', 'apply_patch']
782
+ /** Remote discussions must read through arch_remote_* instead of local files. */
783
+ const REMOTE_DISCUSSION_DENY = ['read', 'grep', 'glob']
784
+ const discussionIds = new Set()
785
+ const discussionRemoteIds = new Set()
786
+
787
+ const restrictAgentTools = (agent, extraDeny = []) => {
788
+ if (!agent?.ctx?.tools || typeof agent.ctx.tools.restrict !== 'function') return 0
789
+ let applied = 0
790
+ let firstError
791
+ for (const name of new Set([...DISCUSSION_DENY, ...extraDeny])) {
792
+ try {
793
+ agent.ctx.tools.restrict({ deny: [name] })
794
+ applied += 1
795
+ } catch (error) {
796
+ firstError ??= error
797
+ }
798
+ }
799
+ if (applied === 0) {
800
+ console.warn('[architecture-map] could not restrict discussion child tools:', String(firstError?.message ?? 'no tool matched'))
801
+ }
802
+ return applied
803
+ }
804
+
805
+ const restrictDiscussionChild = (childId, extraDeny = []) => {
806
+ const id = String(childId)
807
+ discussionIds.add(id)
808
+ if (agents !== null && typeof agents.get === 'function') {
809
+ const child = agents.get(id)
810
+ if (child) return restrictAgentTools(child, extraDeny)
811
+ }
812
+ return 0
813
+ }
814
+
815
+ /** A resumed child emits agent/created; restrict it before its queued turn runs. */
816
+ /** Recognize our children from the durable subagent descriptor (label). */
817
+ const isDiscussionAgent = agent => {
818
+ if (discussionIds.has(String(agent.id))) return true
819
+ try {
820
+ const events = agent.session?.snapshotEvents?.() ?? []
821
+ const descriptor = events.find(event => event.type === 'subagent/descriptor')
822
+ return typeof descriptor?.data?.label === 'string' && /^Discuss (node|edge) /.test(descriptor.data.label)
823
+ } catch {
824
+ return false
825
+ }
826
+ }
827
+
828
+ if (typeof ctx.on === 'function') {
829
+ ctx.on('agent/created', ({ agent }) => {
830
+ if (!agent || !isDiscussionAgent(agent)) return
831
+ discussionIds.add(String(agent.id))
832
+ const extraDeny = discussionRemoteIds.has(String(agent.id)) ? REMOTE_DISCUSSION_DENY : []
833
+ restrictAgentTools(agent, extraDeny)
834
+ })
835
+ }
836
+
837
+ /** An inactive child has no live Agent yet; retry, then rely on agent/created. */
838
+ const restrictDiscussionChildSoon = (childId, extraDeny = []) => {
839
+ if (restrictDiscussionChild(childId, extraDeny) > 0) return
840
+ let attempts = 0
841
+ const timer = setInterval(() => {
842
+ attempts += 1
843
+ const applied = restrictDiscussionChild(childId, extraDeny)
844
+ if (applied > 0 || attempts >= 10) {
845
+ clearInterval(timer)
846
+ if (applied === 0) console.warn('[architecture-map] discussion child is not live; restriction will apply when it starts')
847
+ }
848
+ }, 100)
849
+ timer.unref?.()
850
+ }
851
+
852
+ /**
853
+ * Reapply restrictions to discussion children that outlived a plugin reload.
854
+ * Inactive children still get their id recorded; agent/created catches them
855
+ * when they resume.
856
+ */
857
+ const discoverDiscussionChildren = async () => {
858
+ if (!agents || !subagents || typeof agents.list !== 'function' || typeof subagents.listDescendants !== 'function') return
859
+ const roots = agents.list()
860
+ const seenRoots = new Set()
861
+ for (const root of roots) {
862
+ const rootId = String(root.id)
863
+ if (seenRoots.has(rootId)) continue
864
+ seenRoots.add(rootId)
865
+ let rows
866
+ try {
867
+ rows = await subagents.listDescendants(root.id)
868
+ } catch {
869
+ continue
870
+ }
871
+ for (const row of rows) {
872
+ if (row.kind !== 'child') continue
873
+ const name = typeof row.name === 'string' ? row.name : ''
874
+ if (!/^(node|edge)-/.test(name)) continue
875
+ const id = String(row.id)
876
+ if (discussionIds.has(id)) continue
877
+ discussionIds.add(id)
878
+ const live = typeof agents.get === 'function' ? agents.get(id) : undefined
879
+ if (live) restrictAgentTools(live)
880
+ }
881
+ }
882
+ }
883
+
884
+ const startDiscussion = async ({ agent, workspace, target, mode, question, signal, context }) => {
885
+ if (!agent) throw new Error('arch_discuss requires an owning agent session')
886
+ if (subagents === null) throw new Error('arch_discuss requires the subagents service')
887
+ const remote = String(workspace).startsWith('remote:')
888
+ const remoteWorkspace = remote ? await resolveWorkspace(workspace, context, config) : null
889
+ if (remote && !consent.isAllowed(remoteWorkspace, context).allowed) {
890
+ throw new Error('REMOTE_CONSENT_REQUIRED: allow remote content before starting a discussion')
891
+ }
892
+ const graph = await store.readGraph(workspace, context)
893
+ const match = /^(node|edge):(.+)$/.exec(String(target ?? ''))
894
+ if (!match) throw new Error('target must be node:<id> or edge:<id>')
895
+ const [, kind, id] = match
896
+ const node = kind === 'node' ? graph.nodes.find(item => item.id === id) : undefined
897
+ const edge = kind === 'edge' ? graph.edges.find(item => item.id === id) : undefined
898
+ if (!node && !edge) throw new Error(`${kind} "${id}" does not exist in ${workspace}`)
899
+ const chosenMode = mode === 'lite' ? 'lite' : 'fork'
900
+ const name = `${kind === 'node' ? 'node' : 'edge'}-${id}${chosenMode === 'lite' ? '-lite' : ''}`
901
+ const label = `Discuss ${kind} ${id}`
902
+ const parentId = String(agent.session.id)
903
+
904
+ const findExisting = async () => {
905
+ if (typeof subagents.listDescendants !== 'function') return undefined
906
+ try {
907
+ const rows = await subagents.listDescendants(parentId, signal)
908
+ const found = rows.find(row => row.kind === 'child' && row.depth === 1 && 'name' in row && row.name === name)
909
+ if (!found || found.mode === 'external' || found.mode === 'unknown') return undefined
910
+ return found
911
+ } catch {
912
+ return undefined
913
+ }
914
+ }
915
+
916
+ const existing = await findExisting()
917
+ if (existing) {
918
+ if (remote) discussionRemoteIds.add(String(existing.id))
919
+ restrictDiscussionChildSoon(existing.id, remote ? REMOTE_DISCUSSION_DENY : [])
920
+ return {
921
+ text: `existing ${name} — open it from the subagent catalog.`,
922
+ name: existing.name ?? name,
923
+ childId: String(existing.id),
924
+ parentId,
925
+ resourceMode: existing.mode === 'one-shot' ? 'one-shot' : 'continuable',
926
+ mode: chosenMode,
927
+ target: `${kind}:${id}`,
928
+ existing: true,
929
+ }
930
+ }
931
+
932
+ const title = node ? node.title : edge.label ?? `${edge.from} -> ${edge.to}`
933
+ const prompt = [
934
+ `You are the discussion agent for architecture ${kind} ${id}${title ? ` ("${title}")` : ''} in workspace ${workspace}.`,
935
+ '',
936
+ `Start by calling arch_graph_get({ workspace: ${JSON.stringify(workspace)}, target: ${JSON.stringify(`${kind}:${id}`)}, include: ["summary", "anchors", "edges"] }) and arch_doc_get({ workspace: ${JSON.stringify(workspace)}, id: "modules/${id}" }) if it exists.`,
937
+ '',
938
+ 'Rules:',
939
+ `- Discuss ${id} and its edges only; ask before touching other nodes.`,
940
+ '- Do not edit source code. Graph edits go through arch_graph_patch with the latest rev; prefer apply:false until the user says apply.',
941
+ '- Do not message the parent agent. Write conclusions to notes/' + id + ' via arch_doc_put with mode "append".',
942
+ '- If an anchor looks stale, call arch_sync and say so before concluding.',
943
+ remote ? '- This is a remote workspace: read code with arch_remote_tree/arch_remote_read/arch_remote_grep; local read, grep, glob and bash do not see it.' : '',
944
+ chosenMode === 'lite' ? '- You do not inherit the parent conversation; rely on the graph and the dossier.' : '',
945
+ typeof question === 'string' && question.trim() !== '' ? `\nThe user's initial question: ${question.trim()}` : '',
946
+ ].filter(Boolean).join('\n')
947
+
948
+ // Reserve the child id first so agent/created can restrict it before the
949
+ // first model turn runs.
950
+ const childId = randomUUID()
951
+ discussionIds.add(childId)
952
+ if (remote) discussionRemoteIds.add(childId)
953
+ const activation = await subagents.startActivation({
954
+ provider: chosenMode === 'fork' ? 'fork' : 'spawn',
955
+ childId,
956
+ label,
957
+ name,
958
+ prompt: [{ type: 'text', text: prompt }],
959
+ parent: agent,
960
+ signal,
961
+ delivery: 'caller',
962
+ })
963
+ // The child runs in the background; the caller does not await its result.
964
+ if (remote) consent.inherit(remoteWorkspace, String(activation.childId), parentId)
965
+ restrictDiscussionChildSoon(activation.childId, remote ? REMOTE_DISCUSSION_DENY : [])
966
+ void activation.result.catch(() => {})
967
+ return {
968
+ text: `started ${activation.name} (${chosenMode}) — open it from the subagent catalog in the session header.`,
969
+ name: activation.name,
970
+ childId: String(activation.childId),
971
+ parentId,
972
+ resourceMode: 'continuable',
973
+ mode: chosenMode,
974
+ target: `${kind}:${id}`,
975
+ existing: false,
976
+ }
977
+ }
978
+
979
+ ctx.inject(['subagents'], scope => {
980
+ subagents = scope.subagents
981
+ scope.tools.register({
982
+ name: 'arch_discuss',
983
+ description:
984
+ 'Start a side conversation about one architecture node or edge. mode:fork inherits the main conversation\'s '
985
+ + 'completed turns; mode:lite starts fresh with the graph and dossier. Reuses an existing named child instead '
986
+ + 'of creating a duplicate. The child gets arch_* tools and runs in its own session.',
987
+ parameters: {
988
+ type: 'object',
989
+ additionalProperties: false,
990
+ properties: {
991
+ target: {
992
+ type: 'string',
993
+ description: 'node:<id> or edge:<id>',
994
+ },
995
+ mode: {
996
+ type: 'string',
997
+ enum: ['fork', 'lite'],
998
+ description: 'fork inherits the main conversation (higher cost); lite starts fresh with the dossier. Default fork.',
999
+ },
1000
+ question: {
1001
+ type: 'string',
1002
+ description: 'Optional opening question or focus for the discussion.',
1003
+ },
1004
+ workspace: {
1005
+ type: 'string',
1006
+ description: 'Absolute local workspace root or remote:<id>; defaults to the session working directory.',
1007
+ },
1008
+ },
1009
+ required: ['target'],
1010
+ },
1011
+ output: DISCUSS_OUTPUT,
1012
+ async execute(args, exec) {
1013
+ const started = await startDiscussion({
1014
+ agent: exec.agent,
1015
+ workspace: workspaceOf(args, exec),
1016
+ target: args.target,
1017
+ mode: args.mode,
1018
+ question: args.question,
1019
+ signal: exec.signal,
1020
+ context: exec,
1021
+ })
1022
+ return {
1023
+ text: started.text,
1024
+ name: started.name,
1025
+ mode: started.mode,
1026
+ target: started.target,
1027
+ childId: started.childId,
1028
+ }
1029
+ },
1030
+ })
1031
+ return () => {
1032
+ subagents = null
1033
+ }
1034
+ })
1035
+
1036
+ // The bundled architecture-map skill teaches the agent the sync/patch/dossier
1037
+ // loop. It is optional: a profile without the skill registry still gets the
1038
+ // tools and the panel.
1039
+ ctx.inject(['skills'], scope => {
1040
+ const content = readSkillContent()
1041
+ if (content === undefined) {
1042
+ console.warn('[architecture-map] bundled skill content not found')
1043
+ return () => {}
1044
+ }
1045
+ try {
1046
+ return scope.skills.register({
1047
+ name: 'architecture-map',
1048
+ description: 'Maintain a canonical architecture graph and dossier; use arch_sync, arch_graph_get/patch, arch_doc_get/put, arch_manifest_commit, arch_discuss and arch_export.',
1049
+ whenToUse: 'When the user asks for a project architecture map, module/dependency overview, or wants to discuss one module.',
1050
+ source: 'bundled',
1051
+ content,
1052
+ resourceBase: { kind: 'directory', path: SKILL_DIR },
1053
+ })
1054
+ } catch (error) {
1055
+ console.warn('[architecture-map] bundled skill registration failed:', error)
1056
+ return () => {}
1057
+ }
1058
+ })
1059
+
1060
+ // Mermaid is served from the plugin's own origin; no CDN and no second plugin.
1061
+ // The browser half asks /config first, so renderMermaid:false leaves code fences
1062
+ // as plain code blocks without fetching the 5 MB runtime.
1063
+ ctx.inject(['webServer'], scope => {
1064
+ scope.effect(() => scope.webServer.register({
1065
+ kind: 'exact',
1066
+ path: `${RUNTIME_PATH}/config`,
1067
+ handler: serveMermaidConfig(renderMermaid, mermaidMode),
1068
+ }), 'architecture-map: mermaid config route')
1069
+ if (renderMermaid) {
1070
+ scope.effect(() => scope.webServer.register({
1071
+ kind: 'prefix',
1072
+ path: VENDOR_PREFIX,
1073
+ handler: serveVendorFile,
1074
+ }), 'architecture-map: mermaid runtime route')
1075
+ }
1076
+ return () => {}
1077
+ })
1078
+
1079
+ // The host command supplies the catalog row and the composer's command chip.
1080
+ // The client half listens for command/executed and opens the right-sidebar panel.
1081
+ // `/arch discuss` is also the UI's entry point for a node conversation.
1082
+ ctx.commands.register({
1083
+ name: 'arch',
1084
+ description: 'Open the Architecture map panel',
1085
+ // No `input` descriptor: `/arch` + Enter must execute immediately. The
1086
+ // sidebar's Discuss button still calls `/arch discuss ...` through the
1087
+ // direct commands RPC, which accepts raw input without a composer claim.
1088
+ async handler({ agent, rawInput, signal }) {
1089
+ const extra = rawInput.trim()
1090
+ if (extra === '' || extra === 'open') {
1091
+ return { kind: 'success', text: 'Architecture map opened in the right sidebar.' }
1092
+ }
1093
+ if (extra === 'remote' || extra.startsWith('remote ')) {
1094
+ return await remoteCommands.handle(extra.slice('remote'.length).trim(), agent)
1095
+ }
1096
+ const discuss = /^discuss\s+((?:node|edge):[a-z][a-z0-9_-]*)(?:\s+(fork|lite))?\s*$/.exec(extra)
1097
+ if (discuss) {
1098
+ try {
1099
+ const workspace = agent.session.header.cwd
1100
+ if (typeof workspace !== 'string' || workspace === '') {
1101
+ return { kind: 'error', text: 'the session has no working directory; pass an explicit workspace to arch_discuss' }
1102
+ }
1103
+ const started = await startDiscussion({
1104
+ agent,
1105
+ workspace,
1106
+ target: discuss[1],
1107
+ mode: discuss[2],
1108
+ signal,
1109
+ context: { agent },
1110
+ })
1111
+ return {
1112
+ kind: 'success',
1113
+ text: `${started.text} [child=${started.childId} parent=${started.parentId} mode=${started.resourceMode} target=${started.target}]`,
1114
+ }
1115
+ } catch (error) {
1116
+ return { kind: 'error', text: error?.message ?? String(error) }
1117
+ }
1118
+ }
1119
+ return {
1120
+ kind: 'error',
1121
+ text: '用法:/arch 或 /arch open(打开面板);/arch discuss node:<id> [fork|lite](开节点讨论);/arch remote add|list|select|sync|update|grant|revoke|remove ...(远程仓库)。要调用图工具,请直接发送“调用 arch_graph_get”。',
1122
+ }
1123
+ },
1124
+ })
1125
+ }