@twinsearth/dsh-fang 3.1.21 → 3.1.22

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 (113) hide show
  1. package/LICENSES/LICENSES/cordis-MIT.txt +39 -0
  2. package/client.js +197 -3
  3. package/defaults/defaults/umbrella-rules.yaml +113 -0
  4. package/package.json +2 -2
  5. package/sdk/sdk/README.md +65 -0
  6. package/sdk/sdk/examples/status-badge/README.md +16 -0
  7. package/sdk/sdk/examples/status-badge/client.js +60 -0
  8. package/sdk/sdk/examples/status-badge/cordis.patch.yml +7 -0
  9. package/sdk/sdk/examples/status-badge/index.js +12 -0
  10. package/sdk/sdk/examples/status-badge/package.json +24 -0
  11. package/sdk/sdk/templates/plugin/README.md +36 -0
  12. package/sdk/sdk/templates/plugin/client.js +35 -0
  13. package/sdk/sdk/templates/plugin/cordis.patch.yml +8 -0
  14. package/sdk/sdk/templates/plugin/icon.svg +5 -0
  15. package/sdk/sdk/templates/plugin/index.js +23 -0
  16. package/sdk/sdk/templates/plugin/locale/en.json +6 -0
  17. package/sdk/sdk/templates/plugin/package.json +36 -0
  18. package/src/kernel/types.mjs +1 -1
  19. package/src/src/compose.mjs +67 -0
  20. package/src/src/contract/client.js +86 -0
  21. package/src/src/contract/constants.js +79 -0
  22. package/src/src/contract/envelope.js +83 -0
  23. package/src/src/contract/index.js +19 -0
  24. package/src/src/contract/negotiate.js +106 -0
  25. package/src/src/contract/server.js +77 -0
  26. package/src/src/contract/transports.js +301 -0
  27. package/src/src/index.mjs +11 -0
  28. package/src/src/kernel/core.mjs +100 -0
  29. package/src/src/kernel/extensions.mjs +61 -0
  30. package/src/src/kernel/fsx.mjs +349 -0
  31. package/src/src/kernel/index.mjs +21 -0
  32. package/src/src/kernel/ledger.mjs +94 -0
  33. package/src/src/kernel/paths.mjs +182 -0
  34. package/src/src/kernel/role.mjs +68 -0
  35. package/src/src/kernel/rounds.mjs +172 -0
  36. package/src/src/kernel/schema.mjs +5 -0
  37. package/src/src/kernel/types.mjs +264 -0
  38. package/src/src/kernel/vendor/cosmokit.mjs +421 -0
  39. package/src/src/kernel/vendor/schemastery.mjs +638 -0
  40. package/src/src/lib/adapter-client.mjs +383 -0
  41. package/src/src/lib/adapter-protocol.mjs +243 -0
  42. package/src/src/lib/ai-secret-store.mjs +202 -0
  43. package/src/src/lib/boot-guard.mjs +182 -0
  44. package/src/src/lib/branch-store.mjs +84 -0
  45. package/src/src/lib/branch.mjs +74 -0
  46. package/src/src/lib/bridge-client.mjs +133 -0
  47. package/src/src/lib/broker-adapter.mjs +67 -0
  48. package/src/src/lib/broker.mjs +45 -0
  49. package/src/src/lib/business-producers.mjs +109 -0
  50. package/src/src/lib/command-cache.mjs +209 -0
  51. package/src/src/lib/compat.mjs +170 -0
  52. package/src/src/lib/composer-journal.mjs +128 -0
  53. package/src/src/lib/container/index.mjs +806 -0
  54. package/src/src/lib/decision-events.mjs +129 -0
  55. package/src/src/lib/decision-ingest-client.mjs +41 -0
  56. package/src/src/lib/decision-outbox.mjs +129 -0
  57. package/src/src/lib/default-essence.mjs +61 -0
  58. package/src/src/lib/desktop-launch.mjs +138 -0
  59. package/src/src/lib/essence.mjs +1211 -0
  60. package/src/src/lib/fork-client.mjs +410 -0
  61. package/src/src/lib/fork-config-lock.mjs +153 -0
  62. package/src/src/lib/fork-seed.mjs +304 -0
  63. package/src/src/lib/fork-supervision-settings.mjs +58 -0
  64. package/src/src/lib/fork-supervisor.mjs +122 -0
  65. package/src/src/lib/fs-guard.mjs +28 -0
  66. package/src/src/lib/http-auth.mjs +162 -0
  67. package/src/src/lib/idle-audit.mjs +178 -0
  68. package/src/src/lib/interaction-poke.mjs +61 -0
  69. package/src/src/lib/mirror-etag.mjs +92 -0
  70. package/src/src/lib/mirror-official-source.mjs +93 -0
  71. package/src/src/lib/mirror.mjs +478 -0
  72. package/src/src/lib/mother-link.mjs +156 -0
  73. package/src/src/lib/mutex.mjs +31 -0
  74. package/src/src/lib/permissions.mjs +115 -0
  75. package/src/src/lib/pnpm-store.mjs +189 -0
  76. package/src/src/lib/preferences.mjs +212 -0
  77. package/src/src/lib/producer-contract.mjs +162 -0
  78. package/src/src/lib/reflow.mjs +41 -0
  79. package/src/src/lib/remote.mjs +408 -0
  80. package/src/src/lib/restart-contract.mjs +650 -0
  81. package/src/src/lib/roots.mjs +30 -0
  82. package/src/src/lib/rule-registry.mjs +1101 -0
  83. package/src/src/lib/runtime-capture.mjs +307 -0
  84. package/src/src/lib/semaphore.mjs +34 -0
  85. package/src/src/lib/session-bundle.mjs +138 -0
  86. package/src/src/lib/session-format.mjs +658 -0
  87. package/src/src/lib/sse-parser.mjs +102 -0
  88. package/src/src/lib/ssrf-guard.mjs +170 -0
  89. package/src/src/lib/status-store.mjs +257 -0
  90. package/src/src/lib/task-handle.mjs +622 -0
  91. package/src/src/lib/ui-actions.mjs +55 -0
  92. package/src/src/lib/umbrella.mjs +1661 -0
  93. package/src/src/lib/upgrade-coordinator.mjs +107 -0
  94. package/src/src/lib/upgrade-status.mjs +43 -0
  95. package/src/src/plugins/adapter.mjs +1468 -0
  96. package/src/src/plugins/approver.mjs +1210 -0
  97. package/src/src/plugins/auditor.mjs +330 -0
  98. package/src/src/plugins/buffer-keeper.mjs +522 -0
  99. package/src/src/plugins/decision-center.mjs +2265 -0
  100. package/src/src/plugins/forker.mjs +1594 -0
  101. package/src/src/plugins/healer.mjs +664 -0
  102. package/src/src/plugins/hot-reloader.mjs +274 -0
  103. package/src/src/plugins/imports.mjs +247 -0
  104. package/src/src/plugins/orchestrator.mjs +3806 -0
  105. package/src/src/plugins/restart-guard.mjs +948 -0
  106. package/src/src/plugins/router.mjs +714 -0
  107. package/src/src/plugins/scorer.mjs +624 -0
  108. package/src/src/plugins/session-bridge.mjs +166 -0
  109. package/src/src/plugins/session-catalog.mjs +771 -0
  110. package/src/src/plugins/session-router.mjs +125 -0
  111. package/src/src/plugins/session-sync.mjs +171 -0
  112. package/src/src/plugins/umbrella.mjs +419 -0
  113. package/tools/recover-queue.mjs +133 -0
@@ -0,0 +1,68 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // dsh-Fang kernel — deployment roles and the plugin/role matrix.
4
+ //
5
+ // The same bundle is installed in the mother and in every fork, so which half of a
6
+ // plugin activates must be decided at runtime: the forker launches a fork with
7
+ // DSH_FANG_ROLE=fork, and every plugin asks this module whether its role is enabled.
8
+ //
9
+ // Matrix is the product contract (docs/CONTRACTS-V2.md §2). Adding a plugin to a role
10
+ // here is the only place that decision lives.
11
+
12
+ export const ROLE = { MOTHER: 'mother', FORK: 'fork', CONSUMER: 'consumer' }
13
+
14
+ /** plugin key → roles in which the plugin activates. */
15
+ export const MATRIX = {
16
+ orchestrator: ['mother'],
17
+ forker: ['mother'],
18
+ restartGuard: ['mother'],
19
+ healer: ['fork'],
20
+ hotReloader: ['fork'],
21
+ adapter: ['fork'],
22
+ scorer: ['mother', 'fork'],
23
+ router: ['mother', 'fork'],
24
+ umbrella: ['mother', 'fork'],
25
+ approver: ['mother', 'fork'],
26
+ bufferKeeper: ['fork'],
27
+ auditor: ['mother', 'fork'],
28
+ sessionCatalog: ['mother'],
29
+ sessionBridge: ['mother'],
30
+ sessionSync: ['mother', 'consumer'],
31
+ sessionRouter: ['mother'],
32
+ decisionCenter: ['mother', 'fork'],
33
+ }
34
+
35
+ const VALID_ROLES = new Set([ROLE.MOTHER, ROLE.FORK, ROLE.CONSUMER])
36
+
37
+ /**
38
+ * The environment wins over config: a fork is started by the forker with
39
+ * DSH_FANG_ROLE=fork and must never be able to promote itself to a mother by config.
40
+ * @returns {'mother'|'fork'|'consumer'}
41
+ */
42
+ export function resolveRole({ cfgRole = '', env = process.env } = {}) {
43
+ const fromEnv = env?.DSH_FANG_ROLE
44
+ if (VALID_ROLES.has(fromEnv)) return fromEnv
45
+ if (VALID_ROLES.has(cfgRole)) return cfgRole
46
+ return ROLE.MOTHER
47
+ }
48
+
49
+ export function roleAllows(pluginKey, role) {
50
+ return (MATRIX[pluginKey] ?? []).includes(role)
51
+ }
52
+
53
+ /**
54
+ * Guard used at the top of every plugin's apply().
55
+ * @returns {{role:string, active:boolean, reason:string}}
56
+ */
57
+ export function roleGate(pluginKey, { cfgRole = '', env = process.env, logger = null } = {}) {
58
+ const role = resolveRole({ cfgRole, env })
59
+ const active = roleAllows(pluginKey, role)
60
+ const reason = active ? `${pluginKey} active in ${role}` : `${pluginKey} is not deployed in ${role}`
61
+ if (!active && logger && typeof logger.info === 'function') logger.info(reason)
62
+ return { role, active, reason }
63
+ }
64
+
65
+ /** Roles a plugin activates in — used by status surfaces and tests. */
66
+ export function rolesOf(pluginKey) {
67
+ return [...(MATRIX[pluginKey] ?? [])]
68
+ }
@@ -0,0 +1,172 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // dsh-Fang kernel — round (hot-update transaction) core.
4
+ // Zero node dependencies: every filesystem call comes through an injected fsApi,
5
+ // so the same logic runs under node:fs in the host and under a memory FS in a browser.
6
+ //
7
+ // fsApi contract (node:fs compatible subset):
8
+ // readdirSync, statSync, readFileSync, writeFileSync, mkdirSync, copyFileSync,
9
+ // unlinkSync, existsSync
10
+
11
+ const SKIP_NAMES = new Set(['changes.json', '.age.json', '.rounds'])
12
+
13
+ function hashHex(bytes) {
14
+ const data = typeof bytes === 'string' ? bytes : bufferLikeToString(bytes)
15
+ let h1 = 0x811c9dc5
16
+ let h2 = 0x01000193
17
+ for (let i = 0; i < data.length; i++) {
18
+ const c = data.charCodeAt(i) & 0xff
19
+ h1 = (h1 ^ c) * 16777619 >>> 0
20
+ h2 = (h2 + c * (i + 1)) >>> 0
21
+ }
22
+ return h1.toString(16).padStart(8, '0') + h2.toString(16).padStart(8, '0')
23
+ }
24
+
25
+ function bufferLikeToString(b) {
26
+ if (b == null) return ''
27
+ if (typeof b === 'string') return b
28
+ if (typeof b.toString === 'function') {
29
+ const s = b.toString('utf8')
30
+ if (typeof s === 'string' && !/^\[object/.test(s)) return s
31
+ }
32
+ if (b instanceof Uint8Array) return Array.from(b).map(x => String.fromCharCode(x)).join('')
33
+ return String(b)
34
+ }
35
+
36
+ export function createRounds(fsApi) {
37
+ const fs = fsApi
38
+ const join = (...parts) => parts.filter(p => p != null && p !== '').join('/').replace(/\/+/g, '/')
39
+ const parentOf = (p) => { const i = p.lastIndexOf('/'); return i > 0 ? p.slice(0, i) : '.' }
40
+ const roundsDirOf = (stagingDir, name) => stagingDir + '/' + name + '/.rounds'
41
+
42
+ const fileDigests = (dir) => {
43
+ const out = {}
44
+ const walk = (d, rel = '') => {
45
+ let names = []
46
+ try { names = fs.readdirSync(d) ?? [] } catch { return }
47
+ for (const n of names) {
48
+ const r = rel ? rel + '/' + n : n
49
+ if (SKIP_NAMES.has(r) || SKIP_NAMES.has(n)) continue
50
+ const p = d + '/' + n
51
+ let st
52
+ try { st = fs.statSync(p) } catch { continue }
53
+ if (st && typeof st.isDirectory === 'function' && st.isDirectory()) { walk(p, r); continue }
54
+ try { out[r] = hashHex(fs.readFileSync(p)) } catch { /* unreadable: skip */ }
55
+ }
56
+ }
57
+ walk(dir)
58
+ return out
59
+ }
60
+
61
+ const copyTreeInto = (srcDir, dstDir) => {
62
+ try { fs.mkdirSync(dstDir, { recursive: true }) } catch { /* ignore */ }
63
+ let names = []
64
+ try { names = fs.readdirSync(srcDir) ?? [] } catch { return }
65
+ for (const n of names) {
66
+ if (SKIP_NAMES.has(n)) continue
67
+ const p = srcDir + '/' + n
68
+ let st
69
+ try { st = fs.statSync(p) } catch { continue }
70
+ if (st && typeof st.isDirectory === 'function' && st.isDirectory()) { copyTreeInto(p, dstDir + '/' + n); continue }
71
+ try {
72
+ fs.mkdirSync(parentOf(dstDir + '/' + n), { recursive: true })
73
+ fs.copyFileSync(p, dstDir + '/' + n)
74
+ } catch { /* ignore */ }
75
+ }
76
+ }
77
+
78
+ const beginRound = ({ stagingDir, name, note = '', now = () => new Date().toISOString() }) => {
79
+ const stageDir = stagingDir + '/' + name
80
+ if (!fs.existsSync(stageDir)) return { ok: false, phase: 'not-in-staging' }
81
+ const roundId = 'r' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5)
82
+ const dir = roundsDirOf(stagingDir, name) + '/' + roundId
83
+ const preDir = dir + '/pre'
84
+ try { copyTreeInto(stageDir, preDir) } catch (e) {
85
+ return { ok: false, phase: 'copy-failed', error: String(e?.message ?? e) }
86
+ }
87
+ const manifest = { roundId, name, note: String(note ?? ''), at: now(), files: fileDigests(preDir) }
88
+ try { fs.writeFileSync(dir + '/manifest.json', JSON.stringify(manifest, null, 2)) } catch { /* ignore */ }
89
+ return { ok: true, phase: 'round-open', roundId, files: Object.keys(manifest.files).length }
90
+ }
91
+
92
+ const listRounds = ({ stagingDir, name }) => {
93
+ let ids = []
94
+ try { ids = fs.readdirSync(roundsDirOf(stagingDir, name)) ?? [] } catch { return [] }
95
+ const out = []
96
+ for (const id of ids) {
97
+ const dir = roundsDirOf(stagingDir, name) + '/' + id
98
+ let m = null
99
+ try { m = JSON.parse(bufferLikeToString(fs.readFileSync(dir + '/manifest.json'))) } catch { /* ignore */ }
100
+ if (m) out.push({ ...m, dir })
101
+ }
102
+ return out.sort((a, b) => (a.at < b.at ? 1 : -1))
103
+ }
104
+
105
+ const resetRound = ({ stagingDir, name, roundId } = {}) => {
106
+ const errors = []
107
+ const safeCopy = (src, dst) => {
108
+ try {
109
+ if (!fs.existsSync(src)) { errors.push({ src, error: 'missing-source' }); return false }
110
+ fs.mkdirSync(parentOf(dst), { recursive: true })
111
+ fs.copyFileSync(src, dst)
112
+ return true
113
+ } catch (e) { errors.push({ src, error: String(e?.message ?? e) }); return false }
114
+ }
115
+ const safeUnlink = (p) => {
116
+ try { if (fs.existsSync(p)) fs.unlinkSync(p); return true } catch (e) {
117
+ errors.push({ path: p, error: String(e?.message ?? e) }); return false
118
+ }
119
+ }
120
+ try {
121
+ const rounds = listRounds({ stagingDir, name })
122
+ if (!rounds.length) return { ok: false, phase: 'no-rounds', touched: [], errors }
123
+ const target = roundId ? rounds.find(r => r.roundId === roundId) : rounds[0]
124
+ if (!target) return { ok: false, phase: 'round-not-found', available: rounds.map(r => r.roundId), touched: [], errors }
125
+
126
+ const stageDir = stagingDir + '/' + name
127
+ const preDir = target.dir + '/pre'
128
+ const pre = fileDigests(preDir)
129
+ const cur = fileDigests(stageDir)
130
+
131
+ if (Object.keys(pre).length === 0 && Object.keys(cur).length > 0) {
132
+ return {
133
+ ok: false, phase: 'round-corrupt', roundId: target.roundId,
134
+ manifestFiles: Object.keys(target.files ?? {}).length,
135
+ currentFiles: Object.keys(cur).length, touched: [], errors,
136
+ }
137
+ }
138
+
139
+ const manifest = target.files && typeof target.files === 'object' ? target.files : null
140
+ const inManifest = (p) => !!manifest && Object.prototype.hasOwnProperty.call(manifest, p)
141
+ const touched = []
142
+
143
+ for (const [p, d] of Object.entries(cur)) {
144
+ if (pre[p] === d) continue
145
+ if (inManifest(p)) {
146
+ if (pre[p] !== undefined) {
147
+ if (safeCopy(preDir + '/' + p, stageDir + '/' + p)) touched.push({ path: p, action: 'restored' })
148
+ } else {
149
+ errors.push({ path: p, error: 'pre-image-missing' })
150
+ touched.push({ path: p, action: 'kept-missing-preimage' })
151
+ }
152
+ } else if (pre[p] !== undefined) {
153
+ if (safeCopy(preDir + '/' + p, stageDir + '/' + p)) touched.push({ path: p, action: 'restored' })
154
+ } else {
155
+ if (safeUnlink(stageDir + '/' + p)) touched.push({ path: p, action: 'removed' })
156
+ }
157
+ }
158
+ for (const p of Object.keys(pre)) {
159
+ if (cur[p] !== undefined) continue
160
+ if (safeCopy(preDir + '/' + p, stageDir + '/' + p)) touched.push({ path: p, action: 'recovered' })
161
+ }
162
+ const after = fileDigests(stageDir)
163
+ const clean = Object.keys(pre).length === Object.keys(after).length &&
164
+ Object.entries(pre).every(([k, v]) => after[k] === v)
165
+ return { ok: errors.length === 0, phase: 'reset', roundId: target.roundId, touched, clean, errors }
166
+ } catch (e) {
167
+ return { ok: false, phase: 'threw', error: String(e?.message ?? e), touched: [], errors }
168
+ }
169
+ }
170
+
171
+ return { fileDigests, copyTreeInto, beginRound, listRounds, resetRound, roundsDirOf, join }
172
+ }
@@ -0,0 +1,5 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // Vendored schemastery (link:-installed bundles cannot resolve @deepseek-ai/schemastery,
4
+ // so the schema library ships with the project). Same pattern as packages/shared/vendor.
5
+ export { default } from './vendor/schemastery.mjs'
@@ -0,0 +1,264 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // dsh-Fang kernel — the shared vocabulary of the 1 orchestrator + 9 sub-plugins.
4
+ // Kept as plain constants so plugin code, tests and the client half agree on names.
5
+
6
+ /** Host service keys. Every sub-plugin provides exactly one; subplugins read peers through `ctx.get`. */
7
+ export const SERVICE = {
8
+ orchestrator: 'fang',
9
+ forker: 'fangForker',
10
+ scorer: 'fangScorer',
11
+ healer: 'fangHealer',
12
+ approver: 'fangApprover',
13
+ hotReloader: 'fangHotReloader',
14
+ restart: 'fangRestart',
15
+ buffer: 'fangBuffer',
16
+ auditor: 'fangAudit',
17
+ router: 'fangRouter',
18
+ umbrella: 'fangUmbrella',
19
+ adapter: 'fangAdapter',
20
+ commercial: 'fangCommercial',
21
+ sessionCatalog: 'fangSessionCatalog',
22
+ sessionBridge: 'fangSessionBridge',
23
+ sessionSync: 'fangSessionSync',
24
+ sessionRouter: 'fangSessionRouter',
25
+ link: 'fangLink',
26
+ mirror: 'fangMirror',
27
+ decisionCenter: 'fangDecisionCenter',
28
+ contract: 'fangContract',
29
+ }
30
+
31
+ /** Loader row ids used by cordis.patch.yml. */
32
+ export const ROW = {
33
+ orchestrator: 'fang-orchestrator',
34
+ forker: 'fang-forker',
35
+ scorer: 'fang-scorer',
36
+ healer: 'fang-healer',
37
+ approver: 'fang-approver',
38
+ hotReloader: 'fang-hot-reloader',
39
+ restart: 'fang-restart-guard',
40
+ buffer: 'fang-buffer-keeper',
41
+ auditor: 'fang-auditor',
42
+ router: 'fang-router',
43
+ umbrella: 'fang-umbrella',
44
+ sessionCatalog: 'fang-session-catalog',
45
+ sessionBridge: 'fang-session-bridge',
46
+ sessionSync: 'fang-session-sync',
47
+ sessionRouter: 'fang-session-router',
48
+ decisionCenter: 'fang-decision-center',
49
+ }
50
+
51
+ export const FORK_STATUS = {
52
+ PROVISIONING: 'provisioning',
53
+ RUNNING: 'running',
54
+ CRASHED: 'crashed',
55
+ STOPPED: 'stopped',
56
+ REAPED: 'reaped',
57
+ }
58
+
59
+ /** Risk vocabulary shared by scorer / approver / restart-guard. */
60
+ export const RISK = { BLUE: 'blue', YELLOW: 'yellow', RED: 'red' }
61
+
62
+ /**
63
+ * Action light vocabulary (v2.7.6, `fang-umbrella`).
64
+ *
65
+ * `RISK` above is the *approval* enum of restart-guard (three levels, no "nothing to
66
+ * approve"). The umbrella light is four levels because it also has to say "no side
67
+ * effect at all" — green. Mapping: green → auto-allow, blue → auto-allow + mark,
68
+ * yellow → ask, red → ask(critical)/deny/delegate.
69
+ */
70
+ export const LIGHT = { GREEN: 'green', BLUE: 'blue', YELLOW: 'yellow', RED: 'red' }
71
+
72
+ /** Light severity order; higher rank == more dangerous. */
73
+ export const LIGHT_RANK = { green: 1, blue: 2, yellow: 3, red: 4 }
74
+
75
+
76
+ /** Static plugin grades (A safest .. E veto). */
77
+ export const GRADE = ['A', 'B', 'C', 'D', 'E']
78
+
79
+ export const GRADE_COLOR = { A: 'green', B: 'blue', C: 'yellow', D: 'red', E: 'red' }
80
+
81
+ /** Router outcomes. */
82
+ export const ROUTE = { SANDBOX: 'sandbox', CONTAINER: 'container', DENY: 'deny' }
83
+
84
+ /** Restart-guard state machine (mother level only). */
85
+ export const GUARD_STATE = {
86
+ IDLE: 'idle',
87
+ COLLECTING: 'collecting',
88
+ AWAITING: 'awaiting',
89
+ EXECUTING: 'executing',
90
+ }
91
+
92
+ /** Buffer watcher three-state judgement. */
93
+ export const BUFFER_STATE = { SETTLED: 'settled', WRITING: 'writing', PENDING_HIGH_RISK: 'pending-high-risk' }
94
+
95
+ /** Audit record kinds written by the auditor. */
96
+ export const AUDIT = {
97
+ BOOT: 'boot',
98
+ BOOT_VERIFY: 'boot-verify',
99
+ FORK_CREATED: 'fork-created',
100
+ FORK_STARTED: 'fork-started',
101
+ FORK_CRASHED: 'fork-crashed',
102
+ FORK_SUPERVISION: 'fork-supervision',
103
+ FORK_REAPED: 'fork-reaped',
104
+ FORK_HEALTH: 'fork-health',
105
+ PROMOTE_REQUESTED: 'promote-requested',
106
+ PROMOTE_COMMITTED: 'promote-committed',
107
+ PROMOTE_FAILED: 'promote-failed',
108
+ RESTART_REQUESTED: 'restart-requested',
109
+ RESTART_RESOLVED: 'restart-resolved',
110
+ RESTART_DENIED: 'restart-denied',
111
+ SHUTDOWN_GRACEFUL: 'shutdown-graceful',
112
+ APPROVAL_REQUESTED: 'approval-requested',
113
+ APPROVAL_DECIDED: 'approval-decided',
114
+ SNapshot_CREATED: 'snapshot-created',
115
+ ROLLBACK: 'rollback',
116
+ ROUND_OPEN: 'round-open',
117
+ ROUND_RESET: 'round-reset',
118
+ SCORE: 'score',
119
+ UMBRELLA_DECISION: 'umbrella-decision',
120
+ UMBRELLA_STRICT_MODE: 'umbrella-strict-mode',
121
+ ROUTE: 'route',
122
+ BUFFER_FLUSH: 'buffer-flush',
123
+ TASK_READY: 'task-ready',
124
+ TASK_ARCHIVED: 'task-archived',
125
+ TASK_RESTORED: 'task-restored',
126
+ ADAPTER_HANDSHAKE: 'adapter-handshake',
127
+ ROUTE_CONFIRMED: 'route-confirmed',
128
+ LINK_PROBE: 'link-probe',
129
+ RUNTIME_ERROR: 'runtime-error',
130
+ }
131
+
132
+ export const FANG_VERSION = '3.1.22'
133
+
134
+ /**
135
+ * @typedef {object} ForkInfo
136
+ * @property {string} forkId
137
+ * @property {string} taskTitle
138
+ * @property {'provisioning'|'running'|'crashed'|'stopped'|'reaped'} status
139
+ * @property {number|null} pid
140
+ * @property {number|null} port
141
+ * @property {string} homeDir
142
+ * @property {string} profile
143
+ * @property {string|null} url
144
+ * @property {number} createdAt
145
+ * @property {number} restarts
146
+ * @property {object|null} health
147
+ */
148
+
149
+ /**
150
+ * @typedef {object} Assessment
151
+ * @property {'A'|'B'|'C'|'D'|'E'} grade
152
+ * @property {number} score
153
+ * @property {'green'|'blue'|'yellow'|'red'} color
154
+ * @property {boolean} veto
155
+ * @property {string[]} reasons
156
+ * @property {{id:string, weight:number}[]} signals
157
+ */
158
+
159
+ /**
160
+ * @typedef {object} ImpactReport
161
+ * @property {string[]} activeForks
162
+ * @property {string[]} pendingPromotes
163
+ * @property {string[]} dirtyBuffers
164
+ * @property {number} activeSessions
165
+ */
166
+
167
+
168
+ /** Task lifecycle (v2): a task is the product-facing unit, a fork is its process. */
169
+ export const TASK_STATUS = {
170
+ PROVISIONING: 'provisioning',
171
+ READY: 'ready',
172
+ RUNNING: 'running',
173
+ ARCHIVED: 'archived',
174
+ FAILED: 'failed',
175
+ }
176
+
177
+ /** Adapter command vocabulary (mother → fork control channel). */
178
+ export const ADAPTER_OP = {
179
+ PING: 'ping',
180
+ STATUS: 'status',
181
+ FLUSH_BUFFER: 'flush-buffer',
182
+ SCORE_PLUGIN: 'score-plugin',
183
+ READ_PLUGIN: 'read-plugin',
184
+ ROUTE_CONFIRM: 'route-confirm',
185
+ APPROVALS: 'approvals',
186
+ APPROVAL_DECIDE: 'approval-decide',
187
+ ARCHIVE: 'archive',
188
+ FORK_SESSION: 'fork-session',
189
+ DECISION_INGEST: 'decision-ingest',
190
+ }
191
+
192
+ /** Adapter HTTP route suffixes (fork side). */
193
+ export const ADAPTER_ROUTE = {
194
+ HELLO: '/adapter/hello',
195
+ IDENTITY: '/adapter/identity',
196
+ CLIENT_REPORT: '/adapter/client-report',
197
+ STATUS: '/adapter/status',
198
+ APPROVALS: '/adapter/approvals',
199
+ AUDIT: '/adapter/audit',
200
+ COMMAND: '/adapter/command',
201
+ // ── v3(docs/PROTOCOL-V3.md §4):与 v2 五条并存,向后兼容 ──
202
+ VERSION: '/adapter/version',
203
+ HEALTH: '/adapter/health',
204
+ STATE: '/adapter/state',
205
+ EVENTS: '/adapter/events',
206
+ COMMANDS: '/adapter/commands',
207
+ }
208
+
209
+ /**
210
+ * Adapter 协议版本(v2.6.1 起)。两侧编译期常量:母体用它做版本协商,分身
211
+ * 在 /adapter/version 与 /adapter/state 里回报。
212
+ */
213
+ export const ADAPTER_PROTOCOL_VERSION = 3
214
+ /** 母体可接受的最低协议版本(v1 = 无版本号的 v2.0 握手,按 legacy 处理)。 */
215
+ export const ADAPTER_PROTOCOL_MIN = 1
216
+
217
+ /** Adapter 事件种类(SSE 下行,docs/PROTOCOL-V3.md §6)。 */
218
+ export const ADAPTER_EVENT = {
219
+ STATE_CHANGED: 'state-changed',
220
+ PLUGIN_STATE: 'plugin-state',
221
+ APPROVAL_REQUESTED: 'approval-requested',
222
+ APPROVAL_RESOLVED: 'approval-resolved',
223
+ AUDIT: 'audit',
224
+ COMMAND: 'command',
225
+ COMMAND_PROGRESS: 'command-progress',
226
+ COMMAND_DONE: 'command-done',
227
+ ERROR: 'error',
228
+ }
229
+
230
+ /**
231
+ * Adapter 错误码 → HTTP 状态码(docs/PROTOCOL-V3.md §8)。
232
+ * 未登记的 code 一律 500:宁可让母体看到一个明确的失败,也不要假装成功。
233
+ */
234
+ export const ADAPTER_ERROR_STATUS = {
235
+ 'bad-request': 400,
236
+ 'invalid-json': 400,
237
+ 'invalid-payload': 400,
238
+ 'missing-op': 400,
239
+ 'unknown-op': 400,
240
+ 'path-escape': 400,
241
+ 'file-too-large': 400,
242
+ 'total-too-large': 400,
243
+ 'binary-file': 400,
244
+ 'body-too-large': 413,
245
+ 'cursor-invalid': 400,
246
+ 'command-id-invalid': 400,
247
+ unauthorized: 401,
248
+ 'not-found': 404,
249
+ 'plugin-not-found': 404,
250
+ 'session-changed': 409,
251
+ 'state-conflict': 409,
252
+ 'not-pending': 409,
253
+ 'service-unavailable': 409,
254
+ 'not-configured': 409,
255
+ conflict: 409,
256
+ timeout: 409,
257
+ 'cursor-expired': 410,
258
+ 'handler-threw': 500,
259
+ 'internal-error': 500,
260
+ 'not-ready': 503,
261
+ }
262
+
263
+ /** Container (AppContainer) executor states. */
264
+ export const CONTAINER = { DISABLED: 'disabled', UNAVAILABLE: 'unavailable', READY: 'ready' }