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,391 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Architecture map — remote content source (node 12).
|
|
3
|
+
*
|
|
4
|
+
* Implements the read-only content contract over an SSH client: list paths,
|
|
5
|
+
* batch-hash analyzed files, describe commit candidates, serve bounded reads,
|
|
6
|
+
* grep and compute a change fingerprint. File contents never become local
|
|
7
|
+
* files; only hashes and metadata leave the remote for sync.
|
|
8
|
+
*/
|
|
9
|
+
import { createHash } from 'node:crypto'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
import { assertRemotePath, shQuote } from './ssh.js'
|
|
12
|
+
|
|
13
|
+
const IGNORED_DIRS = new Set([
|
|
14
|
+
'.git', '.archmap', '.codegraph', 'node_modules', 'dist', 'build', 'out',
|
|
15
|
+
'vendor', 'coverage', '.next', '.turbo', '.cache',
|
|
16
|
+
])
|
|
17
|
+
|
|
18
|
+
const DEFAULTS = Object.freeze({
|
|
19
|
+
maxFiles: 20000,
|
|
20
|
+
maxFileBytes: 256 * 1024,
|
|
21
|
+
maxGrepResults: 200,
|
|
22
|
+
hashChunk: 100,
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
function contentError(code, message) {
|
|
26
|
+
const error = new Error(`${code}: ${message}`)
|
|
27
|
+
error.code = code
|
|
28
|
+
return error
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function assertRelative(value, where = 'path') {
|
|
32
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
33
|
+
throw contentError('INVALID_PATH', `${where} must be a non-empty string`)
|
|
34
|
+
}
|
|
35
|
+
if (path.posix.isAbsolute(value) || value.includes('\\') || /[\0\n\r]/.test(value)) {
|
|
36
|
+
throw contentError('PATH_ESCAPE', `${where} must be a workspace-relative POSIX path`)
|
|
37
|
+
}
|
|
38
|
+
const segments = value.split('/')
|
|
39
|
+
if (segments.some(segment => segment === '' || segment === '.' || segment === '..')) {
|
|
40
|
+
throw contentError('PATH_ESCAPE', `${where} must not contain empty, "." or ".." segments`)
|
|
41
|
+
}
|
|
42
|
+
return segments.join('/')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function ignored(rel) {
|
|
46
|
+
return rel.split('/').some(segment => IGNORED_DIRS.has(segment))
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function stripDotSlash(value) {
|
|
50
|
+
return value.startsWith('./') ? value.slice(2) : value
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function parseNulPairs(output) {
|
|
54
|
+
const parts = output.split('\0')
|
|
55
|
+
const pairs = []
|
|
56
|
+
for (let index = 0; index + 1 < parts.length; index += 2) {
|
|
57
|
+
if (parts[index] !== '') pairs.push([parts[index], parts[index + 1]])
|
|
58
|
+
}
|
|
59
|
+
return pairs
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function sha256(value) {
|
|
63
|
+
return createHash('sha256').update(value).digest('hex')
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Create the read-only remote content source.
|
|
68
|
+
* @param {object} config - `{ client, root, vcs?: 'auto'|'git'|'none', maxFiles?, maxFileBytes? }`.
|
|
69
|
+
*/
|
|
70
|
+
export function createRemoteContent(config = {}) {
|
|
71
|
+
const client = config.client
|
|
72
|
+
if (!client || typeof client.exec !== 'function' || typeof client.execShell !== 'function') {
|
|
73
|
+
throw contentError('INVALID_CONTENT', 'a remote content source needs an SSH client')
|
|
74
|
+
}
|
|
75
|
+
const root = assertRemotePath(config.root, 'remote root')
|
|
76
|
+
const maxFiles = Number.isInteger(config.maxFiles) ? config.maxFiles : DEFAULTS.maxFiles
|
|
77
|
+
const maxFileBytes = Number.isInteger(config.maxFileBytes) ? config.maxFileBytes : DEFAULTS.maxFileBytes
|
|
78
|
+
const configuredVcs = config.vcs ?? 'auto'
|
|
79
|
+
if (!['auto', 'git', 'none'].includes(configuredVcs)) {
|
|
80
|
+
throw contentError('INVALID_CONTENT', 'vcs must be auto, git or none')
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let capabilitiesPromise
|
|
84
|
+
let vcsPromise
|
|
85
|
+
|
|
86
|
+
async function capabilities() {
|
|
87
|
+
if (!capabilitiesPromise) capabilitiesPromise = client.probe()
|
|
88
|
+
return capabilitiesPromise
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function hashCommand() {
|
|
92
|
+
const caps = await capabilities()
|
|
93
|
+
if (caps.sha256sum) return 'sha256sum'
|
|
94
|
+
if (caps.shasum) return 'shasum -a 256'
|
|
95
|
+
throw contentError('HASH_UNAVAILABLE', 'remote needs sha256sum or shasum -a 256')
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
let rootRealPromise
|
|
99
|
+
async function canonicalRoot() {
|
|
100
|
+
if (!rootRealPromise) {
|
|
101
|
+
rootRealPromise = (async () => {
|
|
102
|
+
try {
|
|
103
|
+
const { stdout } = await client.exec(['readlink', '-f', '--', root])
|
|
104
|
+
const value = stdout.trim()
|
|
105
|
+
return value === '' ? root : value
|
|
106
|
+
} catch {
|
|
107
|
+
return root
|
|
108
|
+
}
|
|
109
|
+
})()
|
|
110
|
+
}
|
|
111
|
+
return rootRealPromise
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Require `$f` to resolve inside the canonical remote root. */
|
|
115
|
+
function containmentSnippet(rootReal, onFail = 'exit') {
|
|
116
|
+
const prefix = `${rootReal === '/' ? '' : rootReal}/`
|
|
117
|
+
const failure = onFail === 'continue' ? 'continue' : 'exit 6'
|
|
118
|
+
const missing = onFail === 'continue' ? 'continue' : 'exit 5'
|
|
119
|
+
return `f_real=$(readlink -f -- "$f" 2>/dev/null) || ${missing}; case "$f_real" in ${shQuote(prefix)}*) ;; *) ${failure} ;; esac;`
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function detectVcs() {
|
|
123
|
+
if (configuredVcs !== 'auto') return configuredVcs
|
|
124
|
+
if (!vcsPromise) {
|
|
125
|
+
vcsPromise = (async () => {
|
|
126
|
+
const caps = await capabilities()
|
|
127
|
+
if (!caps.git) return 'none'
|
|
128
|
+
try {
|
|
129
|
+
const { stdout } = await client.exec(['git', '-C', root, 'rev-parse', '--is-inside-work-tree'])
|
|
130
|
+
return stdout.trim() === 'true' ? 'git' : 'none'
|
|
131
|
+
} catch {
|
|
132
|
+
return 'none'
|
|
133
|
+
}
|
|
134
|
+
})()
|
|
135
|
+
}
|
|
136
|
+
return vcsPromise
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function listTree(options = {}) {
|
|
140
|
+
const limit = Number.isInteger(options.maxFiles) ? options.maxFiles : maxFiles
|
|
141
|
+
const kind = await detectVcs()
|
|
142
|
+
let stdout
|
|
143
|
+
if (kind === 'git') {
|
|
144
|
+
const result = await client.exec(['git', '-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'])
|
|
145
|
+
stdout = result.stdout
|
|
146
|
+
} else {
|
|
147
|
+
const prune = [...IGNORED_DIRS].map(name => `-name ${shQuote(name)}`).join(' -o ')
|
|
148
|
+
const script = `cd ${shQuote(root)} && find . \\( ${prune} \\) -prune -o -type f -print0`
|
|
149
|
+
const result = await client.execShell(script)
|
|
150
|
+
stdout = result.stdout
|
|
151
|
+
}
|
|
152
|
+
const entries = []
|
|
153
|
+
let truncated = false
|
|
154
|
+
for (const raw of stdout.split('\0')) {
|
|
155
|
+
if (raw === '') continue
|
|
156
|
+
const rel = stripDotSlash(raw)
|
|
157
|
+
if (rel === '' || ignored(rel) || /[\0\n\r]/.test(rel)) continue
|
|
158
|
+
if (entries.length >= limit) {
|
|
159
|
+
truncated = true
|
|
160
|
+
break
|
|
161
|
+
}
|
|
162
|
+
entries.push({ path: rel })
|
|
163
|
+
}
|
|
164
|
+
return { entries, truncated, vcs: kind }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function hashMany(rels) {
|
|
168
|
+
const wanted = [...new Set((rels ?? []).map(rel => assertRelative(rel)))]
|
|
169
|
+
if (wanted.length === 0) return new Map()
|
|
170
|
+
const command = await hashCommand()
|
|
171
|
+
const check = containmentSnippet(await canonicalRoot(), 'continue')
|
|
172
|
+
const hashes = new Map()
|
|
173
|
+
const chunkSize = DEFAULTS.hashChunk
|
|
174
|
+
for (let offset = 0; offset < wanted.length; offset += chunkSize) {
|
|
175
|
+
const chunk = wanted.slice(offset, offset + chunkSize)
|
|
176
|
+
const words = chunk.map(rel => shQuote(rel)).join(' ')
|
|
177
|
+
const script = `cd ${shQuote(root)} && for f in ${words}; do if [ -f "$f" ]; then ${check} h=$(${command} -- "$f" | cut -d' ' -f1); printf '%s\\0%s\\0' "$f" "$h"; fi; done`
|
|
178
|
+
const { stdout } = await client.execShell(script)
|
|
179
|
+
for (const [rel, hash] of parseNulPairs(stdout)) {
|
|
180
|
+
if (/^[0-9a-f]{64}$/.test(hash)) hashes.set(rel, hash)
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return hashes
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function describe(rel, options = {}) {
|
|
187
|
+
const target = assertRelative(rel)
|
|
188
|
+
const limit = Number.isInteger(options.maxFileBytes) ? options.maxFileBytes : maxFileBytes
|
|
189
|
+
const command = await hashCommand()
|
|
190
|
+
const check = containmentSnippet(await canonicalRoot())
|
|
191
|
+
const script = `cd ${shQuote(root)} && f=${shQuote(target)}; ${check} if [ ! -e "$f" ]; then printf 'missing\\n'; elif [ ! -f "$f" ]; then printf 'not-file\\n'; else s=$(wc -c < "$f" | tr -d ' '); if [ "$s" -gt ${limit} ]; then printf 'oversized %s\\n' "$s"; else t=$(tr -d '\\0' < "$f" | wc -c | tr -d ' '); if [ "$t" -ne "$s" ]; then printf 'binary %s\\n' "$s"; else h=$(${command} -- "$f" | cut -d' ' -f1); printf 'text %s %s\\n' "$s" "$h"; fi; fi; fi`
|
|
192
|
+
let stdout
|
|
193
|
+
try {
|
|
194
|
+
({ stdout } = await client.execShell(script))
|
|
195
|
+
} catch (error) {
|
|
196
|
+
if (error?.exitCode === 5) return { kind: 'missing' }
|
|
197
|
+
if (error?.exitCode === 6) throw contentError('PATH_ESCAPE', `"${target}" escapes the remote root`)
|
|
198
|
+
throw error
|
|
199
|
+
}
|
|
200
|
+
const fields = stdout.trim().split(/\s+/)
|
|
201
|
+
const kind = fields[0]
|
|
202
|
+
if (kind === 'text') {
|
|
203
|
+
return { kind, size: Number(fields[1]), sha256: fields[2] }
|
|
204
|
+
}
|
|
205
|
+
if (kind === 'oversized' || kind === 'binary') {
|
|
206
|
+
return { kind, size: Number(fields[1]) }
|
|
207
|
+
}
|
|
208
|
+
return { kind: kind === 'not-file' ? 'not-file' : 'missing' }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function readText(rel, options = {}) {
|
|
212
|
+
const target = assertRelative(rel)
|
|
213
|
+
const limit = Number.isInteger(options.maxBytes) ? options.maxBytes : maxFileBytes
|
|
214
|
+
const check = containmentSnippet(await canonicalRoot())
|
|
215
|
+
const script = `cd ${shQuote(root)} && f=${shQuote(target)}; ${check} if [ ! -f "$f" ]; then exit 4; fi; s=$(wc -c < "$f" | tr -d ' '); if [ "$s" -gt ${limit} ]; then exit 3; fi; cat -- "$f"`
|
|
216
|
+
try {
|
|
217
|
+
const { stdout } = await client.execShell(script)
|
|
218
|
+
return stdout
|
|
219
|
+
} catch (error) {
|
|
220
|
+
if (error?.exitCode === 3 || error?.exitCode === 4 || error?.exitCode === 5) return null
|
|
221
|
+
if (error?.exitCode === 6) throw contentError('PATH_ESCAPE', `"${target}" escapes the remote root`)
|
|
222
|
+
throw error
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function readRange(rel, range = {}) {
|
|
227
|
+
const target = assertRelative(rel)
|
|
228
|
+
const offset = Number.isInteger(range.offset) && range.offset >= 0 ? range.offset : 0
|
|
229
|
+
const length = Number.isInteger(range.length) && range.length > 0 ? range.length : maxFileBytes
|
|
230
|
+
const check = containmentSnippet(await canonicalRoot())
|
|
231
|
+
const script = `cd ${shQuote(root)} && f=${shQuote(target)}; ${check} if [ ! -f "$f" ]; then exit 4; fi; s=$(wc -c < "$f" | tr -d ' '); printf '%s\\n' "$s" >&2; tail -c +$(( ${offset} + 1 )) "$f" | head -c ${length}`
|
|
232
|
+
try {
|
|
233
|
+
const { stdout, stderr } = await client.execShell(script)
|
|
234
|
+
const sizeLines = [...String(stderr).matchAll(/^\s*(\d+)\s*$/gm)]
|
|
235
|
+
const size = sizeLines.length > 0 ? Number(sizeLines[sizeLines.length - 1][1]) : Number.NaN
|
|
236
|
+
const bytes = Math.max(0, Math.min(length, Number.isFinite(size) ? size - offset : length))
|
|
237
|
+
return {
|
|
238
|
+
text: stdout,
|
|
239
|
+
offset,
|
|
240
|
+
bytes,
|
|
241
|
+
eof: Number.isFinite(size) ? offset + bytes >= size : false,
|
|
242
|
+
}
|
|
243
|
+
} catch (error) {
|
|
244
|
+
if (error?.exitCode === 4 || error?.exitCode === 5) return { text: '', offset, bytes: 0, eof: true }
|
|
245
|
+
if (error?.exitCode === 6) throw contentError('PATH_ESCAPE', `"${target}" escapes the remote root`)
|
|
246
|
+
throw error
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function grep(pattern, options = {}) {
|
|
251
|
+
if (typeof pattern !== 'string' || pattern === '') {
|
|
252
|
+
throw contentError('INVALID_PATTERN', 'grep pattern must be a non-empty string')
|
|
253
|
+
}
|
|
254
|
+
const caps = await capabilities()
|
|
255
|
+
const limit = Number.isInteger(options.maxResults) ? options.maxResults : DEFAULTS.maxGrepResults
|
|
256
|
+
const target = options.path === undefined ? '.' : assertRelative(options.path)
|
|
257
|
+
const context = Number.isInteger(options.context) && options.context > 0 ? options.context : 0
|
|
258
|
+
const include = typeof options.include === 'string' && options.include !== '' ? options.include : undefined
|
|
259
|
+
const argv = caps.rg
|
|
260
|
+
? ['rg', '--no-config', '--line-number', '--color', 'never', '--no-heading',
|
|
261
|
+
...(context > 0 ? ['-C', String(context)] : []),
|
|
262
|
+
...(include ? ['-g', include] : []),
|
|
263
|
+
'-e', pattern, '--', target]
|
|
264
|
+
: ['grep', '-rInI',
|
|
265
|
+
...(context > 0 ? ['-C', String(context)] : []),
|
|
266
|
+
...(include ? ['--include', include] : []),
|
|
267
|
+
'-e', pattern, '--', target]
|
|
268
|
+
const script = `cd ${shQuote(root)} && ${argv.map(shQuote).join(' ')}`
|
|
269
|
+
let stdout
|
|
270
|
+
try {
|
|
271
|
+
({ stdout } = await client.execShell(script))
|
|
272
|
+
} catch (error) {
|
|
273
|
+
if (error?.exitCode === 1) return { matches: [], truncated: false, engine: caps.rg ? 'rg' : 'grep' }
|
|
274
|
+
throw error
|
|
275
|
+
}
|
|
276
|
+
const matches = []
|
|
277
|
+
let truncated = false
|
|
278
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
279
|
+
if (line === '') continue
|
|
280
|
+
const first = line.indexOf(':')
|
|
281
|
+
const second = first >= 0 ? line.indexOf(':', first + 1) : -1
|
|
282
|
+
if (second < 0) continue
|
|
283
|
+
const file = line.slice(0, first)
|
|
284
|
+
const lineNumber = Number(line.slice(first + 1, second))
|
|
285
|
+
if (!Number.isInteger(lineNumber)) continue
|
|
286
|
+
if (matches.length >= limit) {
|
|
287
|
+
truncated = true
|
|
288
|
+
break
|
|
289
|
+
}
|
|
290
|
+
matches.push({ path: stripDotSlash(file), line: lineNumber, text: line.slice(second + 1) })
|
|
291
|
+
}
|
|
292
|
+
return { matches, truncated, engine: caps.rg ? 'rg' : 'grep' }
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function stat(rel) {
|
|
296
|
+
const target = assertRelative(rel)
|
|
297
|
+
const check = containmentSnippet(await canonicalRoot())
|
|
298
|
+
const script = `cd ${shQuote(root)} && f=${shQuote(target)}; ${check} if [ -f "$f" ]; then printf 'file %s\\n' "$(wc -c < "$f" | tr -d ' ')"; elif [ -d "$f" ]; then printf 'directory 0\\n'; else printf 'missing\\n'; fi`
|
|
299
|
+
let stdout
|
|
300
|
+
try {
|
|
301
|
+
({ stdout } = await client.execShell(script))
|
|
302
|
+
} catch (error) {
|
|
303
|
+
if (error?.exitCode === 5) return null
|
|
304
|
+
if (error?.exitCode === 6) throw contentError('PATH_ESCAPE', `"${target}" escapes the remote root`)
|
|
305
|
+
throw error
|
|
306
|
+
}
|
|
307
|
+
const fields = stdout.trim().split(/\s+/)
|
|
308
|
+
if (fields[0] === 'file') return { type: 'file', size: Number(fields[1]) }
|
|
309
|
+
if (fields[0] === 'directory') return { type: 'directory', size: 0 }
|
|
310
|
+
return null
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function fingerprint() {
|
|
314
|
+
const kind = await detectVcs()
|
|
315
|
+
if (kind === 'git') {
|
|
316
|
+
let head = null
|
|
317
|
+
try {
|
|
318
|
+
const result = await client.exec(['git', '-C', root, 'rev-parse', 'HEAD'])
|
|
319
|
+
head = result.stdout.trim() || null
|
|
320
|
+
} catch {
|
|
321
|
+
head = null
|
|
322
|
+
}
|
|
323
|
+
const status = await client.exec(['git', '-C', root, 'status', '--porcelain=v1', '-z', '--untracked-files=all'])
|
|
324
|
+
// A dirty path can change again without changing `git status`; include
|
|
325
|
+
// content hashes for changed/untracked paths so the digest moves.
|
|
326
|
+
const changedPaths = []
|
|
327
|
+
try {
|
|
328
|
+
const changed = await client.exec(['git', '-C', root, 'diff', '--name-only', '-z', 'HEAD'])
|
|
329
|
+
changedPaths.push(...changed.stdout.split('\0').filter(Boolean))
|
|
330
|
+
} catch {}
|
|
331
|
+
try {
|
|
332
|
+
const untracked = await client.exec(['git', '-C', root, 'ls-files', '--others', '--exclude-standard', '-z'])
|
|
333
|
+
changedPaths.push(...untracked.stdout.split('\0').filter(Boolean))
|
|
334
|
+
} catch {}
|
|
335
|
+
const safePaths = [...new Set(changedPaths)].filter(rel =>
|
|
336
|
+
typeof rel === 'string'
|
|
337
|
+
&& rel !== ''
|
|
338
|
+
&& !rel.startsWith('/')
|
|
339
|
+
&& !rel.split('/').includes('..')
|
|
340
|
+
&& !/[\0\n\r]/.test(rel))
|
|
341
|
+
const hashes = await hashMany(safePaths)
|
|
342
|
+
const changedDigest = safePaths
|
|
343
|
+
.map(rel => `${rel}\0${hashes.get(rel) ?? ''}`)
|
|
344
|
+
.sort()
|
|
345
|
+
.join('\0')
|
|
346
|
+
return {
|
|
347
|
+
vcs: 'git',
|
|
348
|
+
head,
|
|
349
|
+
dirty: status.stdout !== '',
|
|
350
|
+
digest: sha256(`${head ?? ''}\0${status.stdout}\0${changedDigest}`),
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
// Non-git fingerprints use path + size + mtime metadata only. No content is
|
|
354
|
+
// read or hashed for change detection.
|
|
355
|
+
const prune = [...IGNORED_DIRS].map(name => `-name ${shQuote(name)}`).join(' -o ')
|
|
356
|
+
const script = `cd ${shQuote(root)} || exit 1; if find . -maxdepth 0 -printf '' >/dev/null 2>&1; then find . \\( ${prune} \\) -prune -o -type f -printf '%P\\0%s\\0%T@\\0'; elif stat -c '%n' . >/dev/null 2>&1; then find . \\( ${prune} \\) -prune -o -type f -exec stat -c '%n\\0%s\\0%Y\\0' {} +; else find . \\( ${prune} \\) -prune -o -type f -exec stat -f '%N\\0%z\\0%m\\0' {} +; fi`
|
|
357
|
+
const { stdout } = await client.execShell(script)
|
|
358
|
+
const parts = stdout.split('\0')
|
|
359
|
+
const entries = []
|
|
360
|
+
for (let index = 0; index + 2 < parts.length; index += 3) {
|
|
361
|
+
const rel = stripDotSlash(parts[index])
|
|
362
|
+
if (rel === '' || ignored(rel) || /[\0\n\r]/.test(rel)) continue
|
|
363
|
+
entries.push({ path: rel, size: parts[index + 1], mtime: parts[index + 2] })
|
|
364
|
+
}
|
|
365
|
+
return {
|
|
366
|
+
vcs: 'none',
|
|
367
|
+
head: null,
|
|
368
|
+
dirty: null,
|
|
369
|
+
digest: sha256(entries
|
|
370
|
+
.map(entry => `${entry.path}\0${entry.size}\0${entry.mtime}`)
|
|
371
|
+
.sort()
|
|
372
|
+
.join('\0')),
|
|
373
|
+
entries: entries.length,
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
return {
|
|
378
|
+
kind: 'remote',
|
|
379
|
+
root,
|
|
380
|
+
hashMode: 'sha256',
|
|
381
|
+
detectVcs,
|
|
382
|
+
listTree,
|
|
383
|
+
hashMany,
|
|
384
|
+
describe,
|
|
385
|
+
readText,
|
|
386
|
+
readRange,
|
|
387
|
+
grep,
|
|
388
|
+
stat,
|
|
389
|
+
fingerprint,
|
|
390
|
+
}
|
|
391
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Architecture map — remote change indexer (node 15).
|
|
3
|
+
*
|
|
4
|
+
* Polls tracked remote projects with a cheap fingerprint, runs the existing
|
|
5
|
+
* manifest-only sync when it changes, writes `remote-state.json` and hands the
|
|
6
|
+
* change counts to the auto-maintainer. Polling never reads file content for
|
|
7
|
+
* the model and never writes remotely.
|
|
8
|
+
*/
|
|
9
|
+
import { emptyRemoteState, readRemoteState, writeRemoteState } from './state.js'
|
|
10
|
+
|
|
11
|
+
const DEFAULT_INTERVAL_MS = 60_000
|
|
12
|
+
const DEFAULT_MAX_BACKOFF_MS = 15 * 60_000
|
|
13
|
+
const DEFAULT_MAX_FAILURES = 6
|
|
14
|
+
|
|
15
|
+
function projectKey(ws) {
|
|
16
|
+
return `${ws.pathBase}\0${ws.id}`
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function countTotal(counts) {
|
|
20
|
+
return (counts?.added ?? 0) + (counts?.changed ?? 0) + (counts?.deleted ?? 0)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function iso(ms) {
|
|
24
|
+
return new Date(ms).toISOString()
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {object} options - `{ memory, maintainer?, now?, intervalMs? }`.
|
|
29
|
+
*/
|
|
30
|
+
export function createRemoteIndexer(options = {}) {
|
|
31
|
+
const memory = options.memory
|
|
32
|
+
const maintainer = options.maintainer ?? null
|
|
33
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now()
|
|
34
|
+
const intervalMs = Number.isInteger(options.intervalMs) ? options.intervalMs : DEFAULT_INTERVAL_MS
|
|
35
|
+
const scheduleFn = options.setTimeout ?? setTimeout
|
|
36
|
+
const cancelFn = options.clearTimeout ?? clearTimeout
|
|
37
|
+
const entries = new Map()
|
|
38
|
+
let disposed = false
|
|
39
|
+
|
|
40
|
+
function contextOf(context) {
|
|
41
|
+
return context ?? undefined
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function check(ws, context, settings = {}) {
|
|
45
|
+
if (!ws || ws.kind !== 'remote' || !ws.content) {
|
|
46
|
+
throw new Error('REMOTE_INDEXER: a remote workspace with content is required')
|
|
47
|
+
}
|
|
48
|
+
const checkedAt = iso(now())
|
|
49
|
+
const fingerprint = await ws.content.fingerprint()
|
|
50
|
+
const previous = await readRemoteState(ws)
|
|
51
|
+
const base = previous ?? emptyRemoteState(ws)
|
|
52
|
+
if (!previous?.fingerprint?.digest) {
|
|
53
|
+
const state = await writeRemoteState(ws, {
|
|
54
|
+
...base,
|
|
55
|
+
fingerprint,
|
|
56
|
+
lastCheckedAt: checkedAt,
|
|
57
|
+
lastError: null,
|
|
58
|
+
})
|
|
59
|
+
return { changed: false, first: true, state }
|
|
60
|
+
}
|
|
61
|
+
if (previous.fingerprint.digest === fingerprint.digest) {
|
|
62
|
+
const state = await writeRemoteState(ws, {
|
|
63
|
+
...base,
|
|
64
|
+
fingerprint,
|
|
65
|
+
lastCheckedAt: checkedAt,
|
|
66
|
+
lastError: null,
|
|
67
|
+
})
|
|
68
|
+
return { changed: false, first: false, state }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const sync = await memory.sync(ws, { markStale: true }, contextOf(context))
|
|
72
|
+
const counts = sync.counts
|
|
73
|
+
const total = countTotal(counts)
|
|
74
|
+
const pendingSince = total > 0 ? (previous.pending?.since ?? checkedAt) : null
|
|
75
|
+
let state = await writeRemoteState(ws, {
|
|
76
|
+
...base,
|
|
77
|
+
fingerprint,
|
|
78
|
+
lastCheckedAt: checkedAt,
|
|
79
|
+
lastIndexedAt: checkedAt,
|
|
80
|
+
pending: { added: counts.added, changed: counts.changed, deleted: counts.deleted, count: total, since: pendingSince },
|
|
81
|
+
syncState: 'idle',
|
|
82
|
+
lastError: null,
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
let maintenance = null
|
|
86
|
+
if (maintainer && total > 0 && settings.maintainer !== false) {
|
|
87
|
+
maintenance = await maintainer.maybeRun(ws, contextOf(context), counts, state)
|
|
88
|
+
if (maintenance?.started) {
|
|
89
|
+
state = await writeRemoteState(ws, {
|
|
90
|
+
...state,
|
|
91
|
+
syncState: 'maintaining',
|
|
92
|
+
lastMaintainerAt: checkedAt,
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return { changed: true, first: false, counts, state, maintenance }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function run(entry) {
|
|
100
|
+
if (entry.running) return entry.current
|
|
101
|
+
entry.running = true
|
|
102
|
+
entry.current = (async () => {
|
|
103
|
+
try {
|
|
104
|
+
const result = await check(entry.ws, entry.context)
|
|
105
|
+
entry.failures = 0
|
|
106
|
+
return result
|
|
107
|
+
} catch (error) {
|
|
108
|
+
entry.failures = Math.min(entry.failures + 1, DEFAULT_MAX_FAILURES)
|
|
109
|
+
const previous = await readRemoteState(entry.ws).catch(() => null)
|
|
110
|
+
await writeRemoteState(entry.ws, {
|
|
111
|
+
...(previous ?? emptyRemoteState(entry.ws)),
|
|
112
|
+
lastCheckedAt: iso(now()),
|
|
113
|
+
lastError: String(error?.message ?? error),
|
|
114
|
+
}).catch(() => {})
|
|
115
|
+
return { error }
|
|
116
|
+
} finally {
|
|
117
|
+
entry.running = false
|
|
118
|
+
if (!disposed && intervalMs > 0) schedule(entry)
|
|
119
|
+
}
|
|
120
|
+
})()
|
|
121
|
+
return entry.current
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function schedule(entry) {
|
|
125
|
+
if (disposed || intervalMs <= 0) return
|
|
126
|
+
if (entry.timer) cancelFn(entry.timer)
|
|
127
|
+
const backoff = entry.failures > 0
|
|
128
|
+
? Math.min(intervalMs * 2 ** entry.failures, DEFAULT_MAX_BACKOFF_MS)
|
|
129
|
+
: intervalMs
|
|
130
|
+
entry.timer = scheduleFn(() => {
|
|
131
|
+
entry.timer = null
|
|
132
|
+
void run(entry)
|
|
133
|
+
}, backoff)
|
|
134
|
+
entry.timer?.unref?.()
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Start (or refresh) polling for one remote project. */
|
|
138
|
+
function track(ws, context, settings = {}) {
|
|
139
|
+
if (disposed) throw new Error('REMOTE_INDEXER: the indexer is disposed')
|
|
140
|
+
if (!ws || ws.kind !== 'remote') throw new Error('REMOTE_INDEXER: a remote workspace is required')
|
|
141
|
+
const key = projectKey(ws)
|
|
142
|
+
let entry = entries.get(key)
|
|
143
|
+
if (!entry) {
|
|
144
|
+
entry = { ws, context, timer: null, running: false, current: null, failures: 0 }
|
|
145
|
+
entries.set(key, entry)
|
|
146
|
+
}
|
|
147
|
+
entry.ws = ws
|
|
148
|
+
entry.context = context
|
|
149
|
+
if (settings.immediate !== false) void run(entry)
|
|
150
|
+
else if (!entry.timer) schedule(entry)
|
|
151
|
+
return entry
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function untrack(ws) {
|
|
155
|
+
const key = projectKey(ws)
|
|
156
|
+
const entry = entries.get(key)
|
|
157
|
+
if (!entry) return false
|
|
158
|
+
if (entry.timer) cancelFn(entry.timer)
|
|
159
|
+
entries.delete(key)
|
|
160
|
+
return true
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function status(ws) {
|
|
164
|
+
return readRemoteState(ws)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function dispose() {
|
|
168
|
+
disposed = true
|
|
169
|
+
for (const entry of entries.values()) {
|
|
170
|
+
if (entry.timer) cancelFn(entry.timer)
|
|
171
|
+
}
|
|
172
|
+
entries.clear()
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function tracked() {
|
|
176
|
+
return [...entries.keys()]
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return { track, untrack, check, status, dispose, tracked, intervalMs }
|
|
180
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Architecture map — remote auto-maintainer (node 16).
|
|
3
|
+
*
|
|
4
|
+
* Decides when a changed remote project may start a maintenance child. The
|
|
5
|
+
* child is a normal DSH subagent; the plugin supplies `startChild`. Consent,
|
|
6
|
+
* file-count, cooldown and single-flight limits live here.
|
|
7
|
+
*/
|
|
8
|
+
export const MAINTAINER_LIMITS = Object.freeze({
|
|
9
|
+
maxFiles: 50,
|
|
10
|
+
minIntervalMs: 10 * 60 * 1000,
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
export function buildMaintainerPrompt(ws, counts) {
|
|
14
|
+
const id = ws.id
|
|
15
|
+
const host = ws.project?.host ?? 'remote'
|
|
16
|
+
const root = ws.project?.root ?? ''
|
|
17
|
+
return [
|
|
18
|
+
`You are the remote architecture maintainer for remote:${id} (${host}:${root}).`,
|
|
19
|
+
`The remote changed: +${counts.added} added, ~${counts.changed} changed, -${counts.deleted} deleted.`,
|
|
20
|
+
'',
|
|
21
|
+
'Steps:',
|
|
22
|
+
`1. Call arch_sync({ workspace: "remote:${id}", markStale: true }) to refresh the pending set.`,
|
|
23
|
+
'2. Read only the changed files with arch_remote_read / arch_remote_grep. Never use local read, grep, glob or bash for this workspace.',
|
|
24
|
+
'3. Update only affected node summaries, anchors, edges and dossier docs; keep stable ids.',
|
|
25
|
+
'4. Call arch_manifest_commit with the files you actually analyzed.',
|
|
26
|
+
'5. Do not write remote files. Do not touch unrelated nodes. Finish with one short summary.',
|
|
27
|
+
].join('\n')
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function projectKey(ws) {
|
|
31
|
+
return `${ws.pathBase}\0${ws.id}`
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function totalOf(counts) {
|
|
35
|
+
return (counts?.added ?? 0) + (counts?.changed ?? 0) + (counts?.deleted ?? 0)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {object} options - `{ consent, startChild, now?, maxFiles?, minIntervalMs? }`.
|
|
40
|
+
*/
|
|
41
|
+
export function createMaintainer(options = {}) {
|
|
42
|
+
const consent = options.consent
|
|
43
|
+
const startChild = options.startChild
|
|
44
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now()
|
|
45
|
+
const maxFiles = Number.isInteger(options.maxFiles) ? options.maxFiles : MAINTAINER_LIMITS.maxFiles
|
|
46
|
+
const minIntervalMs = Number.isInteger(options.minIntervalMs) ? options.minIntervalMs : MAINTAINER_LIMITS.minIntervalMs
|
|
47
|
+
const running = new Set()
|
|
48
|
+
|
|
49
|
+
async function maybeRun(ws, context, counts, state = {}, settings = {}) {
|
|
50
|
+
const total = totalOf(counts)
|
|
51
|
+
if (total === 0) return { started: false, reason: 'no-changes' }
|
|
52
|
+
if (!consent || typeof consent.autoMaintenanceAllowed !== 'function' || !consent.autoMaintenanceAllowed(ws)) {
|
|
53
|
+
return { started: false, reason: 'no-workspace-consent' }
|
|
54
|
+
}
|
|
55
|
+
if (total > maxFiles) return { started: false, reason: 'too-many-files', total, maxFiles }
|
|
56
|
+
const agent = context?.agent ?? context
|
|
57
|
+
if (!agent) return { started: false, reason: 'no-agent' }
|
|
58
|
+
const key = projectKey(ws)
|
|
59
|
+
if (running.has(key)) return { started: false, reason: 'already-running' }
|
|
60
|
+
const last = Date.parse(state.lastMaintainerAt ?? '')
|
|
61
|
+
if (!settings.force && Number.isFinite(last) && now() - last < minIntervalMs) {
|
|
62
|
+
return { started: false, reason: 'cooldown', retryAfterMs: minIntervalMs - (now() - last) }
|
|
63
|
+
}
|
|
64
|
+
if (typeof startChild !== 'function') return { started: false, reason: 'no-child-runner' }
|
|
65
|
+
running.add(key)
|
|
66
|
+
try {
|
|
67
|
+
const child = await startChild({ ws, agent, counts })
|
|
68
|
+
return {
|
|
69
|
+
started: true,
|
|
70
|
+
childId: String(child?.childId ?? child?.id ?? ''),
|
|
71
|
+
name: child?.name,
|
|
72
|
+
}
|
|
73
|
+
} catch (error) {
|
|
74
|
+
return { started: false, reason: 'start-failed', error }
|
|
75
|
+
} finally {
|
|
76
|
+
running.delete(key)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function isRunning(ws) {
|
|
81
|
+
return running.has(projectKey(ws))
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return { maybeRun, isRunning, limits: { maxFiles, minIntervalMs } }
|
|
85
|
+
}
|