dsh-project-flow-explainer 0.0.0-stage → 0.6.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/index.js ADDED
@@ -0,0 +1,546 @@
1
+ /**
2
+ * DSH adapter for Project Flow Explainer.
3
+ *
4
+ * The core (Python, no third-party packages) stays independent: this plugin
5
+ * only validates arguments, contains paths, calls the core CLI and maps the
6
+ * result. It imports nothing from @deepseek-ai/* on purpose — a profile's
7
+ * node_modules cannot resolve those packages, so the definition is hand-built
8
+ * and handed to `ctx.tools.register`, which manages its lifecycle.
9
+ *
10
+ * Security posture (see README):
11
+ * - deny-by-default: without `allowedRoots` every call fails with
12
+ * `allowed_roots_unconfigured`;
13
+ * - artifacts may only be written to `<repo>/artifacts/flows`;
14
+ * - cancellation surfaces as AbortError so the runtime keeps the
15
+ * cancellation identity instead of recording a business failure.
16
+ *
17
+ * Besides `project_flow_explain`, this plugin registers the code-knowledge
18
+ * tools from ./lib/tools.js (index, search, context pack, impact, verify,
19
+ * refresh). They share the same path policy and the same core subprocess.
20
+ */
21
+ import path from 'node:path'
22
+ import { createRequire } from 'node:module'
23
+ import { realpathSync } from 'node:fs'
24
+ import { fileURLToPath } from 'node:url'
25
+ import { runCore } from './lib/core-runner.js'
26
+ import {
27
+ InputError, resolveArtifactRoot, resolveCoreRoot, resolveRepository,
28
+ } from './lib/paths.js'
29
+ import { flowCommand } from './lib/command.js'
30
+ import { knowledgeTools } from './lib/tools.js'
31
+ import {
32
+ assertObject, optionalString, rejectUnknownKeys, requiredString,
33
+ } from './lib/validate.js'
34
+
35
+ export const name = 'project-flow-explainer'
36
+ export const inject = ['tools']
37
+
38
+ // The schema must come from the SAME schemastery instance the Loader uses.
39
+ // Node resolution from this package reaches the profile's own copy first, and
40
+ // a foreign copy makes the config projector emit {} for every volatile field
41
+ // (measured: cfg {"allowedRoots":{},"pythonPath":{},...}), so the Settings page
42
+ // drops the entry. Anchor a resolver at $DSH_HOME/profiles instead: the flat
43
+ // closure there links to the installation's schemastery, which is the Loader's.
44
+ function loadSchemaModule() {
45
+ const candidates = []
46
+ // The Loader runs from the installation; anchoring there resolves the exact
47
+ // schemastery instance it validates with.
48
+ try {
49
+ // <install>/lib/node_modules/@deepseek-ai/dsh/lib/bin.js -> package root,
50
+ // whose node_modules holds the Loader's own schemastery.
51
+ const bin = realpathSync(process.argv[1] ?? '')
52
+ const dshPackage = path.dirname(path.dirname(bin))
53
+ candidates.push(createRequire(path.join(dshPackage, 'anchor.js')))
54
+ } catch {
55
+ // no argv anchor (tests, embedders)
56
+ }
57
+ if (process.env.DSH_HOME) {
58
+ candidates.push(createRequire(path.join(process.env.DSH_HOME, 'profiles', 'anchor.js')))
59
+ }
60
+ candidates.push(createRequire(import.meta.url))
61
+ let fallback
62
+ for (const requireFrom of candidates) {
63
+ try {
64
+ const resolved = requireFrom.resolve('@deepseek-ai/schemastery')
65
+ const loaded = requireFrom(resolved)
66
+ const z = loaded.default ?? loaded
67
+ if (typeof z?.object !== 'function') continue
68
+ // Prefer the installation's copy: that is the instance the Loader uses.
69
+ const candidate = { z, source: resolved }
70
+ if (resolved.includes(path.join('@deepseek-ai', 'dsh', 'node_modules'))) return candidate
71
+ fallback ??= candidate
72
+ } catch {
73
+ // try the next anchor
74
+ }
75
+ }
76
+ return fallback
77
+ }
78
+
79
+ const schemaModule = loadSchemaModule()
80
+ let ConfigSchema
81
+ if (schemaModule !== undefined) {
82
+ const z = schemaModule.z
83
+ // .volatile() is what puts the entry into settings.describe(): without it the
84
+ // Plugins page has no ConfigPageForm to pass to plugins.bundle.config.
85
+ ConfigSchema = z.object({
86
+ allowedRoots: z.array(z.string()).volatile().description(
87
+ 'Thư mục gốc được đọc, đường dẫn tuyệt đối. Rỗng nghĩa là từ chối mọi repository.'),
88
+ pythonPath: z.string().default('python3').volatile()
89
+ .description('Interpreter dùng để gọi core'),
90
+ coreRoot: z.string().volatile().description('Thư mục core; bỏ trống để tự dò vendor/core'),
91
+ timeoutMs: z.number().min(1).default(180000).volatile()
92
+ .description('Ngân sách mỗi lần gọi, mili giây'),
93
+ maxOutputBytes: z.number().min(1).default(1048576).volatile()
94
+ .description('Giới hạn stdout và stderr'),
95
+ })
96
+ }
97
+
98
+ /** Real schemastery schema when it resolved, otherwise undefined (fallback path). */
99
+ export const Config = ConfigSchema
100
+
101
+ export const TOOL_NAME = 'project_flow_explain'
102
+ const PACKAGE_NAME = 'dsh-project-flow-explainer'
103
+ /** Settings rows are keyed by profile entry id; both conventions are in use. */
104
+ const SETTINGS_IDS = new Set([name, PACKAGE_NAME])
105
+ const PACKAGE_ROOT = path.dirname(fileURLToPath(import.meta.url))
106
+
107
+ const DEFAULTS = {
108
+ pythonPath: 'python3',
109
+ coreRoot: undefined,
110
+ // Deny-by-default: undefined/empty means "no repository is allowed".
111
+ allowedRoots: undefined,
112
+ timeoutMs: 180000,
113
+ maxOutputBytes: 1024 * 1024,
114
+ }
115
+
116
+ function badConfig(message, hint) {
117
+ throw new InputError('invalid_plugin_config', `${name}: ${message}`, hint)
118
+ }
119
+
120
+ function normalizeConfig(config) {
121
+ // Volatile settings are placeholders ({}) until the user layer carries a
122
+ // value, so every field is type-checked and falls back to its default instead
123
+ // of failing the mount. A real wrong type still fails: the Loader's Config
124
+ // schema rejects it before apply().
125
+ const raw = config ?? {}
126
+ const settings = { ...DEFAULTS }
127
+ // Volatile fields can arrive as {} (no value yet) or as a loader expression
128
+ // object; both mean "unset". A plainly wrong SCALAR must still fail loudly.
129
+ const opaque = (value) => typeof value === 'object' && value !== null && !Array.isArray(value)
130
+ for (const [key, value] of Object.entries(raw)) {
131
+ if (value === undefined || value === null) continue
132
+ if (opaque(value)) {
133
+ if (key === 'allowedRoots' || key === 'pythonPath' || key === 'coreRoot'
134
+ || key === 'timeoutMs' || key === 'maxOutputBytes') continue
135
+ }
136
+ settings[key] = value
137
+ }
138
+ if (typeof settings.pythonPath !== 'string' || settings.pythonPath.trim() === '') {
139
+ badConfig('pythonPath phải là chuỗi không rỗng')
140
+ }
141
+ if (settings.coreRoot !== undefined && typeof settings.coreRoot !== 'string') {
142
+ badConfig('coreRoot phải là chuỗi đường dẫn')
143
+ }
144
+ if (settings.allowedRoots !== undefined && !Array.isArray(settings.allowedRoots)) {
145
+ badConfig('allowedRoots phải là mảng chuỗi đường dẫn')
146
+ }
147
+ if (!Number.isFinite(settings.timeoutMs) || settings.timeoutMs <= 0) {
148
+ badConfig('timeoutMs phải là số dương')
149
+ }
150
+ if (!Number.isFinite(settings.maxOutputBytes) || settings.maxOutputBytes <= 0) {
151
+ badConfig('maxOutputBytes phải là số dương')
152
+ }
153
+ return settings
154
+ }
155
+
156
+ /**
157
+ * Environment for user-facing lookups, read through the launcher snapshot when
158
+ * the host provided one.
159
+ *
160
+ * `launchEnvironmentOf(ctx)` (dsh-launch-environment) returns a snapshot layered
161
+ * over process env, the project `.env` and `$DSH_HOME/.env`, and remembers which
162
+ * layer a value came from. This package imports nothing from @deepseek-ai/*, so
163
+ * it reads the same service through `ctx.get('launchEnvironment')` and degrades
164
+ * to `process.env` when the host has none (headless mount, unit test).
165
+ * @param {object} ctx - plugin context.
166
+ * @returns {{PFE_CORE_ROOT?: string}} plain env view for the keys read below.
167
+ */
168
+ function launchEnv(ctx) {
169
+ const env = { PFE_CORE_ROOT: process.env.PFE_CORE_ROOT }
170
+ let snapshot
171
+ try {
172
+ snapshot = ctx.get?.('launchEnvironment')
173
+ } catch {
174
+ snapshot = undefined
175
+ }
176
+ if (snapshot === undefined || typeof snapshot.get !== 'function') return env
177
+ for (const key of Object.keys(env)) {
178
+ try {
179
+ const entry = snapshot.get(key)
180
+ if (entry !== undefined && typeof entry.value === 'string' && entry.value !== '') {
181
+ env[key] = entry.value
182
+ }
183
+ } catch {
184
+ // one broken lookup must not break mounting
185
+ }
186
+ }
187
+ return env
188
+ }
189
+
190
+ /** A cancellation that the runtime recognises as a cancellation, not a failure. */
191
+ function abortError(reason) {
192
+ const error = new Error(reason instanceof Error ? reason.message : 'tool call aborted')
193
+ error.name = 'AbortError'
194
+ return error
195
+ }
196
+
197
+ function failure(kind, run) {
198
+ const tail = run.stderr.trim().split('\n').slice(-3).join(' ').slice(0, 500)
199
+ return new InputError(kind, `${kind}: ${tail || 'không có thông tin lỗi'}`,
200
+ 'Xem log của core; chạy lại CLI với --json để lấy mã lỗi chi tiết.')
201
+ }
202
+
203
+ function parseCoreResult(result) {
204
+ const line = result.stdout.trim().split('\n').filter(Boolean).pop() ?? ''
205
+ try {
206
+ return JSON.parse(line)
207
+ } catch {
208
+ return null
209
+ }
210
+ }
211
+
212
+ const TEXT = (value) => [{ type: 'text', text: value }]
213
+
214
+ /**
215
+ * @param {object} ctx - Cordis context with the `tools` service injected.
216
+ * @param {object} [config] - profile patch config (`allowedRoots` required to use the tool).
217
+ */
218
+ /**
219
+ * Volatile fields reach apply() as {} placeholders: the Loader keeps their
220
+ * values in the settings document instead of the static config. Read them from
221
+ * the settings service once and refresh on its document event, so every tool
222
+ * call sees the current user layer.
223
+ * @param {object} ctx - Cordis context (settings service optional).
224
+ * @param {object} target - normalized settings object updated in place.
225
+ */
226
+ function attachLiveSettings(ctx, target) {
227
+ let bound = false
228
+ const read = () => {
229
+ try {
230
+ const rows = ctx.settings?.describe?.({ redactSecrets: true }) ?? []
231
+ // `ns` is the profile entry id, not the package name: a bundle row is
232
+ // `project-flow-explainer` while a hand-mounted row may use the package
233
+ // name instead. Accept either, and never match by substring (a prefix
234
+ // match would adopt another plugin's values).
235
+ const mine = rows.find((row) => SETTINGS_IDS.has(String(row.ns)))
236
+ // `value` is the resolved form: profile patch + user layer + defaults.
237
+ // `user` alone is just the profile's own patch layer, so using it would
238
+ // ignore the bundle's configured roots.
239
+ if (mine === undefined || mine.value === undefined) return
240
+ bound = true
241
+ const layer = {}
242
+ for (const [key, value] of Object.entries(mine.value)) {
243
+ if (value !== undefined && value !== null) layer[key] = value
244
+ }
245
+ Object.assign(target, normalizeConfig({ ...target, ...layer }))
246
+ } catch {
247
+ // settings unavailable (headless mount, unit test): keep the static config
248
+ }
249
+ }
250
+ read()
251
+ try {
252
+ ctx.on('settings/document-updated', (ns) => {
253
+ // Re-read on a matching namespace, and also while still unbound: the first
254
+ // read can run before the loader has published this entry's row.
255
+ if (!bound || SETTINGS_IDS.has(String(ns))) read()
256
+ })
257
+ } catch {
258
+ // no event service in this composition
259
+ }
260
+ }
261
+
262
+ export function apply(ctx, config = {}) {
263
+ const settings = normalizeConfig(config)
264
+ // The settings service is optional: a headless mount or a unit test has none.
265
+ // Declaring the dependency through ctx.inject keeps the mount valid either way.
266
+ try {
267
+ ctx.inject(['settings'], (scoped) => { attachLiveSettings(scoped, settings) })
268
+ } catch {
269
+ attachLiveSettings(ctx, settings)
270
+ }
271
+ // PFE_CORE_ROOT may come from the project `.env` or `$DSH_HOME/.env`, not only
272
+ // from the raw process environment.
273
+ const env = launchEnv(ctx)
274
+ const core = resolveCoreRoot({
275
+ coreRoot: settings.coreRoot,
276
+ packageRoot: PACKAGE_ROOT,
277
+ env,
278
+ })
279
+ const inFlight = new Set()
280
+
281
+ ctx.effect(() => () => {
282
+ for (const controller of inFlight) {
283
+ try {
284
+ controller.abort()
285
+ } catch {
286
+ /* already aborted */
287
+ }
288
+ }
289
+ inFlight.clear()
290
+ }, `${name}: dispose in-flight runs`)
291
+
292
+ ctx.tools.register({
293
+ name: TOOL_NAME,
294
+ description: [
295
+ 'Dựng sơ đồ quy trình từ một repository và một câu mô tả luồng bằng tiếng Việt.',
296
+ 'DÙNG KHI: cần hiểu một luồng trước khi sửa, hoặc giải thích cho người không đọc code. '
297
+ + 'KHÔNG DÙNG KHI: chỉ tra một hàm/route (dùng project_code_search).',
298
+ 'ĐIỀU KIỆN: repository_path tuyệt đối trong allowedRoots; flow_request mô tả luồng cụ thể.',
299
+ 'KẾT QUẢ: flow.html (offline, có chế độ Đơn giản), flow.json, overview.md, run.json nội bộ.',
300
+ 'TIẾP THEO: project_context_pack để biết file nào cần đọc trước khi sửa.',
301
+ 'GIỚI HẠN: phân tích tĩnh, không chạy code; verified = vị trí + quan hệ, không phải runtime.',
302
+ ].join('\n'),
303
+ parameters: {
304
+ type: 'object',
305
+ properties: {
306
+ repository_path: {
307
+ type: 'string',
308
+ description: 'Đường dẫn tuyệt đối tới thư mục repository, phải nằm trong allowedRoots.',
309
+ },
310
+ flow_request: {
311
+ type: 'string',
312
+ description: 'Mô tả flow bằng tiếng Việt thông thường, ví dụ: "từ lúc bấm xuất báo cáo '
313
+ + 'đến khi nhận được file, dữ liệu đi qua những bước nào và lỗi xử lý ở đâu".',
314
+ },
315
+ output_directory: {
316
+ type: 'string',
317
+ description: 'Chỉ chấp nhận "artifacts/flows" (hoặc đường dẫn tuyệt đối tương ứng). '
318
+ + 'Mặc định chính là thư mục đó.',
319
+ },
320
+ slug: {
321
+ type: 'string',
322
+ description: 'Tên thư mục artifact. Bỏ trống để tool tự sinh tên mới, tránh ghi đè.',
323
+ },
324
+ },
325
+ required: ['repository_path', 'flow_request'],
326
+ additionalProperties: false,
327
+ },
328
+ output: {
329
+ schema: {
330
+ type: 'object',
331
+ properties: {
332
+ status: { type: 'string', enum: ['ok'] },
333
+ flow_id: { type: 'string' },
334
+ slug: { type: 'string' },
335
+ repository: { type: 'string' },
336
+ repository_name: { type: 'string' },
337
+ path_base: { type: 'string' },
338
+ artifacts_dir: { type: 'string' },
339
+ artifacts: {
340
+ type: 'object',
341
+ properties: {
342
+ flow_json: { type: 'string' },
343
+ flow_html: { type: 'string' },
344
+ overview: { type: 'string' },
345
+ run: { type: 'string' },
346
+ },
347
+ required: ['flow_json', 'flow_html', 'overview', 'run'],
348
+ additionalProperties: false,
349
+ },
350
+ path_visibility: {
351
+ type: 'object',
352
+ properties: {
353
+ repository: { type: 'string' },
354
+ artifacts: { type: 'string' },
355
+ source_refs: { type: 'string' },
356
+ absolute_paths_returned: { type: 'boolean' },
357
+ },
358
+ required: ['repository', 'artifacts', 'source_refs', 'absolute_paths_returned'],
359
+ additionalProperties: false,
360
+ },
361
+ output_contract: {
362
+ type: 'object',
363
+ properties: {
364
+ public: { type: 'array', items: { type: 'string' } },
365
+ internal: { type: 'array', items: { type: 'string' } },
366
+ },
367
+ required: ['public', 'internal'],
368
+ additionalProperties: false,
369
+ },
370
+ counts: {
371
+ type: 'object',
372
+ properties: {
373
+ verified: { type: 'integer' },
374
+ partial: { type: 'integer' },
375
+ inferred: { type: 'integer' },
376
+ unknown: { type: 'integer' },
377
+ },
378
+ required: ['verified', 'partial', 'inferred', 'unknown'],
379
+ additionalProperties: false,
380
+ },
381
+ files_scanned: { type: 'integer' },
382
+ related_count: { type: 'integer' },
383
+ source_version: {
384
+ type: 'object',
385
+ properties: {
386
+ commit: { type: 'string' },
387
+ branch: { type: 'string' },
388
+ dirty: { type: 'boolean' },
389
+ dirty_files: { type: 'integer' },
390
+ },
391
+ required: ['commit', 'branch', 'dirty', 'dirty_files'],
392
+ additionalProperties: false,
393
+ },
394
+ warnings: { type: 'array', items: { type: 'string' } },
395
+ limits: { type: 'array', items: { type: 'string' } },
396
+ },
397
+ required: ['status', 'flow_id', 'slug', 'repository', 'repository_name',
398
+ 'path_base', 'artifacts_dir', 'artifacts', 'path_visibility', 'output_contract', 'counts',
399
+ 'files_scanned', 'related_count', 'source_version', 'warnings', 'limits'],
400
+ additionalProperties: false,
401
+ },
402
+ render(_args, value) {
403
+ const lines = [
404
+ `Sơ đồ: ${value.flow_id} (${value.counts.verified} verified · `
405
+ + `${value.counts.partial} partial · ${value.counts.inferred} inferred)`,
406
+ `Mở: ${value.artifacts.flow_html}`,
407
+ `Dữ liệu: ${value.artifacts.flow_json} · Giải thích: ${value.artifacts.overview}`,
408
+ `Ngoài luồng: ${value.related_count} file chỉ khớp từ khoá`,
409
+ ]
410
+ if (value.warnings.length > 0) lines.push(`Cảnh báo: ${value.warnings[0]}`)
411
+ lines.push('Đường dẫn tính từ repository. Không có nội dung source trong kết quả.')
412
+ lines.push('Tiếp theo: gọi project_context_pack trước khi sửa file trong luồng.')
413
+ return TEXT(lines.join('\n'))
414
+ },
415
+ },
416
+ timeoutMs: settings.timeoutMs,
417
+ // One call writes artifacts: never group it with a parallel batch.
418
+ isConcurrencySafe: () => false,
419
+ async execute(args, exec) {
420
+ // Defence in depth: the runtime validates the JSON schema first, but a
421
+ // direct execute() call must not be able to raise a raw TypeError.
422
+ assertObject(args, TOOL_NAME)
423
+ rejectUnknownKeys(args, ['repository_path', 'flow_request', 'output_directory', 'slug'], TOOL_NAME)
424
+ const repositoryPath = requiredString(args, 'repository_path', TOOL_NAME)
425
+ const request = requiredString(args, 'flow_request', TOOL_NAME)
426
+ const requestedOutput = optionalString(args, 'output_directory', TOOL_NAME)
427
+ const requestedSlug = optionalString(args, 'slug', TOOL_NAME)
428
+ const repository = resolveRepository(repositoryPath, {
429
+ allowedRoots: settings.allowedRoots,
430
+ })
431
+ const outputDirectory = resolveArtifactRoot(
432
+ repository.root, requestedOutput === '' ? undefined : requestedOutput)
433
+ if (exec?.signal?.aborted) throw abortError(exec.signal.reason)
434
+
435
+ const controller = new AbortController()
436
+ const forwardAbort = () => controller.abort(exec.signal.reason)
437
+ if (exec?.signal) exec.signal.addEventListener('abort', forwardAbort, { once: true })
438
+ inFlight.add(controller)
439
+
440
+ let run
441
+ try {
442
+ run = await runCore({
443
+ pythonPath: settings.pythonPath,
444
+ coreRoot: core.root,
445
+ script: core.script,
446
+ repository: repository.root,
447
+ request,
448
+ outputDirectory,
449
+ slug: requestedSlug && requestedSlug.trim() !== '' ? requestedSlug.trim() : undefined,
450
+ signal: controller.signal,
451
+ timeoutMs: settings.timeoutMs,
452
+ maxOutputBytes: settings.maxOutputBytes,
453
+ })
454
+ } finally {
455
+ inFlight.delete(controller)
456
+ if (exec?.signal) exec.signal.removeEventListener('abort', forwardAbort)
457
+ }
458
+
459
+ // Cancellation keeps its own identity: the runtime maps an Error named
460
+ // `AbortError` to code ABORTED, so never dress it as a business failure.
461
+ if (run.aborted) throw abortError(exec?.signal?.reason)
462
+ if (run.timedOut) {
463
+ throw new InputError('core_timeout',
464
+ `Core vượt quá ${settings.timeoutMs} ms và đã bị dừng.`,
465
+ 'Tăng config.timeoutMs hoặc phân tích một luồng hẹp hơn.')
466
+ }
467
+
468
+ const payload = parseCoreResult(run)
469
+ if (payload === null) {
470
+ throw failure(run.code === null ? 'core_spawn_failed' : 'core_failed', run)
471
+ }
472
+ if (payload.status === 'error') {
473
+ throw new InputError(payload.code, payload.message, payload.hint)
474
+ }
475
+ if (run.code !== 0) throw failure('core_failed', run)
476
+
477
+ const source = payload.source ?? {}
478
+ // Canonical output is model-facing, so it carries repository-relative
479
+ // paths only. No DSH presentation boundary has been verified, so an
480
+ // absolute workstation path must not leave this tool.
481
+ const relative = (value) => {
482
+ if (typeof value !== 'string' || value === '') return ''
483
+ const rel = path.relative(repository.root, value)
484
+ return rel.split(path.sep).join('/')
485
+ }
486
+ const artifactsDir = relative(payload.artifacts_dir)
487
+ return {
488
+ status: 'ok',
489
+ flow_id: payload.flow_id,
490
+ slug: payload.slug,
491
+ repository: payload.repository_name ?? path.basename(repository.root),
492
+ repository_name: payload.repository_name ?? path.basename(repository.root),
493
+ path_base: 'repository',
494
+ artifacts_dir: artifactsDir,
495
+ artifacts: {
496
+ flow_json: relative(payload.paths.flow_json),
497
+ flow_html: relative(payload.paths.flow_html),
498
+ overview: relative(payload.paths.overview),
499
+ run: relative(payload.paths.run),
500
+ },
501
+ path_visibility: {
502
+ repository: 'model-facing (name only)',
503
+ artifacts: 'model-facing (repository-relative)',
504
+ source_refs: 'model-facing (repository-relative)',
505
+ absolute_paths_returned: false,
506
+ },
507
+ output_contract: {
508
+ public: payload.contract?.public ?? ['flow.json', 'flow.html', 'overview.md'],
509
+ internal: payload.contract?.internal ?? ['run.json'],
510
+ },
511
+ counts: {
512
+ verified: payload.counts?.verified ?? 0,
513
+ partial: payload.counts?.partial ?? 0,
514
+ inferred: payload.counts?.inferred ?? 0,
515
+ unknown: payload.counts?.unknown ?? 0,
516
+ },
517
+ files_scanned: payload.files_scanned ?? 0,
518
+ related_count: Array.isArray(payload.related) ? payload.related.length : 0,
519
+ source_version: {
520
+ commit: source.commit ?? '',
521
+ branch: source.branch ?? '',
522
+ dirty: Boolean(source.dirty),
523
+ dirty_files: source.dirty_files ?? 0,
524
+ },
525
+ warnings: Array.isArray(payload.warnings) ? payload.warnings : [],
526
+ limits: Array.isArray(payload.limits) ? payload.limits : [],
527
+ }
528
+ },
529
+ })
530
+
531
+ // Knowledge layer: same path policy, same core subprocess, separate tools.
532
+ for (const definition of knowledgeTools({ settings, core, inFlight })) {
533
+ ctx.tools.register(definition)
534
+ }
535
+
536
+ // Human entry point: /project-flow-explainer <request>. Optional service — a
537
+ // headless composition has no command adapter, and the plugin must still
538
+ // mount there (the tools are what that composition needs).
539
+ try {
540
+ ctx.inject(['commands'], (scoped) => {
541
+ scoped.commands.register(flowCommand({ ctx: scoped, settings, core }))
542
+ })
543
+ } catch {
544
+ // no command service in this composition: tools remain the entry point
545
+ }
546
+ }