dsh-swarm-console 0.2.1 → 0.3.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/README.md CHANGED
@@ -33,7 +33,7 @@ dsh-swarm-console
33
33
  plugin_manager install_bundle dsh-swarm-console
34
34
  ```
35
35
 
36
- > 已在 DSH 0.2.2-rc.5 上实测:profile 依赖解析为 `^0.1.5`,安装后 `verify_*` 工具与三条斜杠命令均可用。
36
+ > 已在 DSH 0.2.2-rc.5 上实测:profile 依赖解析为 `^0.2.2`,安装后 `verify_*` 工具与三条斜杠命令均可用。
37
37
 
38
38
  ### 从本地目录安装(已验证)
39
39
 
@@ -49,7 +49,7 @@ plugin_manager install_bundle <本包目录的绝对路径>
49
49
  ```text
50
50
  verify_contract 冻结一个契约(objective / constraints / criteria)
51
51
  verify_run 跑证据校验,得到 GREEN / YELLOW / RED
52
- /gate-status 查看某个契约最近一次判定
52
+ /gate-status 不带参数列出本会话所有契约;带参数看单条(支持 id 前缀,如 1578)
53
53
  /gate-approve 放行(仅 GREEN 允许,用户手动输入)
54
54
  /gate-retry 重算并刷新判定
55
55
  ```
package/docs/DETAIL.md CHANGED
@@ -36,19 +36,35 @@ capabilityRouting: true
36
36
 
37
37
  `stopReason='cancelled'` 表示调用被取消(`exec.signal` 触发),不抛异常。
38
38
 
39
- ## verify v1 三工具(实验性)
40
-
41
- - `verify_contract({objective, constraints, criteria})` → `{contractId}`,契约内容冻结成 12 位 id
42
- - `verify_run({contractId, checks})` → `{decision: 'GREEN'|'YELLOW'|'RED', reasons, evidenceHash, reproCmd?}`
43
- - `verify_status({contractId})` → 有记录时 `{known:true, decision, at}`;未知契约 `{known:false}`(不返回三态值)
39
+ ## verify 三工具(0.3.0 契约结构)
40
+
41
+ - `verify_contract({objective, workspaceRoot, testCmd?, policyId?, constraints, criteria})` → `{contractId}`
42
+ - **`workspaceRoot` 必填**:绝对路径、必须存在且是目录;所有检查以它为根
43
+ - `testCmd` 可选:`exec` 检查**唯一允许**的命令;不声明就拒绝一切 `exec`
44
+ - `policyId` 可选:只有显式声明,且策略的检查 id 全部被契约 `checkIds` 覆盖时才启用
45
+ - `verify_run({contractId, checks})` → `{decision, reasons, evidenceHash, reproCmd?, missing?, warnings?}`
46
+ - `file.exists` 的 `path` 必须是**相对 workspaceRoot 的相对路径**(绝对路径直接判 RED)
47
+ - `exec` 的 `cmd` 必须与 `testCmd` 完全相等;执行时 `cwd` 固定为 `workspaceRoot`
48
+ - 非法检查请求不抛异常,返回 `ok:false` 并判 RED
49
+ - `verify_status({contractId})` → `{known:true, decision, at, evidenceHash, approved?, stale?, ...}`;未知 `{known:false}`
44
50
 
45
51
  三态规则:缺证据 YELLOW;任一 check 失败 RED(必带可复制执行的 `reproCmd`);全部有证据且通过 GREEN。
46
52
 
47
- **放行入口(v1)**:斜杠命令 `/gate-approve <contractId>`、`/gate-retry <contractId>`、`/gate-status <contractId>`。放行只能由用户触发——斜杠命令由用户在交互界面直接输入,图中没有对应的模型工具,模型无法代替用户调用,H3(放行只能由用户触发)由这个结构保证,不依赖运行时身份判断。非 GREEN 时 `/gate-approve` 直接拒绝并提示先 retry。门禁卡(action-cards)为可选增强,仅在挂载该服务的 profile 生效。
53
+ **策略层(`code-change`)当前只生成 `testCmd` 检查**。`exists` / `workspace.diff` 已从策略声明中删除——需要文件检查时由调用方在 `checks` 里显式给出。
54
+
55
+ **放行入口**:斜杠命令 `/gate-approve <id|前缀> <evidenceHash>`、`/gate-retry <id|前缀>`、`/gate-status [id|前缀]`(不带参数列出**本会话**全部契约)。放行只能由用户触发——斜杠命令由用户在交互界面直接输入,图中没有对应的模型工具,模型无法代替用户调用,H3(放行只能由用户触发)由这个结构保证,不依赖运行时身份判断。非 GREEN 时 `/gate-approve` 直接拒绝并提示先 retry。门禁卡(action-cards)为可选增强,仅在挂载该服务的 profile 生效。
48
56
 
49
57
  每次命令执行会在会话日志留下 `command/run` 与 `command/done` 事件,可作为放行/重试的机器证据。
50
58
 
51
- **`gate-retry` 语义**:用空证据重算,结果必为 YELLOW(提示补证据);它只刷新决定时间戳,不伪造通过证据。要转 GREEN 需重新执行 `verify_run` 并提供真实证据。
59
+ **`gate-retry` 语义**:用空证据重算,结果必为 YELLOW(提示补证据);旧放行会被置 `approved=false`、`stale=true`,并保留 `lastApprovedAt` / `lastApprovedHash`,`/gate-status` 显示 `[stale] 上次放行已失效(时间)`。要转 GREEN 需重新执行 `verify_run` 并提供真实证据。
60
+
61
+ **会话隔离**:契约与运行状态都按 `${sessionId}:${contractId}` 存放;`/gate-status` 不带参数只列**本会话**契约,id 前缀解析也只在本会话内匹配(前缀最短 4 位)。
62
+
63
+ ## 命令速查
64
+
65
+ - `/gate-status`:不带参数列出本会话所有契约;带参数(或 id 前缀)查看单条
66
+ - `/gate-approve <id|前缀> <evidenceHash>`:**必须**带证据 hash 自证;缺参数会提示先 `/gate-status` 复制;非 GREEN 或 hash 不一致均拒绝
67
+ - `/gate-retry <id|前缀>`:重跑校验并把旧放行标为 `stale`
52
68
 
53
69
  ## 已知限制
54
70
 
@@ -57,6 +73,7 @@ capabilityRouting: true
57
73
  - 证据存**进程内 Map**,DSH 重启即丢,不做持久化(重启后 `/gate-status` 返回「未知契约」)
58
74
  - 还没有画布 —— 看不到 agent 节点、连线或过程可视化
59
75
  - 多阶段评审状态机未实现
76
+ - `swarm_run` 的 `RESULT:` 解析只取**第一行**(`RESULT: ok` 后面的说明不会进结果)
60
77
  - 动作卡片:代码保留为可选增强,需目标 profile 挂载 `action-cards` 服务;v1 的放行入口是斜杠命令
61
78
  - `swarm_run` 只支持一次调用,不支持多轮对话或子 agent 编排
62
79
 
package/index.js CHANGED
@@ -134,14 +134,15 @@ function registerGateCommands(ctx) {
134
134
  {
135
135
  name: 'gate-approve',
136
136
  description: '放行一个已 GREEN 的门禁契约(仅用户可触发)',
137
- input: { hint: '<contractId> [evidenceHash]' },
137
+ input: { hint: '<contractId> <evidenceHash>' },
138
138
  // 可传第二参数 evidenceHash 做过期校验;不传时以 runs 里的为最新
139
139
  handler: ({ agent, rawInput }) => {
140
140
  const parts = String(rawInput ?? '').trim().split(/\s+/)
141
+ // P0-6:第二个参数 evidenceHash 必填,不传时 gateApprove 会返回明确提示
141
142
  return gateApprove({
142
143
  contractId: parts[0] ?? '',
143
144
  sessionId: sessionOf({ agent }),
144
- ...(parts[1] ? { expectedHash: parts[1] } : {}),
145
+ expectedHash: parts[1],
145
146
  })
146
147
  },
147
148
  },
@@ -153,8 +154,8 @@ function registerGateCommands(ctx) {
153
154
  },
154
155
  {
155
156
  name: 'gate-status',
156
- description: '查看某契约的最近门禁决定与放行状态',
157
- input: { hint: '<contractId>' },
157
+ description: '查看门禁状态:不带参数列出本会话所有契约,带参数看单条(支持 id 前缀)',
158
+ input: { hint: '[<contractId|前缀>]' },
158
159
  handler: ({ agent, rawInput }) => gateStatus({ contractId: String(rawInput ?? '').trim(), sessionId: sessionOf({ agent }) }),
159
160
  },
160
161
  ]
@@ -218,6 +219,9 @@ function registerVerifyTools(ctx) {
218
219
  type: 'object',
219
220
  properties: {
220
221
  objective: { type: 'string' },
222
+ workspaceRoot: { type: 'string', description: '检查的根目录(绝对路径,必须存在)' },
223
+ testCmd: { type: 'string', description: 'exec 检查唯一允许的命令(白名单);不填则拒绝一切 exec' },
224
+ policyId: { type: 'string', description: '显式声明才启用策略(如 code-change)' },
221
225
  constraints: { type: 'array', items: { type: 'string' } },
222
226
  criteria: {
223
227
  type: 'array',
@@ -232,14 +236,14 @@ function registerVerifyTools(ctx) {
232
236
  },
233
237
  },
234
238
  },
235
- required: ['objective'],
239
+ required: ['objective', 'workspaceRoot'],
236
240
  additionalProperties: false,
237
241
  },
238
242
  output: {
239
243
  schema: { type: 'object', properties: { contractId: { type: 'string' } }, required: ['contractId'] },
240
244
  render: (args, v) => [{ type: 'text', text: `contract ${v.contractId} 已冻结` }],
241
245
  },
242
- execute: async (args) => verifyContract(args),
246
+ execute: async (args, exec) => verifyContract(args, sessionOf(exec)),
243
247
  },
244
248
  {
245
249
  name: 'verify_run',
@@ -304,12 +308,17 @@ function registerVerifyTools(ctx) {
304
308
  missing: { type: 'array', items: { type: 'string' } },
305
309
  approved: { type: 'boolean' },
306
310
  approvedAt: { type: 'string' },
311
+ evidenceHash: { type: 'string' },
312
+ stale: { type: 'boolean' },
313
+ lastApprovedAt: { type: 'string' },
307
314
  },
308
315
  required: ['known'],
309
316
  },
310
317
  render: (args, v) => {
311
318
  if (!v.known) return [{ type: 'text', text: '未知 contractId,尚无门禁记录' }]
312
319
  const lines = [`最近决定 ${v.decision}${v.at ? ' @ ' + v.at : ''}${v.approved ? `;已由用户放行 @ ${v.approvedAt}` : ';尚未放行'}`]
320
+ if (v.evidenceHash) lines.push(`证据:${v.evidenceHash}`)
321
+ if (v.stale) lines.push(`[stale] 上次放行已失效${v.lastApprovedAt ? `(${v.lastApprovedAt})` : ''}`)
313
322
  if (v.reproCmd) lines.push(`复现:${v.reproCmd}`)
314
323
  if (Array.isArray(v.missing) && v.missing.length > 0) lines.push(`缺失证据:${v.missing.join(';')}`)
315
324
  return [{ type: 'text', text: lines.join('\n') }]
package/lib/adapter.js CHANGED
@@ -253,7 +253,8 @@ export function parseTodos(output) {
253
253
  * @returns {string|undefined}
254
254
  */
255
255
  export function parseResult(output) {
256
- const m = output.match(/RESULT:\s*([\s\S]+)$/)
256
+ // P2-4:只取 RESULT: 之后的第一行,避免把后续说明整段吞进结果
257
+ const m = output.match(/RESULT:[ \t]*([^\n]*)/)
257
258
  return m ? m[1].trim() : undefined
258
259
  }
259
260
 
@@ -1,53 +1,78 @@
1
1
  /**
2
- * P0-2 · 检查请求执行器(0.2.0:checks 语义从「自报结论」改为「检查请求」)。
2
+ * P0-2 · 检查请求执行器(0.3.0:契约结构破坏性变更)。
3
3
  *
4
- * 模型传入的 ok 一律忽略 —— 由插件真实执行后判定,并记一条 warning。
5
- * 纯函数 + 可注入 existsSync / exec,单测不必真的碰文件或跑命令。
4
+ * 变化:
5
+ * - 一切路径以 contract.workspaceRoot 为根;file.exists 只接受相对路径
6
+ * - exec 的 cwd 固定为 workspaceRoot(结论不由宿主 cwd 决定)
7
+ * - exec 命令必须与 contract.testCmd 完全相等(白名单),否则该检查判 RED
8
+ * - 非法请求不再 throw:返回 {ok:false, detail:'检查请求非法:…'},由 gate 判 RED
9
+ *
10
+ * 模型传入的 ok 一律忽略,并记一条 warning。
6
11
  */
7
12
  import { existsSync as fsExistsSync } from 'node:fs'
8
13
  import { spawnSync as cpSpawnSync } from 'node:child_process'
14
+ import { isAbsolute, resolve } from 'node:path'
9
15
 
10
16
  /**
11
- * @param {Array} requests 检查请求:[{id, type:'file.exists'|'exec', path|cmd, ok?}]
12
- * @param {{existsSync?:Function, exec?:Function}} deps 可注入的执行实现
17
+ * @param {Array} requests 检查请求
18
+ * @param {{workspaceRoot:string, testCmd?:string, existsSync?:Function, exec?:Function}} deps
13
19
  * @returns {{checks:Array, warnings:string[]}}
14
20
  */
15
21
  export function runChecks(requests, deps = {}) {
16
- if (!Array.isArray(requests)) throw new Error('checks 必须是数组')
22
+ const workspaceRoot = deps.workspaceRoot
17
23
  const existsSync = deps.existsSync ?? fsExistsSync
18
- const exec = deps.exec ?? ((cmd) => cpSpawnSync(cmd, {
24
+ const exec = deps.exec ?? ((cmd, opts) => cpSpawnSync(cmd, {
19
25
  shell: true,
26
+ cwd: opts?.cwd,
20
27
  timeout: 120000,
21
28
  encoding: 'utf8',
22
29
  maxBuffer: 8 * 1024 * 1024,
23
30
  }))
24
31
 
25
32
  const warnings = []
33
+ // 顶层非法(不是数组)也不抛:整体记为一条失败检查,交 gate 判 RED
34
+ if (!Array.isArray(requests)) {
35
+ return {
36
+ checks: [{ id: '__checks__', type: 'invalid', ok: false, detail: '检查请求非法:checks 必须是数组' }],
37
+ warnings,
38
+ }
39
+ }
40
+
26
41
  const checks = requests.map((req, i) => {
27
- if (!req || typeof req !== 'object') throw new Error(`checks[${i}] 必须是对象`)
42
+ const fallbackId = req && typeof req === 'object' && typeof req.id === 'string' ? req.id : `checks[${i}]`
43
+ const invalid = (reason) => ({ id: fallbackId, type: String(req?.type ?? 'invalid'), ok: false, detail: `检查请求非法:${reason}` })
44
+
45
+ if (!req || typeof req !== 'object') return invalid('必须是对象')
28
46
  const { id, type } = req
29
- if (typeof id !== 'string' || id === '') throw new Error(`checks[${i}].id 必填`)
30
- if (typeof type !== 'string' || type === '') throw new Error(`checks[${i}].type 必填`)
47
+ if (typeof id !== 'string' || id === '') return invalid('id 必填')
48
+ if (typeof type !== 'string' || type === '') return invalid('type 必填')
31
49
 
32
- // 模型自报 ok 一律忽略,记 warning,不因此判 RED/GREEN
50
+ // 模型自报 ok 一律忽略,记 warning
33
51
  if (req.ok !== undefined) {
34
52
  warnings.push(`check ${id} 自报 ok=${req.ok} 已忽略,改由插件实际执行判定`)
35
53
  }
36
54
 
37
55
  if (type === 'file.exists') {
38
- if (typeof req.path !== 'string' || req.path === '') {
39
- throw new Error(`check ${id} file.exists 必带 path`)
56
+ if (typeof req.path !== 'string' || req.path === '') return invalid('file.exists 必带 path')
57
+ // P0-2:路径必须是相对 workspaceRoot 的相对路径,绝对路径直接判 RED
58
+ if (isAbsolute(req.path)) {
59
+ return { id, type, ok: false, path: req.path, detail: '检查路径必须是相对 workspaceRoot 的相对路径' }
60
+ }
61
+ if (typeof workspaceRoot !== 'string' || workspaceRoot === '') {
62
+ return invalid('缺少 workspaceRoot,无法解析相对路径')
40
63
  }
41
- const ok = existsSync(req.path) === true
42
- return { id, type, ok, path: req.path, detail: ok ? `文件存在:${req.path}` : `文件不存在:${req.path}` }
64
+ const absPath = resolve(workspaceRoot, req.path)
65
+ const ok = existsSync(absPath) === true
66
+ return { id, type, ok, path: req.path, absPath, detail: ok ? `文件存在:${req.path}` : `文件不存在:${req.path}` }
43
67
  }
44
68
 
45
69
  if (type === 'exec') {
46
- if (typeof req.cmd !== 'string' || req.cmd === '') {
47
- throw new Error(`check ${id} exec 必带 cmd`)
70
+ if (typeof req.cmd !== 'string' || req.cmd === '') return invalid('exec 必带 cmd')
71
+ // P0-4:命令白名单——必须与契约 testCmd 完全相等
72
+ if (typeof deps.testCmd !== 'string' || deps.testCmd === '' || req.cmd !== deps.testCmd) {
73
+ return { id, type, ok: false, cmd: req.cmd, detail: 'exec 命令未在契约中声明为 testCmd,已拒绝' }
48
74
  }
49
- const r = exec(req.cmd)
50
- // 关键:ok 只看真实退出码,不看模型自报,也不看 stdout 内容
75
+ const r = exec(req.cmd, { cwd: workspaceRoot })
51
76
  const ok = r.error === undefined && r.status === 0
52
77
  const out = { id, type, ok, cmd: req.cmd, exitCode: r.status }
53
78
  if (!ok) {
@@ -57,7 +82,7 @@ export function runChecks(requests, deps = {}) {
57
82
  return out
58
83
  }
59
84
 
60
- throw new Error(`check ${id} 未知检查类型 ${type}`)
85
+ return invalid(`未知检查类型 ${type}`)
61
86
  })
62
87
 
63
88
  return { checks, warnings }
@@ -1,28 +1,71 @@
1
1
  /**
2
- * D1 · 冻结任务契约。
3
- * id = 规范化内容哈希前 12 位 —— 同一份目标/约束/验收条件得到同一个 id,
4
- * 改一个字就换 id,防止"验收时换了题目"。
5
- * 零运行时依赖:用 node:crypto 的 sha256(Node 内置)。
2
+ * D1 · 冻结任务契约(0.3.0 起破坏性变更)。
3
+ *
4
+ * 新增 workspaceRoot(必填):检查以它为根执行,避免「在哪个 cwd 跑」决定结论。
5
+ * 新增 testCmd(可选):exec 检查唯一允许的命令(白名单);未声明则拒绝一切 exec。
6
+ * policyId 不再默认填充:只有显式声明才可能启用策略(P0-1 杜绝「命名即自证」)。
7
+ *
8
+ * id = 规范化内容哈希前 12 位;改 workspaceRoot / testCmd 同样换 id。
6
9
  */
7
10
  import { createHash } from 'node:crypto'
11
+ import { existsSync, statSync } from 'node:fs'
12
+ import { isAbsolute, resolve } from 'node:path'
8
13
 
9
14
  /**
10
- * @param {{objective:string, constraints?:string[], criteria?:Array<{id:string,text:string,checkIds?:string[]}>, policyId?:string}} input
11
- * @returns {{id:string, objective:string, constraints:string[], criteria:Array<{id:string,text:string,checkIds:string[]}>, policyId:string, frozenAt:string}}
15
+ * @param {{objective:string, constraints?:string[], criteria?:Array, workspaceRoot:string, testCmd?:string, policyId?:string, frozenAt?:string}} input
12
16
  */
13
17
  export function freezeContract(input) {
14
18
  if (!input || typeof input.objective !== 'string' || input.objective.trim() === '') {
15
19
  throw new Error('objective 必须是非空字符串')
16
20
  }
21
+
22
+ // P0-2/P0-5:workspaceRoot 必填,且必须是存在目录的绝对路径
23
+ if (typeof input.workspaceRoot !== 'string' || input.workspaceRoot.trim() === '') {
24
+ throw new Error('workspaceRoot 必填(绝对路径):检查以它为根执行')
25
+ }
26
+ if (!isAbsolute(input.workspaceRoot)) {
27
+ throw new Error(`workspaceRoot 必须是绝对路径,收到:${input.workspaceRoot}`)
28
+ }
29
+ const workspaceRoot = resolve(input.workspaceRoot)
30
+ if (!existsSync(workspaceRoot)) {
31
+ throw new Error(`workspaceRoot 不存在:${workspaceRoot}`)
32
+ }
33
+ let st
34
+ try { st = statSync(workspaceRoot) } catch { st = undefined }
35
+ if (!st || !st.isDirectory()) {
36
+ throw new Error(`workspaceRoot 不是目录:${workspaceRoot}`)
37
+ }
38
+
17
39
  const constraints = normalizeStringArray(input.constraints, 'constraints')
18
40
  const criteria = normalizeCriteria(input.criteria)
19
- const policyId = typeof input.policyId === 'string' && input.policyId !== '' ? input.policyId : 'code-change'
41
+
42
+ // P0-4:testCmd 可选;给了就必须是非空字符串
43
+ let testCmd
44
+ if (input.testCmd !== undefined && input.testCmd !== null) {
45
+ if (typeof input.testCmd !== 'string' || input.testCmd.trim() === '') {
46
+ throw new Error('testCmd 必须是非空字符串(exec 检查的唯一允许命令)')
47
+ }
48
+ testCmd = input.testCmd.trim()
49
+ }
50
+
51
+ // P0-1:policyId 仅显式声明才存在,不设默认值
52
+ let policyId
53
+ if (input.policyId !== undefined && input.policyId !== null) {
54
+ if (typeof input.policyId !== 'string' || input.policyId.trim() === '') {
55
+ throw new Error('policyId 必须是非空字符串')
56
+ }
57
+ policyId = input.policyId.trim()
58
+ }
59
+
20
60
  const frozenAt = typeof input.frozenAt === 'string' && input.frozenAt !== '' ? input.frozenAt : new Date().toISOString()
21
61
 
22
- // 规范化后再哈希:字段顺序固定、数组保序,避免对象键顺序影响 id
23
- const canonical = JSON.stringify({ objective: input.objective, constraints, criteria, policyId })
62
+ const canonical = JSON.stringify({ objective: input.objective, constraints, criteria, workspaceRoot, testCmd, policyId })
24
63
  const id = createHash('sha256').update(canonical).digest('hex').slice(0, 12)
25
- return { id, objective: input.objective, constraints, criteria, policyId, frozenAt }
64
+
65
+ const contract = { id, objective: input.objective, constraints, criteria, workspaceRoot, frozenAt }
66
+ if (testCmd !== undefined) contract.testCmd = testCmd
67
+ if (policyId !== undefined) contract.policyId = policyId
68
+ return contract
26
69
  }
27
70
 
28
71
  /** 校验已冻结契约的形状(供 gate / verify_run 入口复用)。 */
@@ -32,6 +75,12 @@ export function validateContract(contract) {
32
75
  if (typeof contract.id !== 'string' || !/^[0-9a-f]{12}$/.test(contract.id)) errs.push('id 必须是 12 位小写十六进制')
33
76
  if (typeof contract.objective !== 'string' || contract.objective.trim() === '') errs.push('objective 必填')
34
77
  if (!Array.isArray(contract.constraints)) errs.push('constraints 必须是数组')
78
+ if (typeof contract.workspaceRoot !== 'string' || !isAbsolute(contract.workspaceRoot)) {
79
+ errs.push('workspaceRoot 必须是绝对路径')
80
+ }
81
+ if (contract.testCmd !== undefined && (typeof contract.testCmd !== 'string' || contract.testCmd.trim() === '')) {
82
+ errs.push('testCmd 必须是非空字符串')
83
+ }
35
84
  if (!Array.isArray(contract.criteria)) errs.push('criteria 必须是数组')
36
85
  else for (const [i, c] of contract.criteria.entries()) {
37
86
  if (!c || typeof c.id !== 'string' || c.id === '') errs.push(`criteria[${i}].id 必填`)
@@ -92,7 +92,8 @@ function normalizeChecks(value) {
92
92
  }
93
93
  const out = { id: c.id, type: c.type, ok: c.ok }
94
94
  // path 必须保留:file.exists 失败时 gate 要用它生成 `test -f <path>` 复现命令
95
- for (const k of ['detail', 'exitCode', 'cmd', 'path']) if (c[k] !== undefined) out[k] = c[k]
95
+ // absPath 必须保留:file.exists 的复现命令要用绝对路径,否则换个 cwd 就指向别的文件
96
+ for (const k of ['detail', 'exitCode', 'cmd', 'path', 'absPath']) if (c[k] !== undefined) out[k] = c[k]
96
97
  return out
97
98
  })
98
99
  }
package/lib/core/gate.js CHANGED
@@ -1,77 +1,81 @@
1
- /**
2
- * D3 · 三态门禁纯函数。
3
- * decide(contract, evidence) → { decision, reasons, missing, reproCmd? }
4
- *
5
- * R1 任一 criterion 的 checkIds 为空,或没有对应 evidence.checks → 最高 YELLOW
6
- * R2 任一 check.ok === false → RED,reasons 必须包含 reproCmd(可复制执行)
7
- * R3 全部 criteria 有证据且通过 → GREEN
8
- *
9
- * 优先级:RED > YELLOW > GREEN。纯函数,零副作用、零依赖。
10
- */
11
-
12
- /**
13
- * @param {object} contract TaskContract
14
- * @param {object} evidence Evidence
15
- */
16
- export function decide(contract, evidence) {
17
- const reasons = []
18
- const missing = []
19
-
20
- if (!contract || !Array.isArray(contract.criteria) || contract.criteria.length === 0) {
21
- return { decision: 'RED', reasons: ['契约没有任何验收条件,不可判通过'], missing: [] }
22
- }
23
- const checks = Array.isArray(evidence?.checks) ? evidence.checks : []
24
- const byId = new Map(checks.map((c) => [c.id, c]))
25
-
26
- // R2 先行:任一 check 失败即 RED,并给出最小复现命令
27
- const failed = checks.filter((c) => c.ok === false)
28
- if (failed.length > 0) {
29
- const reproCmd = failed.map((c) => reproFor(c)).filter(Boolean).join(' && ')
30
- for (const c of failed) {
31
- reasons.push(`check "${c.id}" 失败:${c.detail || c.type}${c.cmd ? `(${c.cmd})` : ''}`)
32
- }
33
- if (!reproCmd) reasons.push('未提供可复现命令(reproCmd 为空)')
34
- return { decision: 'RED', reasons, missing, reproCmd: reproCmd || undefined }
35
- }
36
-
37
- // R1:逐条 criterion 查证据覆盖
38
- for (const criterion of contract.criteria) {
39
- const ids = Array.isArray(criterion.checkIds) ? criterion.checkIds : []
40
- if (ids.length === 0) {
41
- missing.push(`${criterion.id}: 未绑定 checkIds`)
42
- continue
43
- }
44
- const hit = ids.filter((id) => byId.has(id))
45
- if (hit.length === 0) {
46
- missing.push(`${criterion.id}: 没有对应 evidence.checks(需要 ${ids.join(', ')})`)
47
- } else if (hit.length < ids.length) {
48
- const absent = ids.filter((id) => !byId.has(id))
49
- missing.push(`${criterion.id}: 缺少检查 ${absent.join(', ')}`)
50
- }
51
- }
52
-
53
- if (missing.length > 0) {
54
- reasons.push(`${missing.length} 条验收条件缺少证据,不能判为通过`)
55
- return { decision: 'YELLOW', reasons, missing }
56
- }
57
-
58
- // R3:全部覆盖且全通过
59
- reasons.push(`全部 ${contract.criteria.length} 条验收条件均有通过证据`)
60
- return { decision: 'GREEN', reasons, missing }
61
- }
62
-
63
- /** 从失败 check 构造可复制执行的最小复现命令(按检查类型给对应命令)。 */
64
- function reproFor(check) {
65
- if (typeof check.cmd === 'string' && check.cmd.trim() !== '') return check.cmd
66
- // file.exists:文件缺失时 `test -f` 退出 1,正好复现这次失败
67
- if (check.type === 'file.exists' && typeof check.path === 'string' && check.path !== '') {
68
- return `test -f ${shellQuote(check.path)}`
69
- }
70
- // 其余情况兜底:给一条 sh -c 可直接执行且退出非 0 的真命令,不是装饰性注释
71
- return `echo "check ${check.id} 无可执行复现命令(该检查类型未提供路径/命令)" && exit 1`
72
- }
73
-
74
- /** POSIX 单引号包裹,内部单引号转义为 '\'' */
75
- function shellQuote(value) {
76
- return "'" + String(value).replace(/'/g, "'\\''") + "'"
77
- }
1
+ /**
2
+ * D3 · 三态门禁纯函数。
3
+ * decide(contract, evidence) → { decision, reasons, missing, reproCmd? }
4
+ *
5
+ * R1 任一 criterion 的 checkIds 为空,或没有对应 evidence.checks → 最高 YELLOW
6
+ * R2 任一 check.ok === false → RED,reasons 必须包含 reproCmd(可复制执行)
7
+ * R3 全部 criteria 有证据且通过 → GREEN
8
+ *
9
+ * 优先级:RED > YELLOW > GREEN。纯函数,零副作用、零依赖。
10
+ */
11
+
12
+ /**
13
+ * @param {object} contract TaskContract
14
+ * @param {object} evidence Evidence
15
+ */
16
+ export function decide(contract, evidence) {
17
+ const reasons = []
18
+ const missing = []
19
+
20
+ if (!contract || !Array.isArray(contract.criteria) || contract.criteria.length === 0) {
21
+ return { decision: 'RED', reasons: ['契约没有任何验收条件,不可判通过'], missing: [] }
22
+ }
23
+ const checks = Array.isArray(evidence?.checks) ? evidence.checks : []
24
+ const byId = new Map(checks.map((c) => [c.id, c]))
25
+
26
+ // R2 先行:任一 check 失败即 RED,并给出最小复现命令
27
+ const failed = checks.filter((c) => c.ok === false)
28
+ if (failed.length > 0) {
29
+ const reproCmd = failed.map((c) => reproFor(c)).filter(Boolean).join(' && ')
30
+ for (const c of failed) {
31
+ reasons.push(`check "${c.id}" 失败:${c.detail || c.type}${c.cmd ? `(${c.cmd})` : ''}`)
32
+ }
33
+ if (!reproCmd) reasons.push('未提供可复现命令(reproCmd 为空)')
34
+ return { decision: 'RED', reasons, missing, reproCmd: reproCmd || undefined }
35
+ }
36
+
37
+ // R1:逐条 criterion 查证据覆盖
38
+ for (const criterion of contract.criteria) {
39
+ const ids = Array.isArray(criterion.checkIds) ? criterion.checkIds : []
40
+ if (ids.length === 0) {
41
+ missing.push(`${criterion.id}: 未绑定 checkIds`)
42
+ continue
43
+ }
44
+ const hit = ids.filter((id) => byId.has(id))
45
+ if (hit.length === 0) {
46
+ missing.push(`${criterion.id}: 没有对应 evidence.checks(需要 ${ids.join(', ')})`)
47
+ } else if (hit.length < ids.length) {
48
+ const absent = ids.filter((id) => !byId.has(id))
49
+ missing.push(`${criterion.id}: 缺少检查 ${absent.join(', ')}`)
50
+ }
51
+ }
52
+
53
+ if (missing.length > 0) {
54
+ reasons.push(`${missing.length} 条验收条件缺少证据,不能判为通过`)
55
+ return { decision: 'YELLOW', reasons, missing }
56
+ }
57
+
58
+ // R3:全部覆盖且全通过
59
+ reasons.push(`全部 ${contract.criteria.length} 条验收条件均有通过证据`)
60
+ return { decision: 'GREEN', reasons, missing }
61
+ }
62
+
63
+ /** 从失败 check 构造可复制执行的最小复现命令(按检查类型给对应命令)。 */
64
+ function reproFor(check) {
65
+ if (typeof check.cmd === 'string' && check.cmd.trim() !== '') return check.cmd
66
+ // P1-3 · file.exists:用 node -e 判断,跨平台(不依赖 sh / test -f);
67
+ // 有 absPath 时写绝对路径,保证命令在任何 cwd 下都指向同一文件。
68
+ if (check.type === 'file.exists') {
69
+ const target = typeof check.absPath === 'string' && check.absPath !== '' ? check.absPath : check.path
70
+ if (typeof target === 'string' && target !== '') {
71
+ return `node -e "process.exit(require('node:fs').existsSync(process.argv[1])?0:1)" ${dq(target)}`
72
+ }
73
+ }
74
+ // 其余情况兜底:给一条可直接执行且退出非 0 的真命令,不是装饰性注释
75
+ return `echo "check ${check.id} 无可执行复现命令(该检查类型未提供路径/命令)" && exit 1`
76
+ }
77
+
78
+ /** 双引号包裹(cmd 与 sh 都可解析),内部双引号转义 */
79
+ function dq(value) {
80
+ return '"' + String(value).replace(/"/g, '\\"') + '"'
81
+ }
@@ -1,9 +1,9 @@
1
1
  /**
2
- * P0-3 · 策略加载与转换(0.2.0)。
3
- * loadPolicy(id) 读 plugin/policies/<id>.json;
4
- * policyToChecks(policy, contract) 把描述性 checks 转成可执行的检查请求。
5
- * 说明:策略里的 file.exists / workspace.diff 需要具体输入,不能由策略层伪造,
6
- * 因此 policy runner 只生成能确定的 exec 检查(tests),其余留给调用方显式提供。
2
+ * P0-3 · 策略加载与转换(0.3.0)。
3
+ *
4
+ * P0-1:策略层不再猜命令——删掉 'npm test' 兜底。
5
+ * P0-4:exec 只能来自 contract.testCmd;契约没声明就生成不出任何检查。
6
+ * P2-3:策略 JSON 只声明实际能生成的类型(exec)。
7
7
  */
8
8
  import { readFileSync } from 'node:fs'
9
9
  import { fileURLToPath } from 'node:url'
@@ -19,18 +19,21 @@ export function loadPolicy(id = 'code-change', baseDir = POLICIES_DIR) {
19
19
  return data
20
20
  }
21
21
 
22
- /** 把策略的 checks 描述转成可执行的检查请求(只生成能确定的 exec 检查)。 */
22
+ /**
23
+ * 把策略声明转成可执行的检查请求。
24
+ * 只有契约显式给了 testCmd 才生成 exec;绝不使用默认命令。
25
+ */
23
26
  export function policyToChecks(policy, contract = {}) {
24
27
  const out = []
28
+ const testCmd = typeof contract.testCmd === 'string' ? contract.testCmd.trim() : ''
29
+ if (testCmd === '') return out
25
30
  for (const c of policy.checks ?? []) {
26
- if (c.type === 'exec') {
27
- const testCmd = (Array.isArray(contract.constraints) ? contract.constraints : [])
28
- .map((s) => String(s))
29
- .find((s) => s.startsWith('testCmd:'))
30
- const cmd = testCmd ? testCmd.slice('testCmd:'.length).trim() : 'npm test'
31
- out.push({ id: c.id, type: 'exec', cmd })
32
- }
33
- // file.exists / workspace.diff 需要路径或宿主 workspaceChanges,不在此伪造
31
+ if (c.type === 'exec') out.push({ id: c.id, type: 'exec', cmd: testCmd })
34
32
  }
35
33
  return out
36
34
  }
35
+
36
+ /** 策略声明的检查 id 列表(供 P0-1 判断「策略是否被契约覆盖」)。 */
37
+ export function policyCheckIds(policy) {
38
+ return (policy.checks ?? []).map((c) => c.id).filter((id) => typeof id === 'string')
39
+ }
@@ -1,66 +1,108 @@
1
1
  /**
2
- * D5/D6 · verify v1 的宿主无关核心。
3
- * 三工具的纯逻辑 + 卡片 act 的调用者判定,便于不装 DSH 就能单测。
4
- * 状态用进程内 Map(v1,不做持久化;D8 明确不做多阶段状态机)。
2
+ * D5/D6 · verify 核心(0.3.0 破坏性变更)。
3
+ *
4
+ * 变更点:
5
+ * - 契约按会话隔离:键 `${sessionId}:${contractId}`(与 runs 一致)
6
+ * - policy 仅当契约显式声明 policyId 且策略检查被契约 checkIds 全覆盖时才启用(P0-1)
7
+ * - 检查以 contract.workspaceRoot 为根、exec 受 contract.testCmd 白名单约束(P0-2/P0-4)
8
+ * - approve 必须携带 evidenceHash 自证;retry 置 stale 并保留上次放行信息(P0-6/P1-1)
5
9
  */
6
10
  import { freezeContract } from './contract.js'
7
11
  import { makeEvidence, evidenceHash } from './evidence.js'
8
12
  import { decide } from './gate.js'
9
13
  import { runChecks } from './checks.js'
10
- import { loadPolicy, policyToChecks } from './policy.js'
14
+ import { loadPolicy, policyToChecks, policyCheckIds } from './policy.js'
11
15
 
12
16
  const contracts = new Map()
13
17
  const runs = new Map()
14
18
 
15
- /**
16
- * P0-4 · 运行状态键 = `${sessionId}:${contractId}`,隔离不同会话的同号契约。
17
- * sessionId 缺省 'default'(宿主拿不到时用)。
18
- */
19
+ /** 运行状态键:`${sessionId}:${contractId}` */
19
20
  export function runKey(contractId, sessionId = 'default') {
20
21
  return `${sessionId}:${contractId}`
21
22
  }
22
23
 
23
- /** verify_contract:冻结契约,返回 id。 */
24
- export function verifyContract(input, store = contracts) {
24
+ /** 契约键:与 runKey 同构,保证契约和状态在同一会话维度 */
25
+ export function contractKey(contractId, sessionId = 'default') {
26
+ return `${sessionId}:${contractId}`
27
+ }
28
+
29
+ function splitKey(key) {
30
+ const idx = key.indexOf(':')
31
+ return idx < 0 ? ['default', key] : [key.slice(0, idx), key.slice(idx + 1)]
32
+ }
33
+
34
+ /** verify_contract:冻结契约(按会话存),返回 id。 */
35
+ export function verifyContract(input, sessionId = 'default', store = contracts) {
25
36
  const c = freezeContract(input)
26
- store.set(c.id, { contract: c, frozenAt: c.frozenAt })
37
+ store.set(contractKey(c.id, sessionId), { contract: c, frozenAt: c.frozenAt })
27
38
  return { contractId: c.id }
28
39
  }
29
40
 
30
41
  /**
31
- * verify_run:跑策略 → 三态判定。
32
- * H1 证据先于验收:evidence 缺失时不判 GREEN(gate 的 R1 已保证)。
33
- * policy runner 由调用方注入(composePolicy),这里只做编排与落盘。
42
+ * P1-4 · 前缀解析:最短 4 位,范围限定本会话。
43
+ * @returns {{id?:string, error?:string}}
34
44
  */
35
- export function verifyRun({ contractId, sessionId, evidenceInput, runPolicy, checkDeps, usePolicy }, store = contracts, runStore = runs) {
45
+ export function resolveContractId(input, sessionId = 'default', store = contracts) {
46
+ const raw = String(input ?? '').trim()
47
+ if (raw === '') return { error: '缺少契约 id' }
48
+ if (raw.length < 4) return { error: '契约 id 前缀至少 4 位' }
49
+ const ids = [...store.keys()]
50
+ .filter((k) => splitKey(k)[0] === sessionId)
51
+ .map((k) => splitKey(k)[1])
52
+ if (ids.includes(raw)) return { id: raw }
53
+ const hits = ids.filter((id) => id.startsWith(raw))
54
+ if (hits.length === 1) return { id: hits[0] }
55
+ if (hits.length === 0) return { error: `未知契约 ${raw}` }
56
+ return { error: `前缀 ${raw} 命中多个契约:${hits.join(', ')}` }
57
+ }
58
+
59
+ /**
60
+ * verify_run:执行检查请求 → 三态判定。
61
+ * H1:没有检查请求时不判 GREEN(gate 的 R1 保证)。
62
+ */
63
+ export function verifyRun({ contractId, sessionId = 'default', evidenceInput, runPolicy, checkDeps, usePolicy }, store = contracts, runStore = runs) {
36
64
  const rk = runKey(contractId, sessionId)
37
- const entry = store.get(contractId)
65
+ const entry = store.get(contractKey(contractId, sessionId))
38
66
  if (!entry) return { decision: 'RED', reasons: [`未知 contractId ${contractId}`], evidenceHash: '' }
67
+ const contract = entry.contract
39
68
 
40
- // 0.2.0 P0-3:显式要求用策略且未给 checks 时,按 policy 生成检查请求
41
- if (usePolicy === true && !evidenceInput && typeof runPolicy !== 'function') {
42
- const policy = loadPolicy(entry.contract.policyId || 'code-change')
43
- evidenceInput = { checks: policyToChecks(policy, entry.contract) }
69
+ // P0-1:只有契约显式声明 policyId,且策略的每个检查 id 都被契约 checkIds 覆盖,才启用策略
70
+ let policyNote
71
+ if (usePolicy === true && !evidenceInput && typeof runPolicy !== 'function' && typeof contract.policyId === 'string') {
72
+ const policy = loadPolicy(contract.policyId)
73
+ const declared = policyCheckIds(policy)
74
+ const covered = new Set(contract.criteria.flatMap((c) => c.checkIds))
75
+ const uncovered = declared.filter((id) => !covered.has(id))
76
+ if (declared.length > 0 && uncovered.length === 0) {
77
+ evidenceInput = { checks: policyToChecks(policy, contract) }
78
+ } else if (declared.length > 0) {
79
+ policyNote = `策略未提供/未被契约覆盖的检查:${uncovered.join(', ')}`
80
+ }
44
81
  }
45
82
 
46
- // H1:既没有证据输入、也没有策略来产出证据 → 直接判 YELLOW,不伪造证据
83
+ // H1:没有检查请求 → 不伪造证据
47
84
  if (!evidenceInput && typeof runPolicy !== 'function') {
48
- const d = decide(entry.contract, { checks: [], artifacts: [] })
85
+ const d = decide(contract, { checks: [], artifacts: [] })
49
86
  const ev = makeEvidence({ contractId })
50
87
  const hash = evidenceHash(ev)
51
88
  runStore.set(rk, { decision: d.decision, at: new Date().toISOString(), evidenceHash: hash, missing: d.missing, reproCmd: d.reproCmd })
52
89
  return {
53
- decision: d.decision, reasons: d.reasons, evidenceHash: hash,
90
+ decision: d.decision,
91
+ reasons: policyNote ? [...d.reasons, policyNote] : d.reasons,
92
+ evidenceHash: hash,
54
93
  missing: d.missing,
55
94
  ...(d.reproCmd ? { reproCmd: d.reproCmd } : {}),
56
95
  }
57
96
  }
58
97
 
59
- // 0.2.0:checks 是请求,由插件真实执行(模型自报 ok 被忽略并记 warning)
60
98
  const evidence = typeof runPolicy === 'function'
61
- ? runPolicy(entry.contract, evidenceInput)
99
+ ? runPolicy(contract, evidenceInput)
62
100
  : (() => {
63
- const executed = runChecks(evidenceInput?.checks ?? [], checkDeps)
101
+ const executed = runChecks(evidenceInput?.checks ?? [], {
102
+ workspaceRoot: contract.workspaceRoot,
103
+ testCmd: contract.testCmd,
104
+ ...checkDeps,
105
+ })
64
106
  return makeEvidence({
65
107
  contractId,
66
108
  ...evidenceInput,
@@ -69,12 +111,12 @@ export function verifyRun({ contractId, sessionId, evidenceInput, runPolicy, che
69
111
  })
70
112
  })()
71
113
 
72
- const d = decide(entry.contract, evidence)
114
+ const d = decide(contract, evidence)
73
115
  const hash = evidenceHash(evidence)
74
116
  runStore.set(rk, { decision: d.decision, at: new Date().toISOString(), evidenceHash: hash, missing: d.missing, reproCmd: d.reproCmd })
75
117
  return {
76
118
  decision: d.decision,
77
- reasons: d.reasons,
119
+ reasons: policyNote ? [...d.reasons, policyNote] : d.reasons,
78
120
  evidenceHash: hash,
79
121
  missing: d.missing,
80
122
  ...(Array.isArray(evidence.warnings) && evidence.warnings.length > 0 ? { warnings: evidence.warnings } : {}),
@@ -82,26 +124,24 @@ export function verifyRun({ contractId, sessionId, evidenceInput, runPolicy, che
82
124
  }
83
125
  }
84
126
 
85
- /** verify_status:最近一次 decision 与时间。 */
86
- export function verifyStatus({ contractId, sessionId }, runStore = runs) {
127
+ /** verify_status:最近决定 + 证据 hash + 放行/失效状态(P0-6 要求输出证据行)。 */
128
+ export function verifyStatus({ contractId, sessionId = 'default' }, runStore = runs) {
87
129
  const r = runStore.get(runKey(contractId, sessionId))
88
- // 未知契约返回 known:false,不落进 GREEN/YELLOW/RED 三态(评审必改3)
89
130
  if (!r) return { known: false }
90
131
  return {
91
132
  known: true,
92
133
  decision: r.decision,
93
134
  at: r.at,
135
+ evidenceHash: r.evidenceHash,
94
136
  ...(r.reproCmd ? { reproCmd: r.reproCmd } : {}),
95
137
  ...(Array.isArray(r.missing) && r.missing.length > 0 ? { missing: r.missing } : {}),
96
138
  ...(r.approved === true ? { approved: true, approvedAt: r.approvedAt } : {}),
97
- ...(r.stale === true ? { stale: true } : {}),
139
+ ...(r.stale === true ? { stale: true, lastApprovedAt: r.lastApprovedAt, lastApprovedHash: r.lastApprovedHash } : {}),
98
140
  }
99
141
  }
100
142
 
101
143
  /**
102
- * H3 · act() 的调用者守卫。
103
- * 非用户(subagent / 代码发起 / 无 session)→ refused + 记拒绝事件。
104
- * @returns {{status:'refused',reason}|null} null 表示允许继续
144
+ * H3 · 卡片 act 的调用者守卫(卡片为可选增强;v1 默认入口是斜杠命令)。
105
145
  */
106
146
  export function guardCaller(agent, record) {
107
147
  const origin = agent?.session?.header?.origin
@@ -122,55 +162,99 @@ export function newStores() {
122
162
  return { contracts: new Map(), runs: new Map() }
123
163
  }
124
164
 
125
- // ── v1 放行入口:斜杠命令核心(宿主无关)─────────────────────────────
126
- // 命令只能由用户触发(斜杠命令不走模型工具),H3 由结构保证,不靠 act 守卫。
127
- // 状态与 verify 同源:契约在 contracts,最近决定在 runs,approved 也写回 runs。
165
+ // ── 放行入口:斜杠命令核心(用户触发;模型无对应工具)─────────────────
128
166
 
129
- /** /gate-approve:非 GREEN 拒绝;证据过期拒绝;GREEN 记 approved 返回成功。 */
130
- export function gateApprove({ contractId, sessionId, expectedHash }, store = contracts, runStore = runs) {
131
- if (!store.has(contractId)) return { kind: 'error', text: `未知契约 ${contractId}` }
132
- const rk = runKey(contractId, sessionId)
167
+ /** /gate-approve:必须带 evidenceHash 自证;非 GREEN 拒绝;hash 不一致拒绝。 */
168
+ export function gateApprove({ contractId, sessionId = 'default', expectedHash }, store = contracts, runStore = runs) {
169
+ const resolved = resolveContractId(contractId, sessionId, store)
170
+ if (resolved.error) return { kind: 'error', text: resolved.error }
171
+ const id = resolved.id
172
+ const rk = runKey(id, sessionId)
133
173
  const r = runStore.get(rk)
134
174
  if (!r) return { kind: 'error', text: '尚无门禁决定,请先执行 verify_run' }
175
+ if (typeof expectedHash !== 'string' || expectedHash.trim() === '') {
176
+ return { kind: 'error', text: `缺少 evidenceHash:请先用 /gate-status ${id} 查看并复制「证据:<hash>」,再执行 /gate-approve ${id} <hash>` }
177
+ }
135
178
  if (r.decision !== 'GREEN') {
136
- return { kind: 'error', text: `非 GREEN 不可放行,请先 /gate-retry ${contractId}` }
179
+ return { kind: 'error', text: `非 GREEN 不可放行,请先 /gate-retry ${id}` }
137
180
  }
138
- // P0-4:evidenceHash 与最近一次 verify_run 不一致 → 证据已过期
139
- if (expectedHash !== undefined && r.evidenceHash !== expectedHash) {
181
+ if (r.evidenceHash !== expectedHash.trim()) {
140
182
  return { kind: 'error', text: '证据已过期,请重新 verify_run' }
141
183
  }
142
- runStore.set(rk, { ...r, approved: true, approvedAt: new Date().toISOString(), by: 'user', stale: false })
143
- return { kind: 'success', text: `契约 ${contractId} 已由用户放行(approved)` }
184
+ runStore.set(rk, {
185
+ ...r,
186
+ approved: true,
187
+ approvedAt: new Date().toISOString(),
188
+ approvedHash: r.evidenceHash,
189
+ by: 'user',
190
+ stale: false,
191
+ })
192
+ return { kind: 'success', text: `契约 ${id} 已由用户放行(approved)` }
144
193
  }
145
194
 
146
- /** /gate-retry:空证据重算 → YELLOW;保留 approved 但置 stale、清 approvedAt。 */
147
- export function gateRetry({ contractId, sessionId }, store = contracts, runStore = runs) {
148
- if (!store.has(contractId)) return { kind: 'error', text: `未知契约 ${contractId}` }
149
- const rk = runKey(contractId, sessionId)
195
+ /** /gate-retry:重算 → YELLOW;approved=false、stale=true,保留上次放行信息。 */
196
+ export function gateRetry({ contractId, sessionId = 'default' }, store = contracts, runStore = runs) {
197
+ const resolved = resolveContractId(contractId, sessionId, store)
198
+ if (resolved.error) return { kind: 'error', text: resolved.error }
199
+ const id = resolved.id
200
+ const rk = runKey(id, sessionId)
150
201
  const before = runStore.get(rk)
151
202
  const wasApproved = before?.approved === true
152
- const r = verifyRun({ contractId, sessionId, evidenceInput: undefined }, store, runStore)
153
- // verifyRun 覆盖了整条记录,把旧的 approved/stale 语义补回来
154
- const after = runStore.get(rk)
155
- if (wasApproved) runStore.set(rk, { ...after, approved: true, stale: true, approvedAt: undefined, by: before.by })
156
- else runStore.set(rk, { ...after, stale: true })
157
- const now = verifyStatus({ contractId, sessionId }, runStore)
203
+ const lastApprovedAt = wasApproved ? before.approvedAt : before?.lastApprovedAt
204
+ const lastApprovedHash = wasApproved ? before.approvedHash : before?.lastApprovedHash
205
+
206
+ const r = verifyRun({ contractId: id, sessionId, evidenceInput: undefined }, store, runStore)
207
+
208
+ // verifyRun 覆盖整条记录,这里补回 stale 语义
209
+ const after = runStore.get(rk) ?? {}
210
+ runStore.set(rk, {
211
+ ...after,
212
+ approved: false,
213
+ stale: true,
214
+ ...(lastApprovedAt !== undefined ? { lastApprovedAt } : {}),
215
+ ...(lastApprovedHash !== undefined ? { lastApprovedHash } : {}),
216
+ })
217
+
218
+ const now = verifyStatus({ contractId: id, sessionId }, runStore)
219
+ const staleNote = lastApprovedAt ? ` [stale] 上次放行已失效(${lastApprovedAt})` : ' [stale]'
158
220
  return {
159
221
  kind: 'success',
160
- text: `契约 ${contractId} 已重算:${r.decision} @ ${now.at}${wasApproved ? ' [stale](原放行已失效)' : ''}。需重新执行 verify_run 补证据后才可能转 GREEN。`,
222
+ text: `契约 ${id} 已重算:${r.decision} @ ${now.at}${staleNote}。需重新执行 verify_run 补证据后才可能转 GREEN。`,
161
223
  }
162
224
  }
163
225
 
164
- /** /gate-status:最近决定 + 时间 + 是否 approved / stale;未知契约 error。 */
165
- export function gateStatus({ contractId, sessionId }, store = contracts, runStore = runs) {
166
- if (!store.has(contractId)) return { kind: 'error', text: `未知契约 ${contractId}` }
167
- const r = runStore.get(runKey(contractId, sessionId))
168
- if (!r) return { kind: 'success', text: `契约 ${contractId} 尚无门禁决定` }
226
+ /** /gate-status:无参列出本会话契约;有参(支持 ≥4 位前缀)看单条。 */
227
+ export function gateStatus({ contractId, sessionId = 'default' } = {}, store = contracts, runStore = runs) {
228
+ const raw = String(contractId ?? '').trim()
229
+
230
+ if (raw === '') {
231
+ const ids = [...store.keys()].filter((k) => splitKey(k)[0] === sessionId).map((k) => splitKey(k)[1])
232
+ if (ids.length === 0) return { kind: 'success', text: '当前会话还没有冻结任何契约(先执行 verify_contract)' }
233
+ const rows = ids.map((id) => ({ id, run: runStore.get(runKey(id, sessionId)) }))
234
+ rows.sort((a, b) => String(b.run?.at ?? '').localeCompare(String(a.run?.at ?? '')))
235
+ const lines = rows.map(({ id, run }) => {
236
+ if (!run) return `- ${id} 未跑校验`
237
+ const flags = [run.decision]
238
+ if (run.stale === true) flags.push('[stale]')
239
+ flags.push(run.approved === true ? '已放行' : '尚未放行')
240
+ return `- ${id} ${flags.join(' ')} @ ${run.at ?? '-'}`
241
+ })
242
+ return { kind: 'success', text: [`当前会话契约(${rows.length}):`, ...lines].join('\n') }
243
+ }
244
+
245
+ const resolved = resolveContractId(raw, sessionId, store)
246
+ if (resolved.error) return { kind: 'error', text: resolved.error }
247
+ const id = resolved.id
248
+ const r = runStore.get(runKey(id, sessionId))
249
+ if (!r) return { kind: 'success', text: `契约 ${id} 尚无门禁决定` }
250
+
169
251
  const approved = r.approved === true
170
252
  const stale = r.stale === true
171
- const head = `契约 ${contractId}:最近决定 ${r.decision} @ ${r.at}${stale ? ' [stale]' : ''}${approved ? `;已由 ${r.by ?? 'user'} 放行${stale ? '(已过期)' : ` @ ${r.approvedAt}`}` : ';尚未放行'}`
172
- // H2 可见性:RED 必须把复现命令亮给用户,YELLOW 必须把缺失证据亮出来
173
- const extra = []
253
+ const head = `契约 ${id}:最近决定 ${r.decision} @ ${r.at}` +
254
+ (stale ? ` [stale] 上次放行已失效${r.lastApprovedAt ? `(${r.lastApprovedAt})` : ''}` : '') +
255
+ (approved ? `;已由 ${r.by ?? 'user'} 放行 @ ${r.approvedAt}` : (stale ? '' : ';尚未放行'))
256
+
257
+ const extra = [`证据:${r.evidenceHash ?? '-'}`]
174
258
  if (r.reproCmd) extra.push(`复现:${r.reproCmd}`)
175
259
  if (Array.isArray(r.missing) && r.missing.length > 0) extra.push(`缺失证据:${r.missing.join(';')}`)
176
260
  return { kind: 'success', text: [head, ...extra].join('\n') }
package/package.json CHANGED
@@ -1,47 +1,47 @@
1
- {
2
- "name": "dsh-swarm-console",
3
- "version": "0.2.1",
4
- "type": "module",
5
- "description": "Run one external agent from DSH, with a visible gate (v0.1 · 门禁可用,画布开发中).",
6
- "keywords": [
7
- "deepseek-harness",
8
- "dsh-plugin",
9
- "agent",
10
- "swarm",
11
- "verification",
12
- "gate"
13
- ],
14
- "repository": {
15
- "type": "git",
16
- "url": "git+https://github.com/whyissodifficult/dsh-agent-swarm-console.git",
17
- "directory": "plugin"
18
- },
19
- "license": "MIT",
20
- "author": "郑志阳 (Walk in the white)",
21
- "homepage": "https://github.com/whyissodifficult/dsh-agent-swarm-console",
22
- "bugs": {
23
- "url": "https://github.com/whyissodifficult/dsh-agent-swarm-console/issues"
24
- },
25
- "engines": {
26
- "node": ">=20.3"
27
- },
28
- "exports": {
29
- ".": "./index.js",
30
- "./locale/*.json": "./locale/*.json",
31
- "./icon": "./icon.svg"
32
- },
33
- "files": [
34
- "index.js",
35
- "lib",
36
- "policies",
37
- "cordis.patch.yml",
38
- "locale",
39
- "docs",
40
- "icon.svg"
41
- ],
42
- "dsh": {
43
- "bundle": {
44
- "patch": "./cordis.patch.yml"
45
- }
46
- }
47
- }
1
+ {
2
+ "name": "dsh-swarm-console",
3
+ "version": "0.3.0",
4
+ "type": "module",
5
+ "description": "Run one external agent from DSH, with a visible gate (v0.1 · 门禁可用,画布开发中).",
6
+ "keywords": [
7
+ "deepseek-harness",
8
+ "dsh-plugin",
9
+ "agent",
10
+ "swarm",
11
+ "verification",
12
+ "gate"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/whyissodifficult/dsh-agent-swarm-console.git",
17
+ "directory": "plugin"
18
+ },
19
+ "license": "MIT",
20
+ "author": "郑志阳 (Walk in the white)",
21
+ "homepage": "https://github.com/whyissodifficult/dsh-agent-swarm-console",
22
+ "bugs": {
23
+ "url": "https://github.com/whyissodifficult/dsh-agent-swarm-console/issues"
24
+ },
25
+ "engines": {
26
+ "node": ">=20.3"
27
+ },
28
+ "exports": {
29
+ ".": "./index.js",
30
+ "./locale/*.json": "./locale/*.json",
31
+ "./icon": "./icon.svg"
32
+ },
33
+ "files": [
34
+ "index.js",
35
+ "lib",
36
+ "policies",
37
+ "cordis.patch.yml",
38
+ "locale",
39
+ "docs",
40
+ "icon.svg"
41
+ ],
42
+ "dsh": {
43
+ "bundle": {
44
+ "patch": "./cordis.patch.yml"
45
+ }
46
+ }
47
+ }
@@ -2,23 +2,11 @@
2
2
  "id": "code-change",
3
3
  "label": "代码改动策略",
4
4
  "checks": [
5
- {
6
- "id": "exists",
7
- "type": "file.exists",
8
- "description": "验收条件指定的文件存在",
9
- "input": "criteria[].checkIds -> artifacts[].path"
10
- },
11
- {
12
- "id": "diff",
13
- "type": "workspace.diff",
14
- "description": "取宿主 workspaceChanges.summary|diff,不自建 diff",
15
- "input": "workspaceChanges.summary || workspaceChanges.diff"
16
- },
17
5
  {
18
6
  "id": "tests",
19
7
  "type": "exec",
20
- "description": "执行测试命令,退出码必须为 0",
21
- "input": "constraints[].testCmd || 'npm test'",
8
+ "description": "执行契约声明的 testCmd,退出码必须为 0",
9
+ "input": "contract.testCmd(无声明则不生成任何检查)",
22
10
  "successExitCode": 0
23
11
  }
24
12
  ]