@twinsearth/ai-prison-dsh-plugin 1.1.2 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,28 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.1.3] — 2026-11-18
6
+
7
+ ### Added
8
+
9
+ - **Ledger rebuild action**: the panel now has **Rebuild ledger (clear and run
10
+ demo)** with a two-click confirmation, backed by `action: "reset-demo"` on
11
+ `POST /api/ai-prison/run`. It deletes only the CLI's own `seg-*.log` files in
12
+ the ledger directory and then runs the demo, so a used ledger can be rebuilt
13
+ without shell access. The stale `segments` count is shown too.
14
+ - `ai_prison_demo` now attaches a `hint` when the CLI refuses because the ledger
15
+ is not empty.
16
+
17
+ ### Fixed
18
+
19
+ - **Run demo on a non-empty ledger**: the CLI replays an existing ledger and then
20
+ refuses to re-seed credentials that are already in the revocation set, so
21
+ pressing **Run demo** after any records existed failed with
22
+ `seed allocate: … credential … is present in the global revocation set`.
23
+ The panel now disables that button when the ledger has segments, explains why,
24
+ and offers the rebuild action instead; the Host route also pre-checks and
25
+ answers `ledger-not-empty` with the same guidance.
26
+
5
27
  ## [1.1.2] — 2026-11-18
6
28
 
7
29
  ### Fixed
package/README.md CHANGED
@@ -33,11 +33,15 @@ panel; the six tools become visible to the Agent on the next session step.
33
33
  | `ai_prison_repair_tail` | mutates | Remove only a genuine torn tail line; refuses hard tampering. Run `ai_prison_verify` first. |
34
34
 
35
35
  The panel shows the matrix from `ai_prison_levels` data plus the ledger
36
- directory, integrity pill, record and file counts; it refreshes every 20 seconds
37
- and on demand. Below the audit-chain card sit two explicit buttons — **Run demo
38
- (create ledger)** and **Run recovery drill** — which call `POST
36
+ directory, integrity pill, record/segment/file counts; it refreshes every 20
37
+ seconds and on demand. Below the audit-chain card sit three explicit buttons —
38
+ **Run demo (create ledger)**, **Run recovery drill**, and **Rebuild ledger
39
+ (clear and run demo)** (two-click confirmation) — which call `POST
39
40
  /api/ai-prison/run` and therefore write the ledger only when pressed; the panel
40
- never writes on its own.
41
+ never writes on its own. `demo` needs an empty ledger because the CLI replays an
42
+ existing one and refuses to re-seed revoked credentials, so the demo button is
43
+ disabled once segments exist and the rebuild action clears the CLI's own
44
+ `seg-*.log` files before running it.
41
45
 
42
46
  ## Ledger directory
43
47
 
package/client.js CHANGED
@@ -26,6 +26,7 @@ window.__ModuleLoader__.load({
26
26
  'ledger.title': 'Audit chain',
27
27
  'ledger.dir': 'Ledger directory',
28
28
  'ledger.records': 'Records',
29
+ 'ledger.segments': 'Segments',
29
30
  'ledger.integrity': 'Integrity',
30
31
  'ledger.files': 'Files',
31
32
  'ledger.detail': 'Detail',
@@ -40,9 +41,12 @@ window.__ModuleLoader__.load({
40
41
  'action.loading': 'Reading…',
41
42
  'action.runDemo': 'Run demo (create ledger)',
42
43
  'action.runDrill': 'Run recovery drill',
44
+ 'action.resetDemo': 'Rebuild ledger (clear and run demo)',
45
+ 'action.confirmReset': 'Click again to clear {records} records',
43
46
  'action.running': 'Running…',
44
47
  'ledger.actions': 'Explicit actions',
45
48
  'ledger.actionsHint': 'These buttons run the bundled CLI and write the ledger; the panel never writes on its own.',
49
+ 'ledger.demoNeedsEmpty': 'The ledger is not empty: the demo needs a fresh ledger. Rebuild it or run the recovery drill instead.',
46
50
  'ledger.lastAction': 'Last action',
47
51
  'meta.updated': 'Updated {time}',
48
52
  'meta.readonly': 'Read-only view: the panel never writes by itself; only the buttons above do.',
@@ -62,6 +66,7 @@ window.__ModuleLoader__.load({
62
66
  'ledger.title': '审计链状态',
63
67
  'ledger.dir': '数据目录',
64
68
  'ledger.records': '记录数',
69
+ 'ledger.segments': '段数',
65
70
  'ledger.integrity': '完整性',
66
71
  'ledger.files': '文件数',
67
72
  'ledger.detail': '详情',
@@ -76,9 +81,12 @@ window.__ModuleLoader__.load({
76
81
  'action.loading': '读取中…',
77
82
  'action.runDemo': '运行 demo(创建账本)',
78
83
  'action.runDrill': '运行恢复演练',
84
+ 'action.resetDemo': '重置账本并重建',
85
+ 'action.confirmReset': '再次点击确认清空 {records} 条记录',
79
86
  'action.running': '运行中…',
80
87
  'ledger.actions': '显式操作',
81
88
  'ledger.actionsHint': '这些按钮会运行内置 CLI 并写入账本;面板本身不会自动写入。',
89
+ 'ledger.demoNeedsEmpty': '账本非空:demo 需要空账本。请点「重置账本并重建」,或改用「运行恢复演练」。',
82
90
  'ledger.lastAction': '最近操作',
83
91
  'meta.updated': '更新于 {time}',
84
92
  'meta.readonly': '只读视图:面板不会自行写入账本,只有上方按钮会写入。',
@@ -263,7 +271,9 @@ window.__ModuleLoader__.load({
263
271
  }
264
272
 
265
273
  function LedgerCard({ ledger, cliFound, busy, onAction, lastResult }) {
274
+ const [confirmReset, setConfirmReset] = React.useState(false)
266
275
  const exists = Boolean(ledger && ledger.exists)
276
+ const canDemo = !exists || ledger.canDemo !== false
267
277
  const integrityTone = !exists ? 'none' : ledger.integrity === 'ok' ? 'ok' : 'error'
268
278
  const integrityText = !exists ? t('integrity.none') : ledger.integrity === 'ok' ? t('integrity.ok') : t('integrity.failed')
269
279
  const entries = [
@@ -272,12 +282,21 @@ window.__ModuleLoader__.load({
272
282
  ]
273
283
  if (exists) {
274
284
  entries.push({ key: 'records', label: t('ledger.records'), value: h('span', { style: C.mono }, String(ledger.records ?? '—')) })
285
+ entries.push({ key: 'segments', label: t('ledger.segments'), value: h('span', { style: C.mono }, String(ledger.segments ?? '—')) })
275
286
  entries.push({ key: 'files', label: t('ledger.files'), value: h('span', { style: C.mono }, String(ledger.files ?? '—')) })
276
287
  }
277
288
  if (exists && ledger.detail) {
278
289
  entries.push({ key: 'detail', label: t('ledger.detail'), value: h('span', { style: { ...C.mono, wordBreak: 'break-word' } }, ledger.detail) })
279
290
  }
280
291
  const disabled = Boolean(busy) || !cliFound
292
+ const rebuild = () => {
293
+ if (!confirmReset) {
294
+ setConfirmReset(true)
295
+ return
296
+ }
297
+ setConfirmReset(false)
298
+ onAction('reset-demo')
299
+ }
281
300
  return h(
282
301
  'section',
283
302
  { style: C.card },
@@ -296,7 +315,7 @@ window.__ModuleLoader__.load({
296
315
  { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginTop: 10 } },
297
316
  h(
298
317
  'button',
299
- { type: 'button', style: C.actionBtn, disabled, onClick: () => onAction('demo') },
318
+ { type: 'button', style: C.actionBtn, disabled: disabled || !canDemo, onClick: () => onAction('demo') },
300
319
  busy === 'demo' ? t('action.running') : t('action.runDemo'),
301
320
  ),
302
321
  h(
@@ -304,8 +323,25 @@ window.__ModuleLoader__.load({
304
323
  { type: 'button', style: C.actionBtn, disabled, onClick: () => onAction('drill') },
305
324
  busy === 'drill' ? t('action.running') : t('action.runDrill'),
306
325
  ),
326
+ exists
327
+ ? h(
328
+ 'button',
329
+ {
330
+ type: 'button',
331
+ style: confirmReset ? { ...C.actionBtn, color: '#b45309', borderColor: '#f59e0b' } : C.actionBtn,
332
+ disabled,
333
+ onClick: rebuild,
334
+ },
335
+ busy === 'reset-demo'
336
+ ? t('action.running')
337
+ : confirmReset
338
+ ? t('action.confirmReset', { records: ledger.records ?? '?' })
339
+ : t('action.resetDemo'),
340
+ )
341
+ : null,
307
342
  h('span', { style: { ...C.muted, fontSize: 11.5 } }, t('ledger.actionsHint')),
308
343
  ),
344
+ !canDemo ? h('p', { style: { ...C.muted, fontSize: 12, margin: '8px 0 0' } }, t('ledger.demoNeedsEmpty')) : null,
309
345
  lastResult
310
346
  ? h(
311
347
  'p',
package/lib/api.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { resolveCli, resolveDataDir, runCli } from './cli.js'
2
+ import { listSegments, resetLedger } from './ledger.js'
2
3
  import { buildStatus, summarizeRun } from './status.js'
3
4
 
4
5
  /**
@@ -30,14 +31,16 @@ export function resolveSessionCwd(ctx) {
30
31
  return undefined
31
32
  }
32
33
 
34
+ const ACTIONS = new Set(['demo', 'drill', 'reset', 'reset-demo'])
35
+
33
36
  function jsonResponse(payload, status = 200) {
34
37
  return Response.json(payload, { status, headers: { 'cache-control': 'no-store' } })
35
38
  }
36
39
 
37
40
  /**
38
- * Panel API: read-only status plus the two explicit ledger actions the panel
39
- * offers. Actions run the bundled CLI and therefore write the ledger only when
40
- * the user presses the corresponding button.
41
+ * Panel API: read-only status plus the explicit ledger actions the panel offers.
42
+ * `demo` needs an empty ledger (the CLI replays an existing one and refuses to
43
+ * re-seed revoked credentials), so the panel offers `reset-demo` to rebuild it.
41
44
  */
42
45
  export function registerApi({ ctx, config = {}, logger } = {}) {
43
46
  if (!ctx || typeof ctx.inject !== 'function') return false
@@ -60,8 +63,7 @@ export function registerApi({ ctx, config = {}, logger } = {}) {
60
63
  const url = new URL(request.url)
61
64
  const requested = url.searchParams.get('data_dir')
62
65
  const statusConfig = requested ? { ...config, dataDir: requested } : config
63
- const cwd = resolveSessionCwd(ctx)
64
- const status = await buildStatus({ config: statusConfig, cwd })
66
+ const status = await buildStatus({ config: statusConfig, cwd: resolveSessionCwd(ctx) })
65
67
  return jsonResponse(status)
66
68
  } catch (error) {
67
69
  return jsonResponse({ ok: false, error: String((error && error.message) || error) }, 500)
@@ -84,18 +86,50 @@ export function registerApi({ ctx, config = {}, logger } = {}) {
84
86
  body = {}
85
87
  }
86
88
  const action = String(body?.action ?? '')
87
- if (action !== 'demo' && action !== 'drill') {
88
- return jsonResponse({ ok: false, error: 'action must be "demo" or "drill"' }, 400)
89
+ if (!ACTIONS.has(action)) {
90
+ return jsonResponse({ ok: false, error: 'action must be one of demo, drill, reset, reset-demo' }, 400)
89
91
  }
90
92
  const resolved = resolveCli({ config })
91
- if (!resolved.path) {
92
- return jsonResponse({ ok: false, error: resolved.missing, reason: 'cli-missing' }, 409)
93
- }
94
93
  const cwd = resolveSessionCwd(ctx) || process.cwd()
95
94
  const requested = typeof body?.data_dir === 'string' && body.data_dir ? body.data_dir : undefined
96
95
  const dataDir = requested ? requested : resolveDataDir({ config, cwd })
96
+
97
+ let removed = []
98
+ if (action === 'reset' || action === 'reset-demo') {
99
+ const reset = resetLedger(dataDir)
100
+ if (!reset.ok) {
101
+ return jsonResponse({ ok: false, action, dataDir, error: reset.error || 'reset failed' }, 500)
102
+ }
103
+ removed = reset.removed
104
+ if (action === 'reset') {
105
+ return jsonResponse({
106
+ ok: true,
107
+ action,
108
+ dataDir,
109
+ removed,
110
+ summary: `已清空 ${removed.length} 个账本段`,
111
+ })
112
+ }
113
+ }
114
+
115
+ if (!resolved.path) {
116
+ return jsonResponse({ ok: false, error: resolved.missing, reason: 'cli-missing' }, 409)
117
+ }
97
118
  const timeoutMs = Number(config.timeoutMs) > 0 ? Number(config.timeoutMs) : 120_000
98
- const result = await runCli(['--data-dir', dataDir, action], {
119
+ const runAction = action === 'reset-demo' ? 'demo' : action
120
+ if (runAction === 'demo' && listSegments(dataDir).length > 0) {
121
+ return jsonResponse(
122
+ {
123
+ ok: false,
124
+ action,
125
+ dataDir,
126
+ error: 'ledger-not-empty',
127
+ hint: '账本已有记录:demo 需要空账本。请点「重置账本并重建」,或改用「运行恢复演练」。',
128
+ },
129
+ 409,
130
+ )
131
+ }
132
+ const result = await runCli(['--data-dir', dataDir, runAction], {
99
133
  bin: resolved.path,
100
134
  cwd,
101
135
  timeoutMs: Math.max(timeoutMs, 180_000),
@@ -105,9 +139,10 @@ export function registerApi({ ctx, config = {}, logger } = {}) {
105
139
  action,
106
140
  dataDir,
107
141
  cwd,
142
+ removed,
108
143
  exitCode: result.exitCode,
109
144
  timedOut: result.timedOut === true,
110
- summary: summarizeRun(action, result),
145
+ summary: summarizeRun(runAction, result),
111
146
  stdout: result.stdout,
112
147
  stderr: result.stderr,
113
148
  })
package/lib/ledger.js ADDED
@@ -0,0 +1,57 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ /** Ledger segment files written by the CLI: `seg-<10-digit start seq>.log`. */
5
+ export const SEGMENT_PATTERN = /^seg-\d+\.log$/
6
+
7
+ /** Segments currently present in a ledger directory (newest name last). */
8
+ export function listSegments(dataDir) {
9
+ if (!dataDir) return []
10
+ let entries
11
+ try {
12
+ entries = fs.readdirSync(dataDir, { withFileTypes: true })
13
+ } catch {
14
+ return []
15
+ }
16
+ return entries
17
+ .filter((entry) => entry.isFile() && SEGMENT_PATTERN.test(entry.name))
18
+ .map((entry) => {
19
+ let bytes = 0
20
+ try {
21
+ bytes = fs.statSync(path.join(dataDir, entry.name)).size
22
+ } catch {
23
+ bytes = 0
24
+ }
25
+ return { name: entry.name, bytes }
26
+ })
27
+ .sort((a, b) => a.name.localeCompare(b.name))
28
+ }
29
+
30
+ /**
31
+ * Delete only the CLI's own segment files from a ledger directory. Nothing else
32
+ * is touched: no recursion, no directories, no files that the CLI did not name.
33
+ */
34
+ export function resetLedger(dataDir) {
35
+ if (!dataDir) return { ok: false, removed: [], error: 'no ledger directory' }
36
+ const resolved = path.resolve(dataDir)
37
+ if (path.dirname(resolved) === resolved) {
38
+ return { ok: false, removed: [], error: 'refusing to clear a filesystem root' }
39
+ }
40
+ const segments = listSegments(resolved)
41
+ const removed = []
42
+ const failed = []
43
+ for (const segment of segments) {
44
+ try {
45
+ fs.rmSync(path.join(resolved, segment.name), { force: true })
46
+ removed.push(segment.name)
47
+ } catch (error) {
48
+ failed.push(`${segment.name}: ${String((error && error.message) || error)}`)
49
+ }
50
+ }
51
+ return {
52
+ ok: failed.length === 0,
53
+ removed,
54
+ failed,
55
+ error: failed.length > 0 ? failed.join('; ') : undefined,
56
+ }
57
+ }
package/lib/status.js CHANGED
@@ -1,6 +1,7 @@
1
- import { existsSync, readdirSync, statSync } from 'node:fs'
1
+ import { existsSync, readdirSync } from 'node:fs'
2
2
  import { describeCli, resolveCli, resolveDataDir, runCli } from './cli.js'
3
3
  import { parseLevels } from './levels.js'
4
+ import { listSegments } from './ledger.js'
4
5
 
5
6
  const MAX_DETAIL = 600
6
7
 
@@ -17,7 +18,7 @@ function firstLines(text, count = 3) {
17
18
  /** Read the durable ledger's integrity through `aiprison verify`. */
18
19
  export async function inspectLedger({ bin, dataDir, timeoutMs } = {}) {
19
20
  if (!dataDir || !existsSync(dataDir)) {
20
- return { dir: dataDir || null, exists: false, integrity: 'none', records: null, detail: '', files: 0 }
21
+ return { dir: dataDir || null, exists: false, integrity: 'none', records: null, detail: '', files: 0, segments: 0, canDemo: true }
21
22
  }
22
23
  let files = 0
23
24
  try {
@@ -25,6 +26,7 @@ export async function inspectLedger({ bin, dataDir, timeoutMs } = {}) {
25
26
  } catch {
26
27
  files = 0
27
28
  }
29
+ const segments = listSegments(dataDir).length
28
30
  const result = await runCli(['--data-dir', dataDir, 'verify'], { bin, timeoutMs })
29
31
  const text = result.ok ? result.stdout : `${result.stdout}\n${result.stderr}`
30
32
  if (result.ok) {
@@ -36,6 +38,8 @@ export async function inspectLedger({ bin, dataDir, timeoutMs } = {}) {
36
38
  records: records ? Number(records[1]) : null,
37
39
  detail: firstLines(text, 1),
38
40
  files,
41
+ segments,
42
+ canDemo: segments === 0,
39
43
  }
40
44
  }
41
45
  return {
@@ -45,6 +49,8 @@ export async function inspectLedger({ bin, dataDir, timeoutMs } = {}) {
45
49
  records: null,
46
50
  detail: firstLines(text, 3) || (result.timedOut ? 'verify timed out' : 'verify failed'),
47
51
  files,
52
+ segments,
53
+ canDemo: segments === 0,
48
54
  }
49
55
  }
50
56
 
package/lib/tools.js CHANGED
@@ -169,6 +169,13 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
169
169
  output: stringOutput,
170
170
  async execute(args, exec) {
171
171
  const outcome = await invoke({ ctx, config, exec, subcommand: 'demo', dataDir: args?.data_dir })
172
+ if (!outcome.ok) {
173
+ const text = `${outcome.payload.stdout || ''}\n${outcome.payload.stderr || ''}`
174
+ if (/reopened ledger/i.test(text)) {
175
+ outcome.payload.hint =
176
+ '账本非空:demo 只能从空账本开始(CLI 会重放旧账本并拒绝重新分配已吊销的凭据)。可改用 ai_prison_drill,或清空该数据目录下的 seg-*.log 后重试。'
177
+ }
178
+ }
172
179
  return toolResult(outcome.payload)
173
180
  },
174
181
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
4
4
  "description": "AI Prison for DSH: six governance tools wrapping the aiprison CLI (levels, demo, drill, inspect, verify, repair-tail) plus a panel for the L0–L5 matrix and the audit-chain state. The CLI ships bundled for Windows, macOS and Linux; every capability-removal backend stays simulated.",
5
5
  "type": "module",
6
6
  "main": "index.js",