@twinsearth/dsh-fang 3.0.10 → 3.1.2

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 (39) hide show
  1. package/client.js +1511 -1
  2. package/cordis.patch.yml +9 -0
  3. package/package.json +6 -2
  4. package/src/compose.mjs +4 -1
  5. package/src/kernel/paths.mjs +9 -1
  6. package/src/kernel/role.mjs +1 -0
  7. package/src/kernel/types.mjs +5 -1
  8. package/src/lib/ai-secret-store.mjs +202 -0
  9. package/src/lib/boot-guard.mjs +182 -0
  10. package/src/lib/business-producers.mjs +109 -0
  11. package/src/lib/compat.mjs +1 -1
  12. package/src/lib/composer-journal.mjs +8 -0
  13. package/src/lib/decision-events.mjs +129 -0
  14. package/src/lib/decision-ingest-client.mjs +41 -0
  15. package/src/lib/decision-outbox.mjs +129 -0
  16. package/src/lib/desktop-launch.mjs +138 -0
  17. package/src/lib/fork-config-lock.mjs +65 -2
  18. package/src/lib/fork-supervision-settings.mjs +58 -0
  19. package/src/lib/mirror-official-source.mjs +93 -0
  20. package/src/lib/mirror.mjs +10 -3
  21. package/src/lib/producer-contract.mjs +162 -0
  22. package/src/lib/restart-contract.mjs +650 -0
  23. package/src/lib/rule-registry.mjs +69 -0
  24. package/src/lib/ssrf-guard.mjs +170 -0
  25. package/src/lib/umbrella.mjs +143 -18
  26. package/src/plugins/adapter.mjs +31 -2
  27. package/src/plugins/approver.mjs +423 -40
  28. package/src/plugins/decision-center.mjs +2255 -0
  29. package/src/plugins/forker.mjs +33 -2
  30. package/src/plugins/healer.mjs +53 -20
  31. package/src/plugins/imports.mjs +48 -0
  32. package/src/plugins/orchestrator.mjs +818 -42
  33. package/src/plugins/restart-guard.mjs +645 -52
  34. package/src/plugins/scorer.mjs +227 -15
  35. package/src/plugins/umbrella.mjs +18 -14
  36. package/tools/boot-guard.mjs +95 -0
  37. package/tools/decision-ingest.mjs +53 -0
  38. package/tools/desktop-launch.mjs +71 -0
  39. package/tools/fangctl.mjs +229 -1
@@ -22,7 +22,7 @@
22
22
  import fs from 'node:fs'
23
23
  import path from 'node:path'
24
24
  import { SERVICE, AUDIT, ROLE, z, readJson, roleGate } from '../kernel/index.mjs'
25
- import { scanSource, importsToSignals } from './imports.mjs'
25
+ import { scanSource, scanDeep, importsToSignals } from './imports.mjs'
26
26
 
27
27
  export const name = 'fang-scorer'
28
28
  export const inject = []
@@ -148,8 +148,9 @@ export function basisOf(environment, bands = null) {
148
148
  */
149
149
  export function scoreScan(signals, pkg = {}, bands = BAND_DEFAULTS.mother) {
150
150
  const thresholds = resolveBands(ROLE.MOTHER, bands)
151
+ const c3 = { count: 0, core: false, graced: false, applied: false }
151
152
  if (pkg?.dsh?.hotReload === false) {
152
- return { grade: 'E', S: 100, veto: true, degraded: false, perDim: {}, reasons: ['hotReload-false'] }
153
+ return { grade: 'E', S: 100, veto: true, degraded: false, perDim: {}, reasons: ['hotReload-false'], c3 }
153
154
  }
154
155
 
155
156
  const reasons = []
@@ -164,11 +165,17 @@ export function scoreScan(signals, pkg = {}, bands = BAND_DEFAULTS.mother) {
164
165
  if (fam === 'C3') {
165
166
  const services = Array.isArray(s?.evidence?.services) ? s.evidence.services : []
166
167
  const core = services.some(x => ['sessions', 'registry', 'loader'].includes(x))
167
- weight = (services.length > 8 || core) ? weight : 0
168
+ const graced = !(services.length > 8 || core)
169
+ c3.count = Math.max(c3.count, services.length)
170
+ c3.core = c3.core || core
171
+ c3.graced = graced
172
+ c3.applied = true
173
+ weight = graced ? 0 : weight
168
174
  if (weight <= 0) {
169
175
  reasons.push(`${s?.id}:C3-service-grace`)
170
176
  continue
171
177
  }
178
+ reasons.push(`${s?.id}:C3-service-risk(count=${services.length},core=${core})`)
172
179
  }
173
180
  if (!(weight > 0)) continue
174
181
 
@@ -191,7 +198,7 @@ export function scoreScan(signals, pkg = {}, bands = BAND_DEFAULTS.mother) {
191
198
  // 证据不全时不给 A/B:降 C。
192
199
  if (grade === 'A' || grade === 'B') grade = 'C'
193
200
  }
194
- return { grade, S, veto: false, degraded, perDim, reasons }
201
+ return { grade, S, veto: false, degraded, perDim, reasons, c3 }
195
202
  }
196
203
 
197
204
  /** 等级 → 动作灯色。B 级已可能含单一危险能力(child_process 单独 28 分 = B),不能判绿。 */
@@ -202,6 +209,33 @@ export function gradeToColor(grade) {
202
209
  : 'red'
203
210
  }
204
211
 
212
+ /**
213
+ * Resolve a plugin-relative file while proving it stays inside the plugin root.
214
+ * Absolute candidates, `..` escapes and symlinks pointing outside are rejected.
215
+ * Returns the checked absolute path, or null when the candidate is unsafe/missing.
216
+ */
217
+ export function resolvePluginFile(rootDir, candidate) {
218
+ const root = path.resolve(String(rootDir ?? ''))
219
+ const rel = String(candidate ?? '')
220
+ if (!rel || path.isAbsolute(rel)) return null
221
+ const target = path.resolve(root, rel)
222
+ const inside = (from, to) => {
223
+ const r = path.relative(from, to)
224
+ return r === '' || (!r.startsWith('..' + path.sep) && r !== '..' && !path.isAbsolute(r))
225
+ }
226
+ if (!inside(root, target)) return null
227
+ try {
228
+ const realRoot = fs.realpathSync(root)
229
+ const realTarget = fs.realpathSync(target)
230
+ if (!inside(realRoot, realTarget)) return null
231
+ const st = fs.statSync(target)
232
+ if (!st.isFile()) return null
233
+ return target
234
+ } catch {
235
+ return null
236
+ }
237
+ }
238
+
205
239
  /**
206
240
  * 入口候选顺序(评分与 healer 共用):manifest.entry → exports["."] → module → main
207
241
  * → index.js → lib/index.js → plugin.js。
@@ -228,7 +262,128 @@ export function entryCandidates(pkg, manifest = null) {
228
262
  return out
229
263
  }
230
264
 
231
- /** 对一段源码评分(纯函数,basis 注解由这里统一生成)。 */
265
+ /**
266
+ * Deep directory scan: entry + all local .js/.mjs/.cjs files (bounded), imports and
267
+ * a small call-layer signal set. It is still not an AST/call graph and says so via
268
+ * coverage/degradedReasons instead of pretending completeness.
269
+ */
270
+ const DEEP_MAX_FILES = 200
271
+ const DEEP_MAX_BYTES = 2 * 1024 * 1024
272
+ const DEEP_MAX_FILE_BYTES = 512 * 1024
273
+
274
+ function listDeepFiles(root) {
275
+ const files = []
276
+ const reasons = []
277
+ let bytes = 0
278
+ let skipped = 0
279
+ let truncated = false
280
+ const walk = (dir, relBase) => {
281
+ let entries
282
+ try {
283
+ entries = fs.readdirSync(dir, { withFileTypes: true })
284
+ } catch (e) {
285
+ skipped += 1
286
+ reasons.push(`readdir-failed:${relBase || '.'}:${String(e?.message ?? e)}`)
287
+ return
288
+ }
289
+ for (const entry of entries) {
290
+ if (truncated) return
291
+ if (entry.isSymbolicLink()) { skipped += 1; continue }
292
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name
293
+ if (entry.isDirectory()) {
294
+ if (entry.name === 'node_modules' || entry.name === '.git') continue
295
+ walk(path.join(dir, entry.name), rel)
296
+ continue
297
+ }
298
+ if (!entry.isFile() || !/\.(?:mjs|cjs|js)$/i.test(entry.name)) continue
299
+ const abs = resolvePluginFile(root, rel)
300
+ if (!abs) { skipped += 1; reasons.push(`unsafe-or-missing:${rel}`); continue }
301
+ let size = 0
302
+ try { size = fs.statSync(abs).size } catch { skipped += 1; reasons.push(`stat-failed:${rel}`); continue }
303
+ if (size > DEEP_MAX_FILE_BYTES) { skipped += 1; reasons.push(`file-too-large:${rel}`); continue }
304
+ if (files.length >= DEEP_MAX_FILES || bytes + size > DEEP_MAX_BYTES) {
305
+ truncated = true
306
+ break
307
+ }
308
+ files.push({ rel, abs })
309
+ bytes += size
310
+ }
311
+ }
312
+ walk(root, '')
313
+ return { files, skipped, truncated, reasons }
314
+ }
315
+
316
+ function scoreDeepDir(root, pkg, manifest, settings, basis) {
317
+ let entry = null
318
+ for (const candidate of entryCandidates(pkg, manifest)) {
319
+ const file = resolvePluginFile(root, candidate)
320
+ if (file) {
321
+ try {
322
+ if (fs.statSync(file).isFile()) { entry = { rel: candidate, abs: file }; break }
323
+ } catch { /* next */ }
324
+ }
325
+ }
326
+ if (!entry) return null
327
+ const listed = listDeepFiles(root)
328
+ const files = listed.files.some((file) => file.rel === entry.rel)
329
+ ? listed.files
330
+ : [{ rel: entry.rel, abs: entry.abs }, ...listed.files]
331
+ const scanSignals = []
332
+ const callSites = []
333
+ const scanWarnings = []
334
+ const reasons = [...listed.reasons]
335
+ let imports = 0
336
+ let scannedFiles = 0
337
+ for (const file of files) {
338
+ let source = ''
339
+ try {
340
+ source = fs.readFileSync(file.abs, 'utf8')
341
+ } catch (e) {
342
+ reasons.push(`read-failed:${file.rel}:${String(e?.message ?? e)}`)
343
+ continue
344
+ }
345
+ try {
346
+ const deep = scanDeep(source)
347
+ scannedFiles += 1
348
+ imports += deep.imports.length
349
+ scanWarnings.push(...deep.warnings.map((warning) => ({ ...warning, file: file.rel })))
350
+ for (const site of deep.callSites ?? []) callSites.push({ ...site, file: file.rel })
351
+ scanSignals.push(...deep.signals)
352
+ } catch (e) {
353
+ reasons.push(`scan-failed:${file.rel}:${String(e?.message ?? e)}`)
354
+ }
355
+ }
356
+ const degradedReasons = [...new Set(reasons)]
357
+ const scored = scoreScan(scanSignals, { ...(pkg ?? {}), __parseErrors: scanWarnings.length }, settings.thresholds)
358
+ const truncated = listed.truncated || listed.skipped > 0 || degradedReasons.length > 0
359
+ let grade = scored.grade
360
+ if (truncated && (grade === 'A' || grade === 'B')) grade = 'C'
361
+ const degraded = scored.degraded || truncated
362
+ return {
363
+ grade,
364
+ S: scored.S,
365
+ color: gradeToColor(grade),
366
+ veto: scored.veto,
367
+ degraded,
368
+ signals: scanSignals.map((signal) => ({ id: signal.id, weight: signal.weight })),
369
+ reasons: [...scored.reasons, ...degradedReasons.map((reason) => `deep-degraded:${reason}`)],
370
+ perDim: scored.perDim,
371
+ c3: scored.c3,
372
+ coverage: 'deep-import+call',
373
+ imports,
374
+ warnings: scanWarnings.length,
375
+ callSites,
376
+ scannedFiles,
377
+ skippedFiles: listed.skipped,
378
+ truncated: listed.truncated,
379
+ degradedReasons,
380
+ dir: root,
381
+ entry: entry.rel,
382
+ basis,
383
+ }
384
+ }
385
+
386
+
232
387
  function scoreSourceImpl(source, pkg = {}, opts = {}) {
233
388
  const environment = environmentOf(opts, ROLE.MOTHER)
234
389
  const bands = resolveBands(environment, opts && typeof opts === 'object' ? opts.thresholds : null)
@@ -237,7 +392,7 @@ function scoreSourceImpl(source, pkg = {}, opts = {}) {
237
392
 
238
393
  let scan
239
394
  try {
240
- scan = scanSource(text)
395
+ scan = opts && opts.deep === true ? scanDeep(text) : scanSource(text)
241
396
  } catch (e) {
242
397
  return {
243
398
  grade: 'E', S: 100, color: 'red', veto: false, degraded: true,
@@ -246,21 +401,25 @@ function scoreSourceImpl(source, pkg = {}, opts = {}) {
246
401
  basis,
247
402
  }
248
403
  }
249
- const mapped = importsToSignals(scan, pkg)
250
- const scored = scoreScan(mapped.signals, { ...(pkg ?? {}), __parseErrors: scan.warnings.length }, bands)
404
+ const mappedSignals = scan.signals ?? importsToSignals(scan, pkg).signals
405
+ const coverage = scan.coverage ?? 'import-only'
406
+ const scored = scoreScan(mappedSignals, { ...(pkg ?? {}), __parseErrors: scan.warnings.length }, bands)
251
407
  return {
252
408
  grade: scored.grade,
253
409
  S: scored.S,
254
410
  color: gradeToColor(scored.grade),
255
411
  veto: scored.veto,
256
412
  degraded: scored.degraded,
257
- signals: mapped.signals.map(s => ({ id: s.id, weight: s.weight })),
413
+ signals: mappedSignals.map(s => ({ id: s.id, weight: s.weight })),
258
414
  reasons: scored.reasons,
259
415
  // 附加证据(契约允许附加字段,编排器/UI 可直接用)
260
416
  perDim: scored.perDim,
261
- coverage: mapped.coverage,
417
+ c3: scored.c3,
418
+ coverage,
262
419
  imports: scan.imports.length,
263
420
  warnings: scan.warnings.length,
421
+ ...(scan.callSites ? { callSites: scan.callSites } : {}),
422
+ ...(opts && opts.deep === true ? { scannedFiles: 1 } : {}),
264
423
  basis,
265
424
  }
266
425
  }
@@ -304,6 +463,8 @@ export function apply(ctx, config) {
304
463
  const environment = gate.role
305
464
  const policy = {
306
465
  allowlist: Array.isArray(cfg.allowlist) ? cfg.allowlist.map(String) : [],
466
+ // allowlist is policy evidence only: it never lowers the static risk score.
467
+ allowlistUsedForScoring: false,
307
468
  environment,
308
469
  thresholds,
309
470
  }
@@ -312,8 +473,23 @@ export function apply(ctx, config) {
312
473
  try { safeGet(ctx, SERVICE.auditor)?.append?.(kind, data) } catch { /* 审计缺失不得影响评分 */ }
313
474
  }
314
475
 
315
- /** opts.environment 优先;缺省用本实例部署环境。 */
316
- const settingsFor = (opts) => ({ environment: environmentOf(opts, environment), thresholds })
476
+ /** opts.environment 优先;缺省用本实例部署环境。可选的临时 bands 只能收紧,不能放宽。 */
477
+ const settingsFor = (opts) => {
478
+ const env = environmentOf(opts, environment)
479
+ const base = resolveBands(env, thresholds)
480
+ const requested = opts && typeof opts === 'object' ? opts.thresholds : null
481
+ if (!requested || typeof requested !== 'object') {
482
+ return { environment: env, thresholds: base, deep: opts?.deep === true }
483
+ }
484
+ const candidate = resolveBands(env, requested)
485
+ const tightened = {
486
+ a: Math.min(base.a, candidate.a),
487
+ b: Math.min(base.b, candidate.b),
488
+ c: Math.min(base.c, candidate.c),
489
+ d: Math.min(base.d, candidate.d),
490
+ }
491
+ return { environment: env, thresholds: tightened, deep: opts?.deep === true }
492
+ }
317
493
 
318
494
  const service = {
319
495
  policy,
@@ -330,18 +506,53 @@ export function apply(ctx, config) {
330
506
  },
331
507
 
332
508
  scoreSource(source, pkg = {}, opts = {}) {
333
- return scoreSourceImpl(source, pkg ?? {}, settingsFor(opts))
509
+ const out = scoreSourceImpl(source, pkg ?? {}, settingsFor(opts))
510
+ // Hot path stays silent by default; callers that need an audit trail can
511
+ // opt in without making every umbrella source score write a ledger row.
512
+ if (opts && typeof opts === 'object' && opts.audit === true) {
513
+ audit(AUDIT.SCORE, {
514
+ component: name,
515
+ scope: 'source',
516
+ grade: out.grade,
517
+ S: out.S,
518
+ degraded: out.degraded,
519
+ environment: out.basis?.environment ?? null,
520
+ signals: out.signals.map(s => s.id),
521
+ })
522
+ }
523
+ return out
334
524
  },
335
525
 
336
526
  scoreDir(dir, manifest = null, opts = {}) {
337
527
  const settings = settingsFor(opts)
338
528
  const basis = basisOf(settings.environment, resolveBands(settings.environment, settings.thresholds))
339
529
  const abs = path.resolve(String(dir ?? ''))
340
- const pkg = readJson(path.join(abs, 'package.json'), null) ?? {}
530
+ const pkgFile = resolvePluginFile(abs, 'package.json')
531
+ const pkg = pkgFile ? (readJson(pkgFile, null) ?? {}) : {}
532
+ if (settings.deep === true) {
533
+ const deep = scoreDeepDir(abs, pkg, manifest, settings, basis)
534
+ if (deep) {
535
+ audit(AUDIT.SCORE, {
536
+ component: name,
537
+ dir: abs,
538
+ entry: deep.entry,
539
+ grade: deep.grade,
540
+ S: deep.S,
541
+ veto: deep.veto,
542
+ degraded: deep.degraded,
543
+ environment: deep.basis.environment,
544
+ coverage: deep.coverage,
545
+ scannedFiles: deep.scannedFiles,
546
+ signals: deep.signals.map(s => s.id),
547
+ })
548
+ return deep
549
+ }
550
+ }
341
551
  let src = null
342
552
  let entry = null
343
553
  for (const candidate of entryCandidates(pkg, manifest)) {
344
- const file = path.join(abs, candidate)
554
+ const file = resolvePluginFile(abs, candidate)
555
+ if (!file) continue
345
556
  try {
346
557
  const st = fs.statSync(file)
347
558
  if (!st.isFile()) continue
@@ -405,6 +616,7 @@ export const _internals = {
405
616
  normalizeBands,
406
617
  normalizeThresholds,
407
618
  resolveBands,
619
+ resolvePluginFile,
408
620
  basisOf,
409
621
  environmentOf,
410
622
  normalizeEnvironment,
@@ -26,7 +26,7 @@ import {
26
26
  createRuleRegistry,
27
27
  isLockedRule,
28
28
  loadRuleConfigFile,
29
- watchRuleConfigFile,
29
+ watchRuleConfigFiles,
30
30
  } from '../lib/rule-registry.mjs'
31
31
 
32
32
  export const name = 'fang-umbrella'
@@ -227,17 +227,12 @@ export function apply(ctx, config) {
227
227
  let ruleWatcher = null
228
228
  const reloadRules = () => applyAllLayers()
229
229
 
230
- const watchedFile = projectFilePath || envFilePath || baselinePath
231
- if (watchedFile.length > 0 && cfg.rulesWatch) {
232
- ruleWatcher = watchRuleConfigFile(watchedFile, ruleRegistry, (result) => {
233
- ruleConfigStatus = {
234
- ...ruleConfigStatus,
235
- applied: result.applied === true,
236
- ruleCount: ruleRegistry.ids().length,
237
- warnings: result.warnings ?? ruleConfigStatus.warnings,
238
- errors: result.errors ?? [],
239
- appliedAt: Date.now(),
240
- }
230
+ const watchedFiles = layerCandidates.map((layer) => layer.file)
231
+ if (watchedFiles.length > 0 && cfg.rulesWatch) {
232
+ ruleWatcher = watchRuleConfigFiles(watchedFiles, () => {
233
+ // Re-read every layer, not just the file that changed: later layers override
234
+ // earlier ones by id, so a single-layer applyConfig would discard the stack.
235
+ applyAllLayers()
241
236
  }, { debounceMs: cfg.rulesDebounceMs, logger: ctx.logger })
242
237
  ctx.effect(() => () => { try { ruleWatcher?.stop?.() } catch { /* ignore */ } })
243
238
  }
@@ -248,9 +243,17 @@ export function apply(ctx, config) {
248
243
  floorTable: cfg.gradeFloorTable,
249
244
  cacheSize: cfg.cacheSize,
250
245
  registry: ruleRegistry,
246
+ decisionCenter: () => safeGet(ctx, SERVICE.decisionCenter),
251
247
  audit(record) {
252
- if (!cfg.auditDecisions) return
253
- try { safeGet(ctx, SERVICE.auditor)?.append?.(AUDIT.UMBRELLA_DECISION, record) } catch { /* 审计缺失不影响决策 */ }
248
+ if (!cfg.auditDecisions) return { ok: true, skipped: true }
249
+ const auditor = safeGet(ctx, SERVICE.auditor)
250
+ if (!auditor || typeof auditor.append !== 'function') return { ok: false, reason: 'auditor-unavailable' }
251
+ try {
252
+ auditor.append(AUDIT.UMBRELLA_DECISION, record)
253
+ return { ok: true }
254
+ } catch (error) {
255
+ return { ok: false, reason: 'audit-failed', error: String(error?.message ?? error) }
256
+ }
254
257
  },
255
258
  })
256
259
 
@@ -333,6 +336,7 @@ export function apply(ctx, config) {
333
336
  matchedRule: base.matchedRule,
334
337
  category: base.category,
335
338
  tags: base.tags,
339
+ trusted: base.trusted === true,
336
340
  reason: base.reason,
337
341
  evidence: base.evidence,
338
342
  target: base.target,
@@ -0,0 +1,95 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // tools/boot-guard.mjs — DSH 启动前/发布前插件树自检。
3
+ //
4
+ // node tools/boot-guard.mjs --profile-dir <profile> # dry-run:检查行/模块/import
5
+ // node tools/boot-guard.mjs --profile-dir <profile> --apply # 禁用失败行(写 profile patch + 备份)
6
+ // node tools/boot-guard.mjs --profile-dir <profile> --safe-mode # 禁用全部 fang 行(安全模式)
7
+ //
8
+ // 只处理 fang bundle 的行;不碰 DSH 核心/其他插件;写 profile 前备份 .bak-<ts>。
9
+ import path from 'node:path'
10
+
11
+ import {
12
+ applyDisabledRows,
13
+ checkBundleRows,
14
+ findFangPackageDir,
15
+ readBundleRows,
16
+ readPackageName,
17
+ smokePackage,
18
+ } from '../src/lib/boot-guard.mjs'
19
+
20
+ function parseArgs(argv = []) {
21
+ const out = { profileDir: '', pkgDir: '', candidateDir: '', apply: false, safeMode: false, json: false, timeoutMs: 8000 }
22
+ for (let index = 0; index < argv.length; index += 1) {
23
+ const arg = argv[index]
24
+ if (arg === '--apply') { out.apply = true; continue }
25
+ if (arg === '--safe-mode') { out.safeMode = true; continue }
26
+ if (arg === '--json') { out.json = true; continue }
27
+ if (arg === '--profile-dir') { out.profileDir = String(argv[++index] ?? ''); continue }
28
+ if (arg === '--pkg-dir') { out.pkgDir = String(argv[++index] ?? ''); continue }
29
+ if (arg === '--candidate-dir') { out.candidateDir = String(argv[++index] ?? ''); continue }
30
+ if (arg === '--timeout') { out.timeoutMs = Math.max(1000, Number(argv[++index]) || 8000); continue }
31
+ throw new Error(`unknown argument: ${arg}`)
32
+ }
33
+ return out
34
+ }
35
+
36
+ const args = parseArgs(process.argv.slice(2))
37
+ // 更新器候选包冒烟:不读 profile、不写任何文件,只报告是否可转正。
38
+ if (args.candidateDir) {
39
+ const candidateDir = path.resolve(args.candidateDir)
40
+ const smoke = smokePackage(candidateDir, { timeoutMs: args.timeoutMs })
41
+ const result = { candidateDir, ...smoke }
42
+ if (args.json) console.log(JSON.stringify(result, null, 2))
43
+ else console.log(`${smoke.ok ? 'PASS' : 'FAIL'} candidate smoke ${candidateDir}${smoke.ok ? '' : ' — ' + (smoke.error ?? 'no apply()')}`)
44
+ process.exit(smoke.ok ? 0 : 1)
45
+ }
46
+ const profileDir = path.resolve(args.profileDir || '')
47
+ if (!args.profileDir) {
48
+ console.error('usage: node tools/boot-guard.mjs --profile-dir <profile> [--apply|--safe-mode] [--json]')
49
+ process.exit(2)
50
+ }
51
+ const result = { profileDir, ok: false, checked: 0, findings: [], applied: null }
52
+ try {
53
+ const pkgDir = args.pkgDir ? path.resolve(args.pkgDir) : findFangPackageDir(profileDir)
54
+ if (!pkgDir) {
55
+ result.findings = [{ code: 'fang-package-not-found', level: 'block', detail: profileDir }]
56
+ } else {
57
+ result.packageDir = pkgDir
58
+ const parsed = readBundleRows(pkgDir)
59
+ if (!parsed.ok) result.findings.push({ code: 'bundle-patch-invalid', level: 'block', detail: parsed.error })
60
+ result.rows = parsed.rows.length
61
+ if (parsed.rows.length > 0) {
62
+ const checked = checkBundleRows(parsed.rows, { profileDir, ownPackage: readPackageName(pkgDir), timeoutMs: args.timeoutMs })
63
+ result.ok = checked.ok
64
+ result.checked = checked.checked
65
+ result.findings = [...result.findings, ...checked.findings]
66
+ } else if (parsed.ok) {
67
+ result.ok = true
68
+ }
69
+ if (args.apply || args.safeMode) {
70
+ const ids = args.safeMode
71
+ ? parsed.rows.map((row) => row.id)
72
+ : [...new Set(result.findings.filter((finding) => finding.level === 'block' && finding.id).map((finding) => finding.id))]
73
+ if (!ids.length) {
74
+ result.applied = { tried: false, reason: 'nothing-to-disable' }
75
+ } else {
76
+ result.applied = applyDisabledRows(profileDir, ids)
77
+ // 失败行已写 disabled:true(profile 覆盖层会跳过它们)→ 本次 guard 视为已恢复。
78
+ if (result.applied.ok) result.ok = true
79
+ }
80
+ }
81
+ }
82
+ } catch (error) {
83
+ result.findings = [{ code: 'boot-guard-threw', level: 'block', detail: String(error?.message ?? error) }]
84
+ }
85
+ if (args.json) {
86
+ console.log(JSON.stringify(result, null, 2))
87
+ } else {
88
+ console.log(`${result.ok ? 'PASS' : 'FAIL'} boot-guard ${result.profileDir}`)
89
+ for (const finding of result.findings) console.log(` ${finding.level}: ${finding.code}${finding.id ? ' ' + finding.id : ''}${finding.detail ? ' — ' + finding.detail : ''}`)
90
+ if (result.applied) console.log(` applied: ${JSON.stringify(result.applied)}`)
91
+ if (!result.ok && !args.apply && !args.safeMode) {
92
+ console.log(' hint: add --apply to disable failing rows (profile patch backup is written), or --safe-mode')
93
+ }
94
+ }
95
+ process.exit(result.ok ? 0 : 1)
@@ -0,0 +1,53 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ //
4
+ // decision-ingest CLI — 独立进程把 ticket 送进母体决策中心的最低成本方式:
5
+ // node tools/decision-ingest.mjs --outbox-dir <dir> --payload '{"producer":"PJM",...}'
6
+ // node tools/decision-ingest.mjs --outbox-dir <dir> --flush
7
+ // 母体地址默认读 env DSH_FANG_MOTHER,也可 --mother-dir 显式指定。
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+ import process from 'node:process'
11
+
12
+ import { createForkIngestClient } from '../src/lib/decision-ingest-client.mjs'
13
+
14
+ function parseArgs(argv = []) {
15
+ const out = { payload: '', payloadFile: '', outboxDir: '', motherDir: '', flush: false, json: false }
16
+ for (let i = 0; i < argv.length; i += 1) {
17
+ const arg = argv[i]
18
+ if (arg === '--flush') { out.flush = true; continue }
19
+ if (arg === '--json') { out.json = true; continue }
20
+ const next = () => argv[++i]
21
+ if (arg === '--payload') { out.payload = String(next() ?? ''); continue }
22
+ if (arg === '--payload-file') { out.payloadFile = String(next() ?? ''); continue }
23
+ if (arg === '--outbox-dir') { out.outboxDir = String(next() ?? ''); continue }
24
+ if (arg === '--mother-dir') { out.motherDir = String(next() ?? ''); continue }
25
+ throw new Error(`unknown argument: ${arg}`)
26
+ }
27
+ return out
28
+ }
29
+
30
+ async function main() {
31
+ const args = parseArgs(process.argv.slice(2))
32
+ const outboxDir = args.outboxDir || process.env.DSH_FANG_INGEST_OUTBOX || path.join(process.cwd(), '.fang-decision-outbox')
33
+ const motherDir = args.motherDir || process.env.DSH_FANG_MOTHER || ''
34
+ const client = createForkIngestClient({ dataDir: outboxDir, motherDataDir: motherDir })
35
+ let payload = null
36
+ if (args.payload) payload = JSON.parse(args.payload)
37
+ else if (args.payloadFile) payload = JSON.parse(fs.readFileSync(args.payloadFile, 'utf8'))
38
+ const result = {}
39
+ if (payload) result.submitted = await client.submit(payload)
40
+ if (args.flush || !payload) result.flushed = await client.flush()
41
+ result.pending = client.pending()
42
+ if (args.json) console.log(JSON.stringify(result))
43
+ else {
44
+ if (result.submitted) console.log(result.submitted.queued ? `queued: ${result.submitted.outboxId}` : `sent: ${result.submitted.ticket?.id ?? 'ok'}`)
45
+ if (result.flushed) console.log(`flush: sent=${result.flushed.sent} failed=${result.flushed.failed} remaining=${result.flushed.remaining}`)
46
+ console.log(`pending: ${result.pending}`)
47
+ }
48
+ }
49
+
50
+ main().catch((error) => {
51
+ console.error(`[decision-ingest] ${String(error?.message ?? error)}`)
52
+ process.exitCode = 1
53
+ })
@@ -0,0 +1,71 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ //
4
+ // 启动 DSH Desktop 并把它的重启权交给 restart-supervisor(默认 dry-run)。
5
+ //
6
+ // node tools/desktop-launch.mjs --exe "C:\\Path\\DSH Desktop.exe" --data-root <fang-data>
7
+ // node tools/desktop-launch.mjs --execute --exe ... --data-root ... --arg=--some-desktop-flag
8
+ import { spawn } from 'node:child_process'
9
+ import process from 'node:process'
10
+
11
+ import { describeDesktopLaunch, detectDesktopProfileDir, resolveDesktopLaunch, runBootGuard } from '../src/lib/desktop-launch.mjs'
12
+
13
+ function parseArgs(argv = []) {
14
+ const out = { exe: '', dataRoot: '', profileDir: '', execute: false, args: [], bootGuard: true, safeModeOnFailure: true }
15
+ for (let i = 0; i < argv.length; i += 1) {
16
+ const arg = argv[i]
17
+ if (arg === '--execute') { out.execute = true; continue }
18
+ if (arg === '--exe') { out.exe = String(argv[++i] ?? ''); continue }
19
+ if (arg === '--data-root') { out.dataRoot = String(argv[++i] ?? ''); continue }
20
+ if (arg === '--profile-dir') { out.profileDir = String(argv[++i] ?? ''); continue }
21
+ if (arg === '--no-boot-guard') { out.bootGuard = false; continue }
22
+ if (arg === '--no-safe-mode') { out.safeModeOnFailure = false; continue }
23
+ if (arg.startsWith('--arg=')) { out.args.push(arg.slice('--arg='.length)); continue }
24
+ if (arg === '--arg') { out.args.push(String(argv[++i] ?? '')); continue }
25
+ throw new Error(`unknown argument: ${arg}`)
26
+ }
27
+ return out
28
+ }
29
+
30
+ const args = parseArgs(process.argv.slice(2))
31
+ // 未显式给 profile-dir 时,按 DSH_PROFILE_DIR / DSH_HOME/profiles/<profile> 自动探测;
32
+ // 探测不到就跳过自检(不阻塞启动),但会打印提示。
33
+ const detectedProfileDir = (args.profileDir || !args.bootGuard) ? '' : detectDesktopProfileDir({ env: process.env, args: args.args })
34
+ const profileDir = args.profileDir || detectedProfileDir
35
+ if (args.bootGuard && !args.profileDir && detectedProfileDir) console.log(`[boot-guard] auto-detected profile: ${detectedProfileDir}`)
36
+ const plan = resolveDesktopLaunch({ exe: args.exe, dataRoot: args.dataRoot, profileDir, args: args.args, execute: args.execute })
37
+ if (!plan.ok) {
38
+ console.error(`desktop-launch: ${plan.error}`)
39
+ process.exitCode = 2
40
+ } else {
41
+ console.log(describeDesktopLaunch(plan))
42
+ // 启动前自检:失败时(--execute 且未 --no-safe-mode)自动安全模式禁用 fang 行。
43
+ let guard = null
44
+ if (args.bootGuard && plan.profileDir) {
45
+ guard = runBootGuard(plan.profileDir, { dataRoot: plan.dataRoot, safeModeOnFailure: args.execute && args.safeModeOnFailure })
46
+ if (guard.ok && guard.safeModeApplied) {
47
+ console.warn(`[boot-guard] safe-mode applied: disabled ${guard.applied?.added ?? 0} fang row(s); fix profile before re-enabling`)
48
+ } else if (!guard.ok) {
49
+ console.error(`[boot-guard] blocked: ${guard.error ?? 'boot-guard-blocked'}`)
50
+ for (const finding of (guard.blocked ?? guard.findings ?? []).slice(0, 10)) {
51
+ console.error(` ${finding.level}: ${finding.code}${finding.id ? ' ' + finding.id : ''}${finding.detail ? ' — ' + finding.detail : ''}`)
52
+ }
53
+ if (!args.execute && args.safeModeOnFailure) console.error('[boot-guard] dry-run: would apply safe-mode on --execute')
54
+ console.error('[boot-guard] 不启动;先运行 tools/boot-guard.mjs --profile-dir <profile> --apply/--safe-mode 修复,或加 --no-boot-guard')
55
+ process.exitCode = 2
56
+ } else {
57
+ console.log(`[boot-guard] PASS checked=${guard.checked ?? 0} findings=${(guard.findings ?? []).length}`)
58
+ }
59
+ }
60
+ if (process.exitCode === 2) {
61
+ // fail-closed:自检失败绝不继续启动
62
+ } else if (plan.dryRun) {
63
+ console.log('dry-run:未启动。加 --execute 才会真正交给 supervisor。')
64
+ } else {
65
+ const child = spawn(plan.argv[0], plan.argv.slice(1), { stdio: 'inherit', windowsHide: false })
66
+ child.on('exit', (code, signal) => {
67
+ if (signal) process.kill(process.pid, signal)
68
+ else process.exitCode = code ?? 0
69
+ })
70
+ }
71
+ }