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,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Architecture map — project index (node 9).
|
|
3
|
+
*
|
|
4
|
+
* `.archmap/index.json` lists the local project and any remote projects. The
|
|
5
|
+
* local project keeps the legacy layout (`.archmap/graph.json`); remote
|
|
6
|
+
* projects own `.archmap/projects/<id>/`, so one `.archmap` can hold several
|
|
7
|
+
* projects without migrating existing data.
|
|
8
|
+
*/
|
|
9
|
+
import { promises as fs } from 'node:fs'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
import { randomBytes } from 'node:crypto'
|
|
12
|
+
|
|
13
|
+
export const INDEX_SCHEMA = 1
|
|
14
|
+
export const LOCAL_PROJECT_ID = 'local'
|
|
15
|
+
export const PROJECT_ID_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/
|
|
16
|
+
|
|
17
|
+
const INDEX_FIELDS = new Set(['schema', 'projects'])
|
|
18
|
+
const PROJECT_FIELDS = new Set([
|
|
19
|
+
'id', 'kind', 'title', 'dir', 'transport', 'host', 'root', 'vcs',
|
|
20
|
+
'autoRefresh', 'consent', 'createdAt', 'lastUsedAt',
|
|
21
|
+
])
|
|
22
|
+
const CONSENT_FIELDS = new Set(['scope', 'grantedAt', 'grantedBy'])
|
|
23
|
+
const PROJECT_KINDS = new Set(['local', 'remote'])
|
|
24
|
+
const VCS_KINDS = new Set(['git', 'none'])
|
|
25
|
+
|
|
26
|
+
/** Throw a coded error the tool layer can surface verbatim to the model. */
|
|
27
|
+
function fail(code, message) {
|
|
28
|
+
const error = new Error(`${code}: ${message}`)
|
|
29
|
+
error.code = code
|
|
30
|
+
throw error
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function isPlainObject(value) {
|
|
34
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function assertKnownKeys(value, allowed, where) {
|
|
38
|
+
for (const key of Object.keys(value)) {
|
|
39
|
+
if (!allowed.has(key)) {
|
|
40
|
+
fail('INVALID_PROJECT', `${where}.${key} is not a recognized field (expected: ${[...allowed].join(', ')})`)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function assertText(value, where, max = 200) {
|
|
46
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
47
|
+
fail('INVALID_PROJECT', `${where} must be a non-empty string`)
|
|
48
|
+
}
|
|
49
|
+
if (value.length > max) {
|
|
50
|
+
fail('LIMIT_EXCEEDED', `${where} is ${value.length} characters; the limit is ${max}`)
|
|
51
|
+
}
|
|
52
|
+
return value.trim()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function assertRelativeDir(value, where) {
|
|
56
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
57
|
+
fail('INVALID_PROJECT', `${where} must be a non-empty string`)
|
|
58
|
+
}
|
|
59
|
+
if (value.startsWith('/') || value.includes('\\') || value.includes('\0') || value.includes('\n')) {
|
|
60
|
+
fail('PATH_ESCAPE', `${where} must be a workspace-relative POSIX directory`)
|
|
61
|
+
}
|
|
62
|
+
const segments = value.split('/')
|
|
63
|
+
if (segments.some(segment => segment === '' || segment === '.' || segment === '..')) {
|
|
64
|
+
fail('PATH_ESCAPE', `${where} must not contain empty, "." or ".." segments`)
|
|
65
|
+
}
|
|
66
|
+
return segments.join('/')
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function assertRemoteRoot(value, where) {
|
|
70
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
71
|
+
fail('INVALID_PROJECT', `${where} must be a non-empty absolute path`)
|
|
72
|
+
}
|
|
73
|
+
if (!value.startsWith('/') || value.includes('\\') || value.includes('\0') || value.includes('\n')) {
|
|
74
|
+
fail('PATH_ESCAPE', `${where} must be an absolute POSIX path`)
|
|
75
|
+
}
|
|
76
|
+
if (value.split('/').some(segment => segment === '..')) {
|
|
77
|
+
fail('PATH_ESCAPE', `${where} must not contain ".."`)
|
|
78
|
+
}
|
|
79
|
+
return value
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function normalizeConsent(raw, where) {
|
|
83
|
+
if (raw === undefined) return undefined
|
|
84
|
+
if (!isPlainObject(raw)) fail('INVALID_PROJECT', `${where} must be an object`)
|
|
85
|
+
assertKnownKeys(raw, CONSENT_FIELDS, where)
|
|
86
|
+
if (raw.scope !== 'workspace') {
|
|
87
|
+
fail('INVALID_PROJECT', `${where}.scope must be "workspace"`)
|
|
88
|
+
}
|
|
89
|
+
if (typeof raw.grantedAt !== 'string' || raw.grantedAt.trim() === '') {
|
|
90
|
+
fail('INVALID_PROJECT', `${where}.grantedAt must be an ISO-8601 string`)
|
|
91
|
+
}
|
|
92
|
+
if (raw.grantedBy !== undefined && typeof raw.grantedBy !== 'string') {
|
|
93
|
+
fail('INVALID_PROJECT', `${where}.grantedBy must be a string when present`)
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
scope: 'workspace',
|
|
97
|
+
grantedAt: raw.grantedAt,
|
|
98
|
+
...(raw.grantedBy === undefined ? {} : { grantedBy: raw.grantedBy }),
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function assertOptionalTimestamp(raw, where) {
|
|
103
|
+
if (raw === undefined) return undefined
|
|
104
|
+
if (typeof raw !== 'string' || raw.trim() === '') {
|
|
105
|
+
fail('INVALID_PROJECT', `${where} must be an ISO-8601 string when present`)
|
|
106
|
+
}
|
|
107
|
+
return raw
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The legacy local project: `.archmap/graph.json`. */
|
|
111
|
+
export function localProject() {
|
|
112
|
+
return { id: LOCAL_PROJECT_ID, kind: 'local', title: 'This project', dir: '.' }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function normalizeProject(raw, where) {
|
|
116
|
+
if (!isPlainObject(raw)) fail('INVALID_PROJECT', `${where} must be an object`)
|
|
117
|
+
assertKnownKeys(raw, PROJECT_FIELDS, where)
|
|
118
|
+
if (typeof raw.id !== 'string' || !PROJECT_ID_PATTERN.test(raw.id)) {
|
|
119
|
+
fail('INVALID_PROJECT', `${where}.id must match ${PROJECT_ID_PATTERN}`)
|
|
120
|
+
}
|
|
121
|
+
if (!PROJECT_KINDS.has(raw.kind)) {
|
|
122
|
+
fail('INVALID_PROJECT', `${where}.kind must be local or remote`)
|
|
123
|
+
}
|
|
124
|
+
if (raw.kind === 'local' && raw.id !== LOCAL_PROJECT_ID) {
|
|
125
|
+
fail('INVALID_PROJECT', `${where}.id must be "local" for the local project`)
|
|
126
|
+
}
|
|
127
|
+
if (raw.kind === 'remote' && raw.id === LOCAL_PROJECT_ID) {
|
|
128
|
+
fail('INVALID_PROJECT', `${where}.id "local" is reserved for the local project`)
|
|
129
|
+
}
|
|
130
|
+
const dir = raw.dir === undefined
|
|
131
|
+
? (raw.kind === 'local' ? '.' : `projects/${raw.id}`)
|
|
132
|
+
: (raw.kind === 'local' && raw.dir === '.' ? '.' : assertRelativeDir(raw.dir, `${where}.dir`))
|
|
133
|
+
const createdAt = assertOptionalTimestamp(raw.createdAt, `${where}.createdAt`)
|
|
134
|
+
const lastUsedAt = assertOptionalTimestamp(raw.lastUsedAt, `${where}.lastUsedAt`)
|
|
135
|
+
|
|
136
|
+
if (raw.kind === 'local') {
|
|
137
|
+
if (dir !== '.') fail('INVALID_PROJECT', `${where}.dir must be "." for the local project`)
|
|
138
|
+
if (raw.host !== undefined || raw.root !== undefined || raw.transport !== undefined || raw.vcs !== undefined) {
|
|
139
|
+
fail('INVALID_PROJECT', `${where}: the local project has no remote fields`)
|
|
140
|
+
}
|
|
141
|
+
if (raw.consent !== undefined || raw.autoRefresh !== undefined) {
|
|
142
|
+
fail('INVALID_PROJECT', `${where}: the local project has no remote policy fields`)
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
id: raw.id,
|
|
146
|
+
kind: 'local',
|
|
147
|
+
title: raw.title === undefined ? 'This project' : assertText(raw.title, `${where}.title`),
|
|
148
|
+
dir,
|
|
149
|
+
...(createdAt === undefined ? {} : { createdAt }),
|
|
150
|
+
...(lastUsedAt === undefined ? {} : { lastUsedAt }),
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const transport = raw.transport ?? 'ssh'
|
|
155
|
+
if (transport !== 'ssh') fail('INVALID_PROJECT', `${where}.transport must be "ssh"`)
|
|
156
|
+
const host = assertText(raw.host, `${where}.host`, 255)
|
|
157
|
+
const root = assertRemoteRoot(raw.root, `${where}.root`)
|
|
158
|
+
const vcs = raw.vcs ?? 'git'
|
|
159
|
+
if (!VCS_KINDS.has(vcs)) fail('INVALID_PROJECT', `${where}.vcs must be git or none`)
|
|
160
|
+
const autoRefresh = raw.autoRefresh === undefined ? true : raw.autoRefresh
|
|
161
|
+
if (typeof autoRefresh !== 'boolean') {
|
|
162
|
+
fail('INVALID_PROJECT', `${where}.autoRefresh must be a boolean when present`)
|
|
163
|
+
}
|
|
164
|
+
const consent = normalizeConsent(raw.consent, `${where}.consent`)
|
|
165
|
+
return {
|
|
166
|
+
id: raw.id,
|
|
167
|
+
kind: 'remote',
|
|
168
|
+
title: raw.title === undefined ? `${host}:${root}` : assertText(raw.title, `${where}.title`),
|
|
169
|
+
dir,
|
|
170
|
+
transport,
|
|
171
|
+
host,
|
|
172
|
+
root,
|
|
173
|
+
vcs,
|
|
174
|
+
autoRefresh,
|
|
175
|
+
...(consent === undefined ? {} : { consent }),
|
|
176
|
+
...(createdAt === undefined ? {} : { createdAt }),
|
|
177
|
+
...(lastUsedAt === undefined ? {} : { lastUsedAt }),
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Validate and normalize one index; a missing local entry is added in memory. */
|
|
182
|
+
export function validateIndex(raw) {
|
|
183
|
+
if (!isPlainObject(raw)) fail('INDEX_CORRUPT', 'index.json must be an object')
|
|
184
|
+
assertKnownKeys(raw, INDEX_FIELDS, 'index')
|
|
185
|
+
if (raw.schema !== INDEX_SCHEMA) {
|
|
186
|
+
fail('INDEX_CORRUPT', `index.schema must be ${INDEX_SCHEMA}`)
|
|
187
|
+
}
|
|
188
|
+
if (!Array.isArray(raw.projects)) fail('INDEX_CORRUPT', 'index.projects must be an array')
|
|
189
|
+
const projects = raw.projects.map((project, index) => normalizeProject(project, `projects[${index}]`))
|
|
190
|
+
if (!projects.some(project => project.id === LOCAL_PROJECT_ID)) projects.unshift(localProject())
|
|
191
|
+
|
|
192
|
+
const ids = new Set()
|
|
193
|
+
const dirs = new Set()
|
|
194
|
+
for (const project of projects) {
|
|
195
|
+
if (ids.has(project.id)) fail('INVALID_PROJECT', `duplicate project id "${project.id}"`)
|
|
196
|
+
ids.add(project.id)
|
|
197
|
+
const dirKey = project.dir.toLowerCase()
|
|
198
|
+
if (dirs.has(dirKey)) fail('INVALID_PROJECT', `project "${project.id}" reuses directory "${project.dir}"`)
|
|
199
|
+
dirs.add(dirKey)
|
|
200
|
+
}
|
|
201
|
+
return { schema: INDEX_SCHEMA, projects }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Read the project index; a missing file is the legacy local-only index. */
|
|
205
|
+
export async function loadIndex(root, dir = '.archmap') {
|
|
206
|
+
const file = path.join(root, dir, 'index.json')
|
|
207
|
+
let text
|
|
208
|
+
try {
|
|
209
|
+
text = await fs.readFile(file, 'utf8')
|
|
210
|
+
} catch (error) {
|
|
211
|
+
if (error && error.code === 'ENOENT') return { schema: INDEX_SCHEMA, projects: [localProject()] }
|
|
212
|
+
fail('IO_ERROR', `cannot read ${file}: ${error.message}`)
|
|
213
|
+
}
|
|
214
|
+
let parsed
|
|
215
|
+
try {
|
|
216
|
+
parsed = JSON.parse(text)
|
|
217
|
+
} catch (error) {
|
|
218
|
+
fail('INDEX_CORRUPT', `index.json is not valid JSON (${error.message})`)
|
|
219
|
+
}
|
|
220
|
+
return validateIndex(parsed)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Write the project index atomically; returns the normalized value. */
|
|
224
|
+
export async function writeIndex(root, index, dir = '.archmap') {
|
|
225
|
+
const normalized = validateIndex(index)
|
|
226
|
+
const dataDir = path.join(root, dir)
|
|
227
|
+
await fs.mkdir(dataDir, { recursive: true })
|
|
228
|
+
const file = path.join(dataDir, 'index.json')
|
|
229
|
+
const temp = path.join(dataDir, `index.tmp-${process.pid}-${randomBytes(6).toString('hex')}.json`)
|
|
230
|
+
await fs.writeFile(temp, JSON.stringify(normalized, null, 2) + '\n', 'utf8')
|
|
231
|
+
await fs.rename(temp, file)
|
|
232
|
+
return normalized
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Return one project by id, or undefined when it is not registered. */
|
|
236
|
+
export function projectById(index, id) {
|
|
237
|
+
if (typeof id !== 'string' || !PROJECT_ID_PATTERN.test(id)) {
|
|
238
|
+
fail('INVALID_PROJECT', `invalid project id "${id}"`)
|
|
239
|
+
}
|
|
240
|
+
return index.projects.find(project => project.id === id)
|
|
241
|
+
}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Architecture map — `/arch remote ...` commands (node 15/16 wiring).
|
|
3
|
+
*
|
|
4
|
+
* Commands are user-driven: the model cannot add a host or grant consent on its
|
|
5
|
+
* own. They use the same index, workspace resolver, indexer and consent gate as
|
|
6
|
+
* the tools.
|
|
7
|
+
*/
|
|
8
|
+
import { promises as fs } from 'node:fs'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { LOCAL_PROJECT_ID, loadIndex, writeIndex } from '../projects.js'
|
|
11
|
+
import { normalizeDataDir, resolveWorkspace } from '../workspace.js'
|
|
12
|
+
import { assertHost, assertRemotePath, createSshClient } from './ssh.js'
|
|
13
|
+
import { createRemoteContent } from './content.js'
|
|
14
|
+
|
|
15
|
+
const ID_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/
|
|
16
|
+
|
|
17
|
+
function commandError(message) {
|
|
18
|
+
return { kind: 'error', text: message }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Split a command line into words, honoring simple single/double quotes. */
|
|
22
|
+
export function splitArgs(input) {
|
|
23
|
+
const text = String(input ?? '')
|
|
24
|
+
const args = []
|
|
25
|
+
const pattern = /"([^"]*)"|'([^']*)'|(\S+)/g
|
|
26
|
+
for (const match of text.matchAll(pattern)) {
|
|
27
|
+
args.push(match[1] ?? match[2] ?? match[3])
|
|
28
|
+
}
|
|
29
|
+
return args
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function countText(counts) {
|
|
33
|
+
return `+${counts?.added ?? 0} added · ~${counts?.changed ?? 0} changed · -${counts?.deleted ?? 0} deleted`
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {object} options - `{ config, consent, indexer, maintainer }`.
|
|
38
|
+
*/
|
|
39
|
+
export function createRemoteCommands(options = {}) {
|
|
40
|
+
const config = options.config ?? {}
|
|
41
|
+
const consent = options.consent
|
|
42
|
+
const indexer = options.indexer
|
|
43
|
+
const maintainer = options.maintainer
|
|
44
|
+
const dataDir = normalizeDataDir(config.dir)
|
|
45
|
+
|
|
46
|
+
async function hubOf(agent) {
|
|
47
|
+
const cwd = agent?.session?.header?.cwd
|
|
48
|
+
if (typeof cwd !== 'string' || cwd === '') {
|
|
49
|
+
throw new Error('REMOTE_WORKSPACE_REQUIRED: the session has no working directory')
|
|
50
|
+
}
|
|
51
|
+
const ws = await resolveWorkspace(cwd, { agent }, config)
|
|
52
|
+
const relative = path.relative(ws.pathBase, ws.dataDir)
|
|
53
|
+
return { hub: ws.pathBase, dir: relative === '' ? '.' : relative.split(path.sep).join('/') }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function remoteWorkspace(id, agent) {
|
|
57
|
+
if (!ID_PATTERN.test(id ?? '') || id === LOCAL_PROJECT_ID) {
|
|
58
|
+
throw new Error(`INVALID_PROJECT: "${id}" is not a remote project id`)
|
|
59
|
+
}
|
|
60
|
+
const ws = await resolveWorkspace(`remote:${id}`, { agent }, config)
|
|
61
|
+
if (ws.kind !== 'remote') throw new Error(`INVALID_PROJECT: "${id}" is not remote`)
|
|
62
|
+
return ws
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function add(args, agent) {
|
|
66
|
+
const [id, host, root] = args
|
|
67
|
+
if (!id || !host || !root) return commandError('用法:/arch remote add <id> <host> <远程绝对路径>')
|
|
68
|
+
if (!ID_PATTERN.test(id) || id === LOCAL_PROJECT_ID) {
|
|
69
|
+
return commandError(`id 必须匹配 ${ID_PATTERN},且不能是 local`)
|
|
70
|
+
}
|
|
71
|
+
let safeHost
|
|
72
|
+
let safeRoot
|
|
73
|
+
try {
|
|
74
|
+
safeHost = assertHost(host)
|
|
75
|
+
safeRoot = assertRemotePath(root, '远程路径')
|
|
76
|
+
} catch (error) {
|
|
77
|
+
return commandError(error.message)
|
|
78
|
+
}
|
|
79
|
+
const { hub, dir } = await hubOf(agent)
|
|
80
|
+
const index = await loadIndex(hub, dir)
|
|
81
|
+
if (index.projects.some(project => project.id === id)) {
|
|
82
|
+
return commandError(`项目 "${id}" 已存在`)
|
|
83
|
+
}
|
|
84
|
+
let vcs = 'none'
|
|
85
|
+
try {
|
|
86
|
+
const client = createSshClient({ ...(config.ssh ?? {}), host: safeHost })
|
|
87
|
+
const content = createRemoteContent({ client, root: safeRoot, vcs: 'auto' })
|
|
88
|
+
vcs = await content.detectVcs()
|
|
89
|
+
} catch (error) {
|
|
90
|
+
return commandError(`无法连接 ${safeHost}:${safeRoot}:${error?.message ?? error}`)
|
|
91
|
+
}
|
|
92
|
+
const project = {
|
|
93
|
+
id,
|
|
94
|
+
kind: 'remote',
|
|
95
|
+
title: `${safeHost}:${safeRoot}`,
|
|
96
|
+
dir: `projects/${id}`,
|
|
97
|
+
transport: 'ssh',
|
|
98
|
+
host: safeHost,
|
|
99
|
+
root: safeRoot,
|
|
100
|
+
vcs,
|
|
101
|
+
autoRefresh: true,
|
|
102
|
+
}
|
|
103
|
+
await writeIndex(hub, { schema: 1, projects: [...index.projects, project] }, dir)
|
|
104
|
+
return {
|
|
105
|
+
kind: 'success',
|
|
106
|
+
text: `已添加远程项目 ${id} · ${safeHost}:${safeRoot} · vcs ${vcs}\n状态在 ${path.join(dir, project.dir, 'remote-state.json')};面板来源选择器或 /arch remote select ${id} 启动轮询。`,
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function list(agent) {
|
|
111
|
+
const { hub, dir } = await hubOf(agent)
|
|
112
|
+
const index = await loadIndex(hub, dir)
|
|
113
|
+
const lines = [`remote projects (${index.projects.length}):`]
|
|
114
|
+
for (const project of index.projects) {
|
|
115
|
+
if (project.kind === 'local') {
|
|
116
|
+
lines.push(' local · 本地项目')
|
|
117
|
+
continue
|
|
118
|
+
}
|
|
119
|
+
lines.push(` ${project.id} · ssh ${project.host}:${project.root} · vcs ${project.vcs} · consent ${project.consent?.scope ?? 'none'}`)
|
|
120
|
+
}
|
|
121
|
+
return { kind: 'success', text: lines.join('\n') }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function select(args, agent) {
|
|
125
|
+
const [id] = args
|
|
126
|
+
if (!id) return commandError('用法:/arch remote select <id>')
|
|
127
|
+
const ws = await remoteWorkspace(id, agent)
|
|
128
|
+
indexer.track(ws, { agent }, { immediate: true })
|
|
129
|
+
return { kind: 'success', text: `已开始跟踪 ${id}:每 ${Math.round((indexer.intervalMs ?? 60_000) / 1000)} 秒检查一次指纹。` }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function sync(args, agent) {
|
|
133
|
+
const [id] = args
|
|
134
|
+
if (!id) return commandError('用法:/arch remote sync <id>')
|
|
135
|
+
const ws = await remoteWorkspace(id, agent)
|
|
136
|
+
indexer.track(ws, { agent }, { immediate: false })
|
|
137
|
+
const result = await indexer.check(ws, { agent }, { maintainer: false })
|
|
138
|
+
if (result.first) return { kind: 'success', text: `${id}: 已记录初始指纹;下次变化时会做增量同步。` }
|
|
139
|
+
if (!result.changed) return { kind: 'success', text: `${id}: 没有变化。` }
|
|
140
|
+
return {
|
|
141
|
+
kind: 'success',
|
|
142
|
+
text: `${id}: 检测到变化 ${countText(result.counts)}\n已标记受影响节点 stale;用 /arch remote update ${id} 或面板 Update 启维护子会话。`,
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function update(args, agent) {
|
|
147
|
+
const [id] = args
|
|
148
|
+
if (!id) return commandError('用法:/arch remote update <id>')
|
|
149
|
+
const ws = await remoteWorkspace(id, agent)
|
|
150
|
+
const checked = await indexer.check(ws, { agent }, { maintainer: false })
|
|
151
|
+
const counts = checked.counts ?? checked.state?.pending ?? { added: 0, changed: 0, deleted: 0 }
|
|
152
|
+
if ((counts.added ?? 0) + (counts.changed ?? 0) + (counts.deleted ?? 0) === 0) {
|
|
153
|
+
return { kind: 'success', text: `${id}: 没有待处理的变更。` }
|
|
154
|
+
}
|
|
155
|
+
const started = await maintainer.maybeRun(ws, { agent }, counts, checked.state ?? {}, { force: true })
|
|
156
|
+
if (started.started) {
|
|
157
|
+
return { kind: 'success', text: `${id}: 已启动维护子会话 ${started.name ?? started.childId}。` }
|
|
158
|
+
}
|
|
159
|
+
const reasons = {
|
|
160
|
+
'no-workspace-consent': '需要先“始终允许”这个远程,才能自动维护。',
|
|
161
|
+
'too-many-files': `变更文件 ${started.total} 个,超过上限 ${started.maxFiles};请手动同步或分批处理。`,
|
|
162
|
+
'already-running': '已经有维护子会话在跑。',
|
|
163
|
+
'cooldown': '刚维护过,稍后再试。',
|
|
164
|
+
'no-agent': '没有活跃会话。',
|
|
165
|
+
'no-child-runner': '当前 profile 不支持子会话。',
|
|
166
|
+
}
|
|
167
|
+
return commandError(`${id}: 未启动维护 — ${reasons[started.reason] ?? started.reason}`)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function grant(args, agent) {
|
|
171
|
+
const [id] = args
|
|
172
|
+
if (!id) return commandError('用法:/arch remote grant <id>')
|
|
173
|
+
const ws = await remoteWorkspace(id, agent)
|
|
174
|
+
await consent.grantWorkspace(ws)
|
|
175
|
+
indexer.track(ws, { agent }, { immediate: false })
|
|
176
|
+
return { kind: 'success', text: `${id}: 已写入 workspace 级内容授权。` }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function revoke(args, agent) {
|
|
180
|
+
const [id] = args
|
|
181
|
+
if (!id) return commandError('用法:/arch remote revoke <id>')
|
|
182
|
+
const ws = await remoteWorkspace(id, agent)
|
|
183
|
+
const result = await consent.revoke(ws)
|
|
184
|
+
return { kind: 'success', text: `${id}: 已撤销 ${result.revoked === 'workspace' ? 'workspace 与全部会话' : '会话'}授权。` }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function remove(args, agent) {
|
|
188
|
+
const id = args.find(value => !value.startsWith('--'))
|
|
189
|
+
if (!id) return commandError('用法:/arch remote remove <id> [--purge]')
|
|
190
|
+
const purge = args.includes('--purge')
|
|
191
|
+
const ws = await remoteWorkspace(id, agent)
|
|
192
|
+
const { hub, dir } = await hubOf(agent)
|
|
193
|
+
const index = await loadIndex(hub, dir)
|
|
194
|
+
if (!index.projects.some(project => project.id === id)) return commandError(`项目 "${id}" 不存在`)
|
|
195
|
+
const projects = index.projects.filter(project => project.id !== id)
|
|
196
|
+
await writeIndex(hub, { schema: 1, projects }, dir)
|
|
197
|
+
indexer.untrack(ws)
|
|
198
|
+
if (purge) await fs.rm(ws.stateDir, { recursive: true, force: true })
|
|
199
|
+
return { kind: 'success', text: `${id}: 已移除${purge ? '并删除本地状态' : '(保留本地状态)'}。` }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function handle(input, agent) {
|
|
203
|
+
const args = splitArgs(input)
|
|
204
|
+
const sub = args.shift()
|
|
205
|
+
try {
|
|
206
|
+
switch (sub) {
|
|
207
|
+
case 'add': return await add(args, agent)
|
|
208
|
+
case 'list': return await list(agent)
|
|
209
|
+
case 'select': return await select(args, agent)
|
|
210
|
+
case 'sync': return await sync(args, agent)
|
|
211
|
+
case 'update': return await update(args, agent)
|
|
212
|
+
case 'grant': return await grant(args, agent)
|
|
213
|
+
case 'revoke': return await revoke(args, agent)
|
|
214
|
+
case 'remove': return await remove(args, agent)
|
|
215
|
+
case undefined:
|
|
216
|
+
case '':
|
|
217
|
+
return commandError('用法:/arch remote add|list|select|sync|update|grant|revoke|remove ...')
|
|
218
|
+
default:
|
|
219
|
+
return commandError(`未知子命令 "${sub}"`)
|
|
220
|
+
}
|
|
221
|
+
} catch (error) {
|
|
222
|
+
return commandError(error?.message ?? String(error))
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
return { handle, add, list, select, sync, update, grant, revoke, remove }
|
|
227
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Architecture map — remote content consent gate (node 13).
|
|
3
|
+
*
|
|
4
|
+
* Remote content only enters the model context after the user answers a
|
|
5
|
+
* blocking approval question. Grants are either session-scoped (including the
|
|
6
|
+
* children that session starts) or workspace-scoped and stored in
|
|
7
|
+
* `.archmap/index.json`; without the user-questions service the gate fails
|
|
8
|
+
* closed.
|
|
9
|
+
*/
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
import { writeIndex } from '../projects.js'
|
|
12
|
+
|
|
13
|
+
export const CONSENT = Object.freeze({
|
|
14
|
+
session: '允许,本次会话',
|
|
15
|
+
always: '始终允许这个远程',
|
|
16
|
+
reject: '拒绝',
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
const DETAIL = '只读:不会修改远程文件,也不会在本地保存源码副本。'
|
|
20
|
+
|
|
21
|
+
function consentError(code, message) {
|
|
22
|
+
const error = new Error(`${code}: ${message}`)
|
|
23
|
+
error.code = code
|
|
24
|
+
return error
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function agentOf(context) {
|
|
28
|
+
return context?.agent ?? context
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function sessionIdOf(context) {
|
|
32
|
+
const id = agentOf(context)?.session?.id
|
|
33
|
+
return typeof id === 'string' && id !== '' ? id : null
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function projectKey(ws) {
|
|
37
|
+
return `${ws.pathBase}\0${ws.id}`
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function projectDirRelative(ws) {
|
|
41
|
+
if (typeof ws.dataDir !== 'string') {
|
|
42
|
+
throw consentError('CONSENT_UNAVAILABLE', 'the workspace descriptor has no data directory')
|
|
43
|
+
}
|
|
44
|
+
const relative = path.relative(ws.pathBase, ws.dataDir)
|
|
45
|
+
return relative === '' ? '.' : relative.split(path.sep).join('/')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function withoutConsent(project) {
|
|
49
|
+
const next = { ...project }
|
|
50
|
+
delete next.consent
|
|
51
|
+
return next
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @param {object} config - `{ getUserQuestions?: () => service, now?: () => Date }`.
|
|
56
|
+
*/
|
|
57
|
+
export function createConsentGate(config = {}) {
|
|
58
|
+
const getUserQuestions = typeof config.getUserQuestions === 'function'
|
|
59
|
+
? config.getUserQuestions
|
|
60
|
+
: () => undefined
|
|
61
|
+
const now = typeof config.now === 'function' ? config.now : () => new Date()
|
|
62
|
+
const sessions = new Set()
|
|
63
|
+
|
|
64
|
+
function workspaceConsent(ws) {
|
|
65
|
+
return ws?.project?.consent?.scope === 'workspace'
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function sessionGrant(ws, sessionId) {
|
|
69
|
+
return typeof sessionId === 'string' && sessions.has(`${projectKey(ws)}\0${sessionId}`)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function isAllowed(ws, context) {
|
|
73
|
+
if (workspaceConsent(ws)) return { allowed: true, scope: 'workspace' }
|
|
74
|
+
if (sessionGrant(ws, sessionIdOf(context))) return { allowed: true, scope: 'session' }
|
|
75
|
+
return { allowed: false, scope: null }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function allowSession(ws, context) {
|
|
79
|
+
const sessionId = sessionIdOf(context)
|
|
80
|
+
if (!sessionId) throw consentError('CONSENT_CONTEXT_REQUIRED', 'a session consent needs a live session id')
|
|
81
|
+
sessions.add(`${projectKey(ws)}\0${sessionId}`)
|
|
82
|
+
return { allowed: true, scope: 'session' }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Let a child started by a consented parent reuse the parent's session grant. */
|
|
86
|
+
function inherit(ws, childSessionId, parentSessionId) {
|
|
87
|
+
if (typeof childSessionId !== 'string' || childSessionId === '') return false
|
|
88
|
+
if (typeof parentSessionId !== 'string' || parentSessionId === '') return false
|
|
89
|
+
const key = projectKey(ws)
|
|
90
|
+
if (!sessions.has(`${key}\0${parentSessionId}`)) return false
|
|
91
|
+
sessions.add(`${key}\0${childSessionId}`)
|
|
92
|
+
return true
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function writeConsent(ws, consent) {
|
|
96
|
+
if (ws?.kind !== 'remote' || !ws.index || !ws.project) {
|
|
97
|
+
throw consentError('CONSENT_UNAVAILABLE', 'workspace consent is only available for a registered remote project')
|
|
98
|
+
}
|
|
99
|
+
const projects = ws.index.projects.map(project => {
|
|
100
|
+
if (project.id !== ws.id) return project
|
|
101
|
+
return consent === undefined ? withoutConsent(project) : { ...project, consent }
|
|
102
|
+
})
|
|
103
|
+
const next = await writeIndex(ws.pathBase, { schema: 1, projects }, projectDirRelative(ws))
|
|
104
|
+
ws.index = next
|
|
105
|
+
ws.project = next.projects.find(project => project.id === ws.id)
|
|
106
|
+
return next
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function grantWorkspace(ws) {
|
|
110
|
+
const consent = {
|
|
111
|
+
scope: 'workspace',
|
|
112
|
+
grantedAt: now().toISOString(),
|
|
113
|
+
grantedBy: 'user',
|
|
114
|
+
}
|
|
115
|
+
await writeConsent(ws, consent)
|
|
116
|
+
return consent
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Resolve consent for a remote content read. Never returns content itself.
|
|
121
|
+
* @returns `{ allowed, scope, reason?, error? }`
|
|
122
|
+
*/
|
|
123
|
+
async function ensure(ws, context, options = {}) {
|
|
124
|
+
const current = isAllowed(ws, context)
|
|
125
|
+
if (current.allowed) return current
|
|
126
|
+
|
|
127
|
+
const service = getUserQuestions()
|
|
128
|
+
if (!service || typeof service.ask !== 'function') {
|
|
129
|
+
return { allowed: false, reason: 'no-answerer' }
|
|
130
|
+
}
|
|
131
|
+
const agent = agentOf(context)
|
|
132
|
+
if (!agent) return { allowed: false, reason: 'no-agent' }
|
|
133
|
+
|
|
134
|
+
const host = ws?.project?.host ?? 'remote'
|
|
135
|
+
const root = ws?.project?.root ?? ''
|
|
136
|
+
const question = {
|
|
137
|
+
id: `archmap-consent-${ws.id}`,
|
|
138
|
+
header: '远程内容授权',
|
|
139
|
+
question: `允许读取远程仓库 ${host}:${root} 的内容并发送给模型分析吗?`,
|
|
140
|
+
detail: DETAIL,
|
|
141
|
+
options: [
|
|
142
|
+
{ label: CONSENT.session, description: '本次会话有效,包括本会话启动的子会话。' },
|
|
143
|
+
{ label: CONSENT.always, description: '写入 .archmap/index.json;后续会话和自动维护可用。' },
|
|
144
|
+
{ label: CONSENT.reject, description: '不读取内容。' },
|
|
145
|
+
],
|
|
146
|
+
intent: {
|
|
147
|
+
kind: 'approval',
|
|
148
|
+
approve: CONSENT.session,
|
|
149
|
+
reject: CONSENT.reject,
|
|
150
|
+
always: CONSENT.always,
|
|
151
|
+
detail: DETAIL,
|
|
152
|
+
subject: { name: `${host}:${root}` },
|
|
153
|
+
},
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
let answer
|
|
157
|
+
try {
|
|
158
|
+
answer = await service.ask({ agent, signal: options.signal, questions: [question] })
|
|
159
|
+
} catch (error) {
|
|
160
|
+
return { allowed: false, reason: 'ask-failed', error }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const item = Array.isArray(answer?.answers) ? answer.answers[0] : undefined
|
|
164
|
+
const selected = Array.isArray(item?.selected) ? item.selected : []
|
|
165
|
+
const choice = typeof item?.custom === 'string' && item.custom.trim() !== ''
|
|
166
|
+
? item.custom.trim()
|
|
167
|
+
: selected[0]
|
|
168
|
+
|
|
169
|
+
if (choice === CONSENT.always) {
|
|
170
|
+
const consent = await grantWorkspace(ws)
|
|
171
|
+
return { allowed: true, scope: 'workspace', consent }
|
|
172
|
+
}
|
|
173
|
+
if (choice === CONSENT.session) {
|
|
174
|
+
allowSession(ws, context)
|
|
175
|
+
return { allowed: true, scope: 'session' }
|
|
176
|
+
}
|
|
177
|
+
return { allowed: false, reason: 'rejected' }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Revoke one session grant, or all session grants plus the workspace record.
|
|
182
|
+
* @returns `{ revoked: 'session' | 'workspace' }`
|
|
183
|
+
*/
|
|
184
|
+
async function revoke(ws, options = {}) {
|
|
185
|
+
const key = projectKey(ws)
|
|
186
|
+
if (typeof options.sessionId === 'string') {
|
|
187
|
+
sessions.delete(`${key}\0${options.sessionId}`)
|
|
188
|
+
return { revoked: 'session' }
|
|
189
|
+
}
|
|
190
|
+
for (const entry of [...sessions]) {
|
|
191
|
+
if (entry.startsWith(`${key}\0`)) sessions.delete(entry)
|
|
192
|
+
}
|
|
193
|
+
if (workspaceConsent(ws)) {
|
|
194
|
+
await writeConsent(ws, undefined)
|
|
195
|
+
return { revoked: 'workspace' }
|
|
196
|
+
}
|
|
197
|
+
return { revoked: 'session' }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Auto maintenance is allowed only on a durable workspace grant. */
|
|
201
|
+
function autoMaintenanceAllowed(ws) {
|
|
202
|
+
return workspaceConsent(ws)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
return {
|
|
206
|
+
isAllowed,
|
|
207
|
+
ensure,
|
|
208
|
+
allowSession,
|
|
209
|
+
inherit,
|
|
210
|
+
revoke,
|
|
211
|
+
grantWorkspace,
|
|
212
|
+
autoMaintenanceAllowed,
|
|
213
|
+
workspaceConsent,
|
|
214
|
+
sessionGrant,
|
|
215
|
+
}
|
|
216
|
+
}
|