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,287 @@
1
+ /**
2
+ * Architecture map — read-only SSH transport (node 11).
3
+ *
4
+ * One client owns an OpenSSH connection recipe: fixed options, optional
5
+ * ControlMaster reuse, bounded concurrency, a per-command timeout, abort
6
+ * handling, output caps, POSIX quoting and a small capability probe. It never
7
+ * adds a remote write command; callers pass the exact remote command.
8
+ */
9
+ import { spawn } from 'node:child_process'
10
+ import { createHash } from 'node:crypto'
11
+ import os from 'node:os'
12
+ import path from 'node:path'
13
+
14
+ export const SSH_DEFAULTS = Object.freeze({
15
+ connectTimeoutMs: 10_000,
16
+ requestTimeoutMs: 30_000,
17
+ maxOutputBytes: 4 * 1024 * 1024,
18
+ maxPending: 4,
19
+ })
20
+
21
+ function sshError(code, message) {
22
+ const error = new Error(`${code}: ${message}`)
23
+ error.code = code
24
+ return error
25
+ }
26
+
27
+ /** Quote one argument for the remote POSIX shell. */
28
+ export function shQuote(value) {
29
+ if (typeof value !== 'string') throw sshError('INVALID_ARGUMENT', 'ssh arguments must be strings')
30
+ if (value.includes('\0')) throw sshError('INVALID_ARGUMENT', 'ssh arguments must not contain NUL')
31
+ return `'${value.replace(/'/g, "'\\''")}'`
32
+ }
33
+
34
+ /** Validate an OpenSSH destination (`user@host`, host alias, or bracketed IPv6). */
35
+ export function assertHost(host) {
36
+ if (typeof host !== 'string' || host.trim() === '') {
37
+ throw sshError('INVALID_HOST', 'ssh host must be a non-empty string')
38
+ }
39
+ if (host !== host.trim() || /[\0\n\r\s]/.test(host) || host.startsWith('-')) {
40
+ throw sshError('INVALID_HOST', `ssh host ${JSON.stringify(host)} is not a plain OpenSSH destination`)
41
+ }
42
+ return host
43
+ }
44
+
45
+ /** Validate and normalize an absolute POSIX path used as a remote root. */
46
+ export function assertRemotePath(value, where = 'path') {
47
+ if (typeof value !== 'string' || value.trim() === '') {
48
+ throw sshError('INVALID_PATH', `${where} must be a non-empty string`)
49
+ }
50
+ if (!value.startsWith('/') || value.includes('\\') || /[\0\n\r]/.test(value)) {
51
+ throw sshError('PATH_ESCAPE', `${where} must be an absolute POSIX path without control characters`)
52
+ }
53
+ const normalized = value.replace(/\/{2,}/g, '/').replace(/(.)\/+$/, '$1')
54
+ if (normalized.split('/').some(segment => segment === '..')) {
55
+ throw sshError('PATH_ESCAPE', `${where} must not contain ".."`)
56
+ }
57
+ return normalized
58
+ }
59
+
60
+ function controlPathFor(host) {
61
+ const digest = createHash('sha256').update(host).digest('hex').slice(0, 12)
62
+ return path.join(os.tmpdir(), `dsh-archmap-ssh-${digest}.sock`)
63
+ }
64
+
65
+ function stderrSummary(text, limit = 400) {
66
+ const clean = String(text ?? '').trim().replace(/\s+/g, ' ')
67
+ return clean.length > limit ? `${clean.slice(0, limit)}…` : clean
68
+ }
69
+
70
+ function classify(stderr, exitCode) {
71
+ if (/host key verification failed/i.test(stderr)) return 'SSH_HOST_KEY'
72
+ if (/permission denied|publickey|authentication failed/i.test(stderr)) return 'SSH_CONNECTION_FAILED'
73
+ if (/could not resolve hostname|name or service not known|nodename nor servname/i.test(stderr)) return 'SSH_HOST_UNKNOWN'
74
+ return exitCode === 255 ? 'SSH_CONNECTION_FAILED' : 'SSH_COMMAND_FAILED'
75
+ }
76
+
77
+ /**
78
+ * Create a read-only SSH client.
79
+ * @param {object} config - `{ host, binary?, connectTimeoutMs?, requestTimeoutMs?, maxOutputBytes?, maxPending?, controlMaster?, controlPath?, env? }`.
80
+ * @returns `{ host, controlPath, run, exec, execShell, probe }`.
81
+ */
82
+ export function createSshClient(config = {}) {
83
+ const host = assertHost(config.host)
84
+ const binary = typeof config.binary === 'string' && config.binary !== '' ? config.binary : 'ssh'
85
+ const connectTimeoutMs = Number.isInteger(config.connectTimeoutMs) ? config.connectTimeoutMs : SSH_DEFAULTS.connectTimeoutMs
86
+ const requestTimeoutMs = Number.isInteger(config.requestTimeoutMs) ? config.requestTimeoutMs : SSH_DEFAULTS.requestTimeoutMs
87
+ const maxOutputBytes = Number.isInteger(config.maxOutputBytes) ? config.maxOutputBytes : SSH_DEFAULTS.maxOutputBytes
88
+ const maxPending = Number.isInteger(config.maxPending) && config.maxPending > 0 ? config.maxPending : SSH_DEFAULTS.maxPending
89
+ const env = { ...process.env, LC_ALL: 'C', ...(config.env ?? {}) }
90
+ const controlPath = config.controlPath ?? controlPathFor(host)
91
+
92
+ const baseArgs = [
93
+ '-o', 'BatchMode=yes',
94
+ '-o', `ConnectTimeout=${Math.max(1, Math.ceil(connectTimeoutMs / 1000))}`,
95
+ '-o', 'ServerAliveInterval=15',
96
+ ]
97
+ if (config.controlMaster !== false) {
98
+ baseArgs.push('-o', 'ControlMaster=auto', '-o', `ControlPath=${controlPath}`, '-o', 'ControlPersist=300')
99
+ }
100
+
101
+ let active = 0
102
+ const queue = []
103
+
104
+ function acquire(signal) {
105
+ if (signal?.aborted) return Promise.reject(sshError('SSH_ABORTED', `${host}: command aborted`))
106
+ if (active < maxPending) {
107
+ active += 1
108
+ return Promise.resolve()
109
+ }
110
+ return new Promise((resolve, reject) => {
111
+ const waiter = { resolve, reject, signal, onAbort: undefined }
112
+ waiter.onAbort = () => {
113
+ const index = queue.indexOf(waiter)
114
+ if (index >= 0) queue.splice(index, 1)
115
+ reject(sshError('SSH_ABORTED', `${host}: command aborted`))
116
+ }
117
+ signal?.addEventListener('abort', waiter.onAbort, { once: true })
118
+ queue.push(waiter)
119
+ })
120
+ }
121
+
122
+ function release() {
123
+ active = Math.max(0, active - 1)
124
+ const next = queue.shift()
125
+ if (next) {
126
+ active += 1
127
+ next.signal?.removeEventListener('abort', next.onAbort)
128
+ next.resolve()
129
+ }
130
+ }
131
+
132
+ function run(command, options = {}) {
133
+ if (typeof command !== 'string' || command === '' || command.includes('\0')) {
134
+ return Promise.reject(sshError('INVALID_COMMAND', 'remote command must be a non-empty string without NUL'))
135
+ }
136
+ const timeoutMs = Number.isInteger(options.timeoutMs) ? options.timeoutMs : requestTimeoutMs
137
+ const outputLimit = Number.isInteger(options.maxOutputBytes) ? options.maxOutputBytes : maxOutputBytes
138
+ const signal = options.signal
139
+
140
+ return (async () => {
141
+ await acquire(signal)
142
+ let released = false
143
+ const releaseOnce = () => {
144
+ if (released) return
145
+ released = true
146
+ release()
147
+ }
148
+ try {
149
+ return await new Promise((resolve, reject) => {
150
+ let child
151
+ try {
152
+ child = spawn(binary, [...baseArgs, host, command], {
153
+ env,
154
+ stdio: ['ignore', 'pipe', 'pipe'],
155
+ windowsHide: true,
156
+ })
157
+ } catch (error) {
158
+ reject(sshError('SSH_IO_ERROR', `${host}: cannot start ${binary}: ${error.message}`))
159
+ return
160
+ }
161
+
162
+ let stdout = Buffer.alloc(0)
163
+ let stderr = Buffer.alloc(0)
164
+ let settled = false
165
+ let timer
166
+ let killTimer
167
+ let onAbort
168
+
169
+ const cleanup = () => {
170
+ if (timer) clearTimeout(timer)
171
+ if (killTimer) clearTimeout(killTimer)
172
+ if (onAbort) signal?.removeEventListener('abort', onAbort)
173
+ }
174
+ const finish = (error, value) => {
175
+ if (settled) return
176
+ settled = true
177
+ cleanup()
178
+ releaseOnce()
179
+ if (error) reject(error)
180
+ else resolve(value)
181
+ }
182
+ const kill = () => {
183
+ try {
184
+ child.kill('SIGTERM')
185
+ } catch {
186
+ // Already gone.
187
+ }
188
+ killTimer = setTimeout(() => {
189
+ try {
190
+ child.kill('SIGKILL')
191
+ } catch {
192
+ // Already gone.
193
+ }
194
+ }, 2_000)
195
+ killTimer.unref?.()
196
+ }
197
+
198
+ child.stdout.on('data', chunk => {
199
+ stdout = Buffer.concat([stdout, chunk])
200
+ if (stdout.length > outputLimit) {
201
+ kill()
202
+ finish(sshError('SSH_OUTPUT_LIMIT', `${host}: stdout exceeded ${outputLimit} bytes`))
203
+ }
204
+ })
205
+ child.stderr.on('data', chunk => {
206
+ stderr = Buffer.concat([stderr, chunk])
207
+ if (stderr.length > outputLimit) {
208
+ kill()
209
+ finish(sshError('SSH_OUTPUT_LIMIT', `${host}: stderr exceeded ${outputLimit} bytes`))
210
+ }
211
+ })
212
+ child.on('error', error => {
213
+ if (error && error.code === 'ENOENT') {
214
+ finish(sshError('SSH_UNAVAILABLE', `ssh binary ${JSON.stringify(binary)} was not found`))
215
+ } else {
216
+ finish(sshError('SSH_IO_ERROR', `${host}: ${error?.message ?? String(error)}`))
217
+ }
218
+ })
219
+ child.on('close', code => {
220
+ if (settled) return
221
+ if (code === 0) {
222
+ finish(null, { stdout: stdout.toString('utf8'), stderr: stderr.toString('utf8'), code: 0 })
223
+ return
224
+ }
225
+ const text = stderr.toString('utf8')
226
+ const codeId = classify(text, code)
227
+ const detail = stderrSummary(text) || `ssh exited ${code}`
228
+ const error = sshError(codeId, `${host}: ${detail}`)
229
+ error.exitCode = code
230
+ error.stderr = text
231
+ finish(error)
232
+ })
233
+
234
+ timer = setTimeout(() => {
235
+ kill()
236
+ finish(sshError('SSH_TIMEOUT', `${host}: command timed out after ${timeoutMs}ms`))
237
+ }, timeoutMs)
238
+
239
+ if (signal) {
240
+ onAbort = () => {
241
+ kill()
242
+ finish(sshError('SSH_ABORTED', `${host}: command aborted`))
243
+ }
244
+ if (signal.aborted) onAbort()
245
+ else signal.addEventListener('abort', onAbort, { once: true })
246
+ }
247
+ })
248
+ } catch (error) {
249
+ releaseOnce()
250
+ throw error
251
+ }
252
+ })()
253
+ }
254
+
255
+ function exec(argv, options = {}) {
256
+ if (!Array.isArray(argv) || argv.length === 0) {
257
+ return Promise.reject(sshError('INVALID_COMMAND', 'exec expects a non-empty argv array'))
258
+ }
259
+ try {
260
+ return run(argv.map(shQuote).join(' '), options)
261
+ } catch (error) {
262
+ return Promise.reject(error)
263
+ }
264
+ }
265
+
266
+ /** Trusted internal scripts only; callers must quote every interpolated value. */
267
+ function execShell(script, options = {}) {
268
+ return run(script, options)
269
+ }
270
+
271
+ async function probe(options = {}) {
272
+ const script = "printf 'os='; uname -s 2>/dev/null || true; printf '\\n'; for c in git sha256sum shasum rg find stat; do printf '%s=' \"$c\"; command -v \"$c\" 2>/dev/null || true; printf '\\n'; done"
273
+ const { stdout } = await execShell(script, options)
274
+ const capabilities = { os: '', git: false, sha256sum: false, shasum: false, rg: false, find: false, stat: false }
275
+ for (const line of stdout.split(/\r?\n/)) {
276
+ const index = line.indexOf('=')
277
+ if (index < 0) continue
278
+ const key = line.slice(0, index)
279
+ const value = line.slice(index + 1).trim()
280
+ if (key === 'os') capabilities.os = value
281
+ else if (key in capabilities) capabilities[key] = value !== ''
282
+ }
283
+ return capabilities
284
+ }
285
+
286
+ return { host, controlPath, run, exec, execShell, probe }
287
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Architecture map — remote project status file.
3
+ *
4
+ * `remote-state.json` lives beside the local project graph and records the last
5
+ * fingerprint, pending change counts, polling state and auto-maintenance time.
6
+ * It never stores remote file content.
7
+ */
8
+ import { promises as fs } from 'node:fs'
9
+ import path from 'node:path'
10
+ import { randomBytes } from 'node:crypto'
11
+
12
+ export const REMOTE_STATE_SCHEMA = 1
13
+
14
+ export function emptyRemoteState(ws) {
15
+ return {
16
+ schema: REMOTE_STATE_SCHEMA,
17
+ id: ws.id,
18
+ host: ws.project?.host ?? null,
19
+ root: ws.project?.root ?? null,
20
+ fingerprint: null,
21
+ lastCheckedAt: null,
22
+ lastIndexedAt: null,
23
+ pending: { added: 0, changed: 0, deleted: 0, count: 0, since: null },
24
+ syncState: 'idle',
25
+ lastMaintainerAt: null,
26
+ lastError: null,
27
+ }
28
+ }
29
+
30
+ export async function readRemoteState(ws) {
31
+ const file = path.join(ws.stateDir, 'remote-state.json')
32
+ let text
33
+ try {
34
+ text = await fs.readFile(file, 'utf8')
35
+ } catch (error) {
36
+ if (error && error.code === 'ENOENT') return null
37
+ throw error
38
+ }
39
+ let parsed
40
+ try {
41
+ parsed = JSON.parse(text)
42
+ } catch {
43
+ return null
44
+ }
45
+ if (!parsed || typeof parsed !== 'object' || parsed.schema !== REMOTE_STATE_SCHEMA) return null
46
+ return parsed
47
+ }
48
+
49
+ export async function writeRemoteState(ws, state) {
50
+ const next = {
51
+ ...emptyRemoteState(ws),
52
+ ...state,
53
+ schema: REMOTE_STATE_SCHEMA,
54
+ id: ws.id,
55
+ host: ws.project?.host ?? state.host ?? null,
56
+ root: ws.project?.root ?? state.root ?? null,
57
+ pending: { ...emptyRemoteState(ws).pending, ...(state.pending ?? {}) },
58
+ }
59
+ await fs.mkdir(ws.stateDir, { recursive: true })
60
+ const file = path.join(ws.stateDir, 'remote-state.json')
61
+ const temp = path.join(ws.stateDir, `remote-state.tmp-${process.pid}-${randomBytes(6).toString('hex')}.json`)
62
+ await fs.writeFile(temp, JSON.stringify(next, null, 2) + '\n', 'utf8')
63
+ await fs.rename(temp, file)
64
+ return next
65
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Architecture map — remote read tools (node 14).
3
+ *
4
+ * These handlers are the only model-facing way to inspect a remote project.
5
+ * Every content/structure read passes the consent gate first; status and the
6
+ * project list expose metadata only. Handlers return `{ text }` so the plugin
7
+ * can wrap them in ordinary tool definitions.
8
+ */
9
+ import { loadIndex } from '../projects.js'
10
+ import { normalizeDataDir, resolveWorkspace } from '../workspace.js'
11
+
12
+ const ID_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/
13
+ const DEFAULT_READ_BYTES = 512 * 1024
14
+
15
+ function remoteError(code, message) {
16
+ const error = new Error(`${code}: ${message}`)
17
+ error.code = code
18
+ return error
19
+ }
20
+
21
+ function clamp(value, min, max, fallback) {
22
+ const number = Number.isInteger(value) ? value : fallback
23
+ return Math.min(Math.max(number, min), max)
24
+ }
25
+
26
+ /**
27
+ * @param {object} options - `{ config: {dir, ssh}, consent }`.
28
+ */
29
+ export function createRemoteTools(options = {}) {
30
+ const config = options.config ?? {}
31
+ const consent = options.consent
32
+ const onUse = options.onUse
33
+ const dir = normalizeDataDir(config.dir)
34
+
35
+ async function hubRoot(args, exec) {
36
+ const explicit = typeof args?.workspace === 'string' ? args.workspace.trim() : ''
37
+ const raw = explicit !== '' ? explicit : exec?.agent?.session?.header?.cwd
38
+ if (typeof raw !== 'string' || raw === '') {
39
+ throw remoteError('REMOTE_WORKSPACE_REQUIRED', 'pass workspace or open a session with a working directory')
40
+ }
41
+ const ws = await resolveWorkspace(raw, exec, config)
42
+ return ws.pathBase
43
+ }
44
+
45
+ async function remoteWorkspace(args, exec) {
46
+ const id = typeof args?.id === 'string' ? args.id.trim() : ''
47
+ if (!ID_PATTERN.test(id) || id === 'local') {
48
+ throw remoteError('INVALID_PROJECT', 'id must be a registered remote project id')
49
+ }
50
+ const ws = await resolveWorkspace(`remote:${id}`, exec, config)
51
+ if (ws.kind !== 'remote') throw remoteError('INVALID_PROJECT', `project "${id}" is not remote`)
52
+ if (typeof onUse === 'function') onUse(ws, exec)
53
+ return ws
54
+ }
55
+
56
+ async function ensureConsent(ws, exec) {
57
+ if (!consent || typeof consent.ensure !== 'function') {
58
+ throw remoteError('REMOTE_CONSENT_UNAVAILABLE', 'the consent gate is not available')
59
+ }
60
+ const decision = await consent.ensure(ws, exec, { signal: exec?.signal })
61
+ if (decision.allowed) return decision
62
+ if (decision.reason === 'no-answerer') {
63
+ throw remoteError('REMOTE_CONSENT_UNAVAILABLE', 'no user-questions answerer; remote content stays unavailable')
64
+ }
65
+ if (decision.reason === 'no-agent') {
66
+ throw remoteError('REMOTE_CONSENT_CONTEXT', 'the tool call has no owning session')
67
+ }
68
+ if (decision.reason === 'ask-failed') {
69
+ throw remoteError('REMOTE_CONSENT_FAILED', decision.error?.message ?? 'the consent question failed')
70
+ }
71
+ if (decision.reason === 'rejected') {
72
+ throw remoteError('REMOTE_CONSENT_REQUIRED', 'the user did not allow remote content')
73
+ }
74
+ throw remoteError('REMOTE_CONSENT_REQUIRED', 'remote content is not allowed')
75
+ }
76
+
77
+ async function list(args = {}, exec) {
78
+ const hub = await hubRoot(args, exec)
79
+ const index = await loadIndex(hub, dir)
80
+ const lines = [`projects (${index.projects.length}):`]
81
+ for (const project of index.projects) {
82
+ if (project.kind === 'local') {
83
+ lines.push(` local · local project · .`)
84
+ continue
85
+ }
86
+ const consentScope = project.consent?.scope ?? 'none'
87
+ lines.push(` ${project.id} · ssh ${project.host}:${project.root} · vcs ${project.vcs} · consent ${consentScope}${project.autoRefresh ? ' · auto' : ''}`)
88
+ }
89
+ return { text: lines.join('\n') }
90
+ }
91
+
92
+ async function status(args = {}, exec) {
93
+ const ws = await remoteWorkspace(args, exec)
94
+ const fingerprint = await ws.content.fingerprint()
95
+ const allowed = consent?.isAllowed ? consent.isAllowed(ws, exec).scope ?? 'none' : 'none'
96
+ const head = fingerprint.head ? `@${fingerprint.head.slice(0, 12)}` : ''
97
+ const dirty = fingerprint.vcs === 'git' ? (fingerprint.dirty ? 'dirty' : 'clean') : 'non-git'
98
+ return {
99
+ text: [
100
+ `remote:${ws.id} · ${fingerprint.vcs}${head} · ${dirty} · consent ${allowed}`,
101
+ `digest: ${fingerprint.digest}`,
102
+ ].join('\n'),
103
+ }
104
+ }
105
+
106
+ async function tree(args = {}, exec) {
107
+ const ws = await remoteWorkspace(args, exec)
108
+ await ensureConsent(ws, exec)
109
+ const maxEntries = clamp(args.maxEntries, 1, 2_000, 500)
110
+ const tree = await ws.content.listTree({ maxFiles: Math.max(maxEntries, 1_000) })
111
+ const shown = tree.entries.slice(0, maxEntries)
112
+ const lines = [`remote:${ws.id} · ${shown.length}/${tree.entries.length} paths${tree.truncated ? ' · listing truncated' : ''}`]
113
+ for (const entry of shown) lines.push(` ${entry.path}`)
114
+ if (tree.entries.length > shown.length) lines.push(` … ${tree.entries.length - shown.length} more`)
115
+ return { text: lines.join('\n') }
116
+ }
117
+
118
+ async function read(args = {}, exec) {
119
+ const ws = await remoteWorkspace(args, exec)
120
+ await ensureConsent(ws, exec)
121
+ const target = typeof args.path === 'string' ? args.path.trim() : ''
122
+ if (target === '') throw remoteError('INVALID_PATH', 'path is required')
123
+ const info = await ws.content.describe(target)
124
+ if (info.kind === 'missing') throw remoteError('REMOTE_NOT_FOUND', `remote file "${target}" does not exist`)
125
+ if (info.kind === 'not-file') throw remoteError('REMOTE_NOT_FILE', `remote path "${target}" is not a regular file`)
126
+ if (info.kind === 'binary') throw remoteError('REMOTE_BINARY', `remote file "${target}" is binary`)
127
+ if (info.kind === 'oversized') {
128
+ throw remoteError('REMOTE_TOO_LARGE', `remote file "${target}" is ${info.size} bytes; use arch_remote_grep`)
129
+ }
130
+ const text = await ws.content.readText(target, { maxBytes: DEFAULT_READ_BYTES })
131
+ if (text === null) throw remoteError('REMOTE_READ_FAILED', `cannot read remote file "${target}"`)
132
+ const lines = text === '' ? [] : text.replace(/\n$/, '').split('\n')
133
+ const offset = clamp(args.offset, 1, Math.max(lines.length, 1), 1)
134
+ const limit = clamp(args.limit, 1, 400, 200)
135
+ const slice = lines.slice(offset - 1, offset - 1 + limit)
136
+ const end = slice.length === 0 ? offset - 1 : offset + slice.length - 1
137
+ const header = `remote:${ws.id}:${target} · lines ${offset}-${end} of ${lines.length}${offset - 1 + slice.length >= lines.length ? ' · eof' : ''}`
138
+ const body = slice.map((line, index) => `${String(offset + index).padStart(4, ' ')}| ${line}`).join('\n')
139
+ return { text: body === '' ? header : `${header}\n${body}` }
140
+ }
141
+
142
+ async function grep(args = {}, exec) {
143
+ const ws = await remoteWorkspace(args, exec)
144
+ await ensureConsent(ws, exec)
145
+ const pattern = typeof args.pattern === 'string' ? args.pattern : ''
146
+ if (pattern === '') throw remoteError('INVALID_PATTERN', 'pattern is required')
147
+ const pathValue = typeof args.path === 'string' && args.path.trim() !== '' && args.path.trim() !== '.'
148
+ ? args.path.trim()
149
+ : undefined
150
+ const result = await ws.content.grep(pattern, {
151
+ include: typeof args.include === 'string' ? args.include : undefined,
152
+ path: pathValue,
153
+ context: clamp(args.context, 0, 5, 0),
154
+ maxResults: clamp(args.maxResults, 1, 200, 100),
155
+ })
156
+ const lines = [`remote:${ws.id} · ${result.matches.length} match${result.matches.length === 1 ? '' : 'es'} (${result.engine})${result.truncated ? ' · truncated' : ''}`]
157
+ for (const match of result.matches) lines.push(` ${match.path}:${match.line}: ${match.text}`)
158
+ return { text: lines.join('\n') }
159
+ }
160
+
161
+ return { list, status, tree, read, grep }
162
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Shared content signatures.
3
+ *
4
+ * `sha256` is the exact file hash used by the manifest. `signature` normalizes
5
+ * comments and whitespace for common code files so a format/comment-only edit
6
+ * does not look like an implementation change; anchors store this signature.
7
+ */
8
+ import { createHash } from 'node:crypto'
9
+ import path from 'node:path'
10
+
11
+ const CODE_EXTS = new Set([
12
+ '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.py', '.go', '.rs', '.java',
13
+ '.kt', '.kts', '.cs', '.rb', '.php', '.swift', '.c', '.h', '.cc', '.cpp',
14
+ '.hpp', '.m', '.mm', '.sh', '.bash', '.zsh',
15
+ ])
16
+
17
+ export function hashBuffer(buffer) {
18
+ return createHash('sha256').update(buffer).digest('hex')
19
+ }
20
+
21
+ /**
22
+ * Normalized code signature for cosmetic-change detection: comments and
23
+ * whitespace are removed, so a comment/format-only edit keeps the same
24
+ * signature while an implementation edit changes it. This is a heuristic:
25
+ * comment markers inside string literals can be stripped too.
26
+ */
27
+ export function signatureOf(relativePath, buffer) {
28
+ const ext = path.extname(relativePath).toLowerCase()
29
+ const text = buffer.toString('utf8')
30
+ if (!CODE_EXTS.has(ext)) {
31
+ return hashBuffer(Buffer.from(text.replace(/\s+/g, ' ').trim()))
32
+ }
33
+ let normalized = text.replace(/\r\n?/g, '\n')
34
+ normalized = normalized.replace(/\/\*[\s\S]*?\*\//g, ' ')
35
+ normalized = normalized.replace(/(^|[^:])\/\/[^\n]*/g, '$1 ')
36
+ if (['.py', '.sh', '.bash', '.zsh', '.rb'].includes(ext)) {
37
+ normalized = normalized.replace(/(^|\s)#[^\n]*/g, '$1 ')
38
+ }
39
+ normalized = normalized.replace(/<!--[\s\S]*?-->/g, ' ')
40
+ normalized = normalized.replace(/\s+/g, ' ').trim()
41
+ return hashBuffer(Buffer.from(normalized))
42
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Architecture map — workspace resolver (node 9).
3
+ *
4
+ * One descriptor answers both questions a store needs: where the code lives
5
+ * (`workspaceRoot`) and where the graph/dossier state lives (`stateDir`).
6
+ * Local projects keep `.archmap/`; remote projects keep
7
+ * `.archmap/projects/<id>/` in the local hub workspace.
8
+ */
9
+ import { promises as fs } from 'node:fs'
10
+ import path from 'node:path'
11
+ import { LOCAL_PROJECT_ID, loadIndex, projectById } from './projects.js'
12
+ import { createLocalContent } from './content/local.js'
13
+ import { createSshClient } from './remote/ssh.js'
14
+ import { createRemoteContent } from './remote/content.js'
15
+
16
+ const DEFAULT_DIR = '.archmap'
17
+ const remoteContents = new Map()
18
+
19
+ function fail(code, message) {
20
+ const error = new Error(`${code}: ${message}`)
21
+ error.code = code
22
+ throw error
23
+ }
24
+
25
+ /** Normalize the configured data directory; invalid values fall back to `.archmap`. */
26
+ export function normalizeDataDir(raw) {
27
+ if (typeof raw !== 'string' || raw.trim() === '') return DEFAULT_DIR
28
+ if (path.isAbsolute(raw) || raw.split(/[\\/]/).includes('..')) return DEFAULT_DIR
29
+ return raw
30
+ }
31
+
32
+ async function resolveLocalRoot(raw) {
33
+ if (typeof raw !== 'string' || raw.trim() === '') {
34
+ fail('WORKSPACE_REQUIRED', 'pass a workspace path or open a session with a working directory')
35
+ }
36
+ if (!path.isAbsolute(raw)) fail('INVALID_WORKSPACE', 'workspace must be an absolute path')
37
+ let real
38
+ try {
39
+ real = await fs.realpath(raw)
40
+ } catch {
41
+ fail('INVALID_WORKSPACE', `workspace "${raw}" does not exist`)
42
+ }
43
+ const stat = await fs.stat(real)
44
+ if (!stat.isDirectory()) fail('INVALID_WORKSPACE', `workspace "${raw}" is not a directory`)
45
+ return real
46
+ }
47
+
48
+ function stateDirUnder(root, relative) {
49
+ const stateDir = path.resolve(root, relative)
50
+ const prefix = root.endsWith(path.sep) ? root : root + path.sep
51
+ if (stateDir !== root && !stateDir.startsWith(prefix)) {
52
+ fail('PATH_ESCAPE', 'project state directory escapes the workspace')
53
+ }
54
+ return stateDir
55
+ }
56
+
57
+ /** Reuse one client/content pair per remote + transport configuration. */
58
+ function remoteContentFor(project, config) {
59
+ const ssh = config.ssh ?? {}
60
+ const key = JSON.stringify([project.host, project.root, project.vcs, ssh.binary ?? 'ssh', ssh.env ?? {}])
61
+ const cached = remoteContents.get(key)
62
+ if (cached) return cached
63
+ const client = createSshClient({ ...ssh, host: project.host })
64
+ const content = createRemoteContent({ client, root: project.root, vcs: project.vcs })
65
+ remoteContents.set(key, content)
66
+ return content
67
+ }
68
+
69
+ /**
70
+ * Resolve a tool workspace into `{ kind, display, workspaceRoot, stateDir }`.
71
+ * `remote:<id>` uses the calling session's working directory as the hub; a
72
+ * local absolute path keeps the legacy single-project layout.
73
+ */
74
+ export async function resolveWorkspace(raw, context, config = {}) {
75
+ if (raw !== null && typeof raw === 'object' && typeof raw.stateDir === 'string' && typeof raw.kind === 'string') {
76
+ return raw
77
+ }
78
+ const dir = normalizeDataDir(config.dir)
79
+ const value = typeof raw === 'string' ? raw.trim() : ''
80
+ if (value === '') {
81
+ fail('WORKSPACE_REQUIRED', 'pass a workspace path or open a session with a working directory')
82
+ }
83
+
84
+ if (value.startsWith('remote:')) {
85
+ const match = /^remote:([a-z][a-z0-9_-]{0,63})$/.exec(value)
86
+ if (!match) fail('INVALID_PROJECT', 'remote workspace must be remote:<id> with a lowercase project id')
87
+ const id = match[1]
88
+ if (id === LOCAL_PROJECT_ID) fail('INVALID_PROJECT', 'remote:local is not a remote project')
89
+ const agent = context?.agent ?? context
90
+ const cwd = agent?.session?.header?.cwd
91
+ if (typeof cwd !== 'string' || cwd === '') {
92
+ fail('WORKSPACE_REQUIRED', 'a remote workspace needs a session with a working directory')
93
+ }
94
+ const hub = await resolveLocalRoot(cwd)
95
+ const index = await loadIndex(hub, dir)
96
+ const project = projectById(index, id)
97
+ if (!project) {
98
+ fail('PROJECT_NOT_FOUND', `remote project "${id}" is not registered in ${path.join(hub, dir, 'index.json')}`)
99
+ }
100
+ if (project.kind !== 'remote') fail('INVALID_PROJECT', `project "${id}" is not remote`)
101
+ const stateDir = stateDirUnder(hub, path.posix.join(dir, project.dir))
102
+ const dataDir = stateDirUnder(hub, dir)
103
+ return {
104
+ kind: 'remote',
105
+ id,
106
+ display: `remote:${id}`,
107
+ workspaceRoot: project.root,
108
+ stateDir,
109
+ dataDir,
110
+ pathBase: hub,
111
+ content: remoteContentFor(project, config),
112
+ project,
113
+ index,
114
+ }
115
+ }
116
+
117
+ const root = await resolveLocalRoot(value)
118
+ const stateDir = stateDirUnder(root, dir)
119
+ return {
120
+ kind: 'local',
121
+ id: LOCAL_PROJECT_ID,
122
+ display: root,
123
+ workspaceRoot: root,
124
+ stateDir,
125
+ dataDir: stateDir,
126
+ pathBase: root,
127
+ content: createLocalContent(root),
128
+ project: null,
129
+ index: null,
130
+ }
131
+ }