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,364 @@
1
+ /**
2
+ * Architecture map — architecture memory (node 7).
3
+ *
4
+ * `.archmap/manifest.json` records content hashes of files that have been
5
+ * analyzed. `arch_sync` compares the workspace against it and reports only
6
+ * added/changed/deleted files plus affected graph nodes; `arch_manifest_commit`
7
+ * is the explicit commit step after analysis. The dossier documents
8
+ * (`overview.md`, `modules/<id>.md`, `notes/<id>.md`) are plain Markdown.
9
+ */
10
+ import { promises as fs } from 'node:fs'
11
+ import path from 'node:path'
12
+ import { randomBytes } from 'node:crypto'
13
+ import { normalizeDataDir, resolveWorkspace } from './workspace.js'
14
+ import { isBinaryPath } from './content/local.js'
15
+
16
+ const MANIFEST_SCHEMA = 1
17
+
18
+ const DEFAULT_LIMITS = Object.freeze({
19
+ dir: '.archmap',
20
+ maxFiles: 20000,
21
+ maxFileBytes: 256 * 1024,
22
+ maxDocBytes: 32 * 1024,
23
+ })
24
+
25
+ function fail(code, message) {
26
+ const error = new Error(`${code}: ${message}`)
27
+ error.code = code
28
+ throw error
29
+ }
30
+
31
+ function normalizeRelative(value) {
32
+ if (typeof value !== 'string' || value.trim() === '') {
33
+ fail('INVALID_PATH', 'path must be a non-empty string')
34
+ }
35
+ if (path.isAbsolute(value) || value.includes('\\')) {
36
+ fail('PATH_ESCAPE', `"${value}" must be a workspace-relative POSIX path`)
37
+ }
38
+ const segments = value.split('/')
39
+ if (segments.some(segment => segment === '' || segment === '.' || segment === '..')) {
40
+ fail('PATH_ESCAPE', `"${value}" must not contain empty, "." or ".." segments`)
41
+ }
42
+ return segments.join('/')
43
+ }
44
+
45
+ function docRelative(id) {
46
+ if (typeof id !== 'string' || id.trim() === '') fail('INVALID_DOC', 'id must be a non-empty string')
47
+ if (id === 'overview') return 'overview.md'
48
+ const match = /^(modules|notes)\/([a-z0-9][a-z0-9._-]{0,63})$/.exec(id)
49
+ if (!match) {
50
+ fail('INVALID_DOC', 'id must be overview, modules/<id> or notes/<id> (lowercase id)')
51
+ }
52
+ return `${match[1]}/${match[2]}.md`
53
+ }
54
+
55
+ export function createMemoryStore(config = {}, deps = {}) {
56
+ const limits = { ...DEFAULT_LIMITS }
57
+ for (const key of Object.keys(DEFAULT_LIMITS)) {
58
+ if (config[key] !== undefined) limits[key] = config[key]
59
+ }
60
+ limits.dir = normalizeDataDir(limits.dir)
61
+ for (const key of ['maxFiles', 'maxFileBytes', 'maxDocBytes']) {
62
+ if (!Number.isInteger(limits[key]) || limits[key] <= 0) limits[key] = DEFAULT_LIMITS[key]
63
+ }
64
+ const resolveConfig = { dir: limits.dir, ssh: config.ssh }
65
+
66
+ async function scanWorkspace(ws, context, options = {}) {
67
+ if (ws.kind !== 'remote') {
68
+ const scanned = await ws.content.scan({
69
+ maxFiles: limits.maxFiles,
70
+ maxFileBytes: limits.maxFileBytes,
71
+ })
72
+ return {
73
+ ws,
74
+ root: ws.workspaceRoot,
75
+ ...scanned,
76
+ tree: new Set(scanned.files.keys()),
77
+ remote: false,
78
+ }
79
+ }
80
+ const tree = await ws.content.listTree({ maxFiles: limits.maxFiles })
81
+ const treePaths = new Set(tree.entries.map(entry => entry.path).filter(entry => !isBinaryPath(entry)))
82
+ const manifestPaths = Object.keys(options.manifest?.files ?? {}).filter(file => treePaths.has(file))
83
+ const hashes = await ws.content.hashMany(manifestPaths)
84
+ const files = new Map()
85
+ for (const file of manifestPaths) {
86
+ const hash = hashes.get(file)
87
+ if (typeof hash === 'string') files.set(file, { sha256: hash })
88
+ }
89
+ return {
90
+ ws,
91
+ root: ws.workspaceRoot,
92
+ files,
93
+ tree: treePaths,
94
+ truncated: tree.truncated,
95
+ skipped: 0,
96
+ remote: true,
97
+ }
98
+ }
99
+
100
+ async function scan(rawWorkspace, context) {
101
+ const ws = await resolveWorkspace(rawWorkspace, context, resolveConfig)
102
+ const manifest = ws.kind === 'remote' ? await readManifest(ws) : null
103
+ return scanWorkspace(ws, context, { manifest })
104
+ }
105
+
106
+ async function readManifest(ws) {
107
+ const file = path.join(ws.stateDir, 'manifest.json')
108
+ let text
109
+ try {
110
+ text = await fs.readFile(file, 'utf8')
111
+ } catch (error) {
112
+ if (error && error.code === 'ENOENT') return null
113
+ fail('IO_ERROR', `cannot read manifest: ${error.message}`)
114
+ }
115
+ let parsed
116
+ try {
117
+ parsed = JSON.parse(text)
118
+ } catch (error) {
119
+ fail('MANIFEST_CORRUPT', `manifest.json is not valid JSON (${error.message})`)
120
+ }
121
+ if (!parsed || parsed.schema !== MANIFEST_SCHEMA || typeof parsed.files !== 'object' || parsed.files === null) {
122
+ fail('MANIFEST_CORRUPT', 'manifest.json has an unsupported shape')
123
+ }
124
+ return parsed
125
+ }
126
+
127
+ async function writeManifest(ws, manifest) {
128
+ await fs.mkdir(ws.stateDir, { recursive: true })
129
+ const file = path.join(ws.stateDir, 'manifest.json')
130
+ const temp = path.join(ws.stateDir, `manifest.tmp-${process.pid}-${randomBytes(6).toString('hex')}.json`)
131
+ await fs.writeFile(temp, JSON.stringify(manifest, null, 2) + '\n', 'utf8')
132
+ await fs.rename(temp, file)
133
+ }
134
+
135
+ async function affectedNodes(ws, changedPaths, scannedFiles, context) {
136
+ if (typeof deps.readGraph !== 'function') return []
137
+ let graph
138
+ try {
139
+ graph = await deps.readGraph(ws, context)
140
+ } catch {
141
+ return []
142
+ }
143
+ const hashMismatch = anchor => {
144
+ if (typeof anchor.hash !== 'string' || anchor.hash === '') return false
145
+ const file = scannedFiles.get(anchor.path)
146
+ // Missing/skipped files are handled by the path delta; do not flag a
147
+ // binary or oversized anchor as stale just because it was not scanned.
148
+ const fileHash = file?.signature ?? file?.sha256
149
+ return file !== undefined && typeof fileHash === 'string' && fileHash !== anchor.hash
150
+ }
151
+ const hits = []
152
+ for (const node of graph.nodes) {
153
+ const anchor = (node.anchors ?? []).find(item => changedPaths.has(item.path) || hashMismatch(item))
154
+ if (anchor) hits.push({ id: node.id, title: node.title, path: anchor.path })
155
+ }
156
+ return hits
157
+ }
158
+
159
+ async function sync(rawWorkspace, input = {}, context) {
160
+ const ws = await resolveWorkspace(rawWorkspace, context, resolveConfig)
161
+ const manifest = await readManifest(ws)
162
+ const scanned = await scanWorkspace(ws, context, { manifest })
163
+ let scannedFiles = scanned.files
164
+ let baseFiles = manifest?.files ?? {}
165
+ let scannedPaths = new Set(scanned.tree ?? scannedFiles.keys())
166
+
167
+ if (Array.isArray(input.paths) && input.paths.length > 0) {
168
+ const wanted = new Set(input.paths.map(item => normalizeRelative(item)))
169
+ scannedFiles = new Map([...scannedFiles].filter(([key]) => wanted.has(key)))
170
+ baseFiles = Object.fromEntries(Object.entries(baseFiles).filter(([key]) => wanted.has(key)))
171
+ scannedPaths = new Set([...scannedPaths].filter(path => wanted.has(path)))
172
+ }
173
+
174
+ const mode = !manifest || input.full === true ? 'full' : 'incremental'
175
+ const added = []
176
+ const changed = []
177
+ const cosmetic = []
178
+ const deleted = []
179
+ if (mode === 'full') {
180
+ added.push(...scannedPaths)
181
+ } else {
182
+ for (const file of scannedPaths) {
183
+ const previous = baseFiles[file]
184
+ if (!previous) {
185
+ added.push(file)
186
+ continue
187
+ }
188
+ const info = scannedFiles.get(file)
189
+ if (!info) continue
190
+ if (previous.sha256 !== info.sha256
191
+ || (info.size !== undefined && previous.size !== undefined && previous.size !== info.size)) {
192
+ changed.push(file)
193
+ if (previous.signature !== undefined && previous.signature === info.signature) {
194
+ cosmetic.push(file)
195
+ }
196
+ }
197
+ }
198
+ for (const file of Object.keys(baseFiles)) {
199
+ if (!scannedPaths.has(file)) deleted.push(file)
200
+ }
201
+ }
202
+
203
+ added.sort()
204
+ changed.sort()
205
+ cosmetic.sort()
206
+ deleted.sort()
207
+ const cosmeticSet = new Set(cosmetic)
208
+ const changedCode = changed.filter(file => !cosmeticSet.has(file))
209
+ const affected = await affectedNodes(ws, new Set([...added, ...changedCode, ...deleted]), scanned.files, context)
210
+
211
+ let marked = []
212
+ let graphRev = null
213
+ const lines = [
214
+ `workspace: ${ws.display}`,
215
+ `mode: ${mode}${manifest ? '' : ' (no manifest yet)'}`,
216
+ `${scannedPaths.size} scanned · ${added.length} added · ${changed.length} changed (${changedCode.length} code, ${cosmetic.length} cosmetic) · ${deleted.length} deleted`,
217
+ ]
218
+ if (mode === 'full' && manifest) lines.push('full:true ignores the manifest and lists every scannable file.')
219
+ const section = (title, values) => {
220
+ if (values.length === 0) return
221
+ lines.push(`${title}:`)
222
+ for (const value of values.slice(0, 100)) lines.push(` ${value}`)
223
+ if (values.length > 100) lines.push(` … ${values.length - 100} more ${title}`)
224
+ }
225
+ section('added', added)
226
+ section('changed (code)', changedCode)
227
+ section('changed (format/comment-only)', cosmetic)
228
+ section('deleted', deleted)
229
+ if (affected.length > 0) {
230
+ lines.push('affected nodes:')
231
+ for (const node of affected.slice(0, 100)) lines.push(` ${node.id} "${node.title}" — ${node.path}`)
232
+ if (affected.length > 100) lines.push(` … ${affected.length - 100} more nodes`)
233
+ }
234
+ if (scanned.truncated) lines.push(`truncated: stopped at ${limits.maxFiles} files`)
235
+ if (scanned.skipped > 0) lines.push(`skipped ${scanned.skipped} binary/oversized file(s)`)
236
+ if (added.length + changed.length + deleted.length === 0) lines.push('no changes against the manifest')
237
+ if (mode === 'full' || !manifest) {
238
+ lines.push('after analysis, call arch_manifest_commit with the files you actually read.')
239
+ }
240
+ if (input.markStale === true) {
241
+ if (mode === 'full') {
242
+ lines.push('markStale is ignored in full mode; use an incremental sync first.')
243
+ } else if (affected.length === 0) {
244
+ lines.push('markStale: no affected nodes to mark.')
245
+ } else if (typeof deps.markStale !== 'function') {
246
+ lines.push('markStale: graph writer unavailable; nodes were not marked.')
247
+ } else {
248
+ const result = await deps.markStale(ws, affected.map(node => node.id), context)
249
+ marked = Array.isArray(result?.marked) ? result.marked : []
250
+ graphRev = Number.isInteger(result?.rev) ? result.rev : null
251
+ lines.push(`marked ${marked.length} node(s) stale${graphRev === null ? '' : ` (graph rev ${graphRev})`}`)
252
+ }
253
+ }
254
+ return {
255
+ text: lines.join('\n'),
256
+ counts: {
257
+ scanned: scannedPaths.size,
258
+ added: added.length,
259
+ changed: changed.length,
260
+ cosmetic: cosmetic.length,
261
+ deleted: deleted.length,
262
+ affected: affected.length,
263
+ marked: marked.length,
264
+ },
265
+ }
266
+ }
267
+
268
+ async function commit(rawWorkspace, input = {}, context) {
269
+ if (!Array.isArray(input.paths) || input.paths.length === 0) {
270
+ fail('INVALID_PATH', 'paths must be a non-empty array of workspace-relative files')
271
+ }
272
+ const ws = await resolveWorkspace(rawWorkspace, context, resolveConfig)
273
+ const manifest = await readManifest(ws) ?? {
274
+ schema: MANIFEST_SCHEMA,
275
+ generatedAt: null,
276
+ root: '.',
277
+ files: {},
278
+ }
279
+ const files = { ...manifest.files }
280
+ let committed = 0
281
+ let removed = 0
282
+ for (const rawPath of input.paths) {
283
+ const rel = normalizeRelative(rawPath)
284
+ try {
285
+ const info = await ws.content.describe(rel, { maxFileBytes: limits.maxFileBytes })
286
+ if (info.kind !== 'text') {
287
+ delete files[rel]
288
+ removed += 1
289
+ continue
290
+ }
291
+ files[rel] = {
292
+ sha256: info.sha256,
293
+ size: info.size,
294
+ ...(info.signature === undefined ? {} : { signature: info.signature }),
295
+ }
296
+ committed += 1
297
+ } catch {
298
+ if (rel in files) {
299
+ delete files[rel]
300
+ removed += 1
301
+ }
302
+ }
303
+ }
304
+ const next = {
305
+ schema: MANIFEST_SCHEMA,
306
+ generatedAt: new Date().toISOString(),
307
+ root: '.',
308
+ files,
309
+ }
310
+ await writeManifest(ws, next)
311
+ return {
312
+ text: `manifest updated: ${committed} committed · ${removed} removed · ${Object.keys(files).length} tracked`,
313
+ committed,
314
+ removed,
315
+ }
316
+ }
317
+
318
+ async function getDoc(rawWorkspace, id, context) {
319
+ const ws = await resolveWorkspace(rawWorkspace, context, resolveConfig)
320
+ const rel = docRelative(id)
321
+ const file = path.join(ws.stateDir, rel)
322
+ try {
323
+ const text = await fs.readFile(file, 'utf8')
324
+ return { text, found: true }
325
+ } catch (error) {
326
+ if (error && error.code === 'ENOENT') return { text: `Document "${id}" does not exist yet.`, found: false }
327
+ fail('IO_ERROR', `cannot read ${id}: ${error.message}`)
328
+ }
329
+ }
330
+
331
+ async function putDoc(rawWorkspace, input = {}, context) {
332
+ if (typeof input.content !== 'string') fail('INVALID_DOC', 'content must be a string')
333
+ if (input.content.length > limits.maxDocBytes) {
334
+ fail('LIMIT_EXCEEDED', `content is ${input.content.length} characters; the limit is ${limits.maxDocBytes}`)
335
+ }
336
+ const mode = input.mode === 'append' ? 'append' : 'overwrite'
337
+ const ws = await resolveWorkspace(rawWorkspace, context, resolveConfig)
338
+ const rel = docRelative(input.id)
339
+ const file = path.join(ws.stateDir, rel)
340
+ await fs.mkdir(path.dirname(file), { recursive: true })
341
+ let content = input.content
342
+ if (mode === 'append') {
343
+ try {
344
+ const existing = await fs.readFile(file, 'utf8')
345
+ content = existing.trimEnd() + '\n\n' + content
346
+ } catch (error) {
347
+ if (!error || error.code !== 'ENOENT') throw error
348
+ }
349
+ }
350
+ if (!content.endsWith('\n')) content += '\n'
351
+ if (content.length > limits.maxDocBytes) {
352
+ fail('LIMIT_EXCEEDED', `the resulting document would be ${content.length} characters; the limit is ${limits.maxDocBytes}`)
353
+ }
354
+ const temp = file + `.tmp-${process.pid}-${randomBytes(4).toString('hex')}`
355
+ await fs.writeFile(temp, content, 'utf8')
356
+ await fs.rename(temp, file)
357
+ return {
358
+ text: `Wrote ${input.id} (${content.length} chars, ${mode}).`,
359
+ bytes: Buffer.byteLength(content, 'utf8'),
360
+ }
361
+ }
362
+
363
+ return { scan, sync, commit, getDoc, putDoc, limits }
364
+ }