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

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,49 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.1.4] — 2026-11-18
6
+
7
+ ### Fixed
8
+
9
+ - **Run drill failed on a second drill**: like `demo`, the CLI replays an
10
+ existing ledger and then refuses to re-seed credentials that an earlier drill
11
+ already revoked, so pressing **Run drill** on a ledger that already contained
12
+ drill events failed with `seed allocate: … credential "cred:resource:drl-N" is
13
+ present in the global revocation set`. A fresh ledger passes (157 records), and
14
+ demo-then-drill passes (233 records); only a second drill failed.
15
+
16
+ ### Changed
17
+
18
+ - **Both actions now start from a clean baseline**: pressing **Run demo** or
19
+ **Run drill** clears the CLI's own `seg-*.log` files first (two-click
20
+ confirmation when the ledger is not empty), so every run is deterministic.
21
+ The action posts `reset-demo` / `reset-drill` to `POST /api/ai-prison/run`;
22
+ the separate rebuild button is gone.
23
+ - `ai_prison_drill` attaches a `hint` for replay/seed-allocation failures, and
24
+ the panel explains the clear-first behaviour under the buttons.
25
+
26
+ ## [1.1.3] — 2026-11-18
27
+
28
+ ### Added
29
+
30
+ - **Ledger rebuild action**: the panel now has **Rebuild ledger (clear and run
31
+ demo)** with a two-click confirmation, backed by `action: "reset-demo"` on
32
+ `POST /api/ai-prison/run`. It deletes only the CLI's own `seg-*.log` files in
33
+ the ledger directory and then runs the demo, so a used ledger can be rebuilt
34
+ without shell access. The stale `segments` count is shown too.
35
+ - `ai_prison_demo` now attaches a `hint` when the CLI refuses because the ledger
36
+ is not empty.
37
+
38
+ ### Fixed
39
+
40
+ - **Run demo on a non-empty ledger**: the CLI replays an existing ledger and then
41
+ refuses to re-seed credentials that are already in the revocation set, so
42
+ pressing **Run demo** after any records existed failed with
43
+ `seed allocate: … credential … is present in the global revocation set`.
44
+ The panel now disables that button when the ledger has segments, explains why,
45
+ and offers the rebuild action instead; the Host route also pre-checks and
46
+ answers `ledger-not-empty` with the same guidance.
47
+
5
48
  ## [1.1.2] — 2026-11-18
6
49
 
7
50
  ### 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
39
- /api/ai-prison/run` and therefore write the ledger only when pressed; the panel
40
- never writes on its own.
36
+ directory, integrity pill, record/segment/file counts; it refreshes every 20
37
+ seconds and on demand. Below the audit-chain card sit two explicit buttons —
38
+ **Run demo** and **Run drill** — which call `POST /api/ai-prison/run` and
39
+ therefore write the ledger only when pressed; the panel never writes on its own.
40
+ Both runs start from a clean baseline: when the ledger already has segments the
41
+ first click asks for confirmation, then the CLI's own `seg-*.log` files are
42
+ deleted and the action runs, because the CLI replays an existing ledger and
43
+ refuses to re-seed credentials that earlier runs already revoked (`demo` twice,
44
+ or a second `drill`, would otherwise fail).
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',
@@ -38,11 +39,13 @@ window.__ModuleLoader__.load({
38
39
  'cli.source': 'Source',
39
40
  'action.refresh': 'Refresh',
40
41
  'action.loading': 'Reading…',
41
- 'action.runDemo': 'Run demo (create ledger)',
42
- 'action.runDrill': 'Run recovery drill',
42
+ 'action.runDemo': 'Run demo',
43
+ 'action.runDrill': 'Run drill',
44
+ 'action.confirmRun': 'Click again: clear {records} records and run',
43
45
  'action.running': 'Running…',
44
46
  'ledger.actions': 'Explicit actions',
45
- 'ledger.actionsHint': 'These buttons run the bundled CLI and write the ledger; the panel never writes on its own.',
47
+ 'ledger.actionsHint': 'These buttons run the bundled CLI. An existing ledger is cleared first, so every run starts from a consistent baseline.',
48
+ 'ledger.resetHint': 'The ledger already exists: a run clears its segments first, then executes. Click twice to confirm.',
46
49
  'ledger.lastAction': 'Last action',
47
50
  'meta.updated': 'Updated {time}',
48
51
  'meta.readonly': 'Read-only view: the panel never writes by itself; only the buttons above do.',
@@ -62,6 +65,7 @@ window.__ModuleLoader__.load({
62
65
  'ledger.title': '审计链状态',
63
66
  'ledger.dir': '数据目录',
64
67
  'ledger.records': '记录数',
68
+ 'ledger.segments': '段数',
65
69
  'ledger.integrity': '完整性',
66
70
  'ledger.files': '文件数',
67
71
  'ledger.detail': '详情',
@@ -74,11 +78,13 @@ window.__ModuleLoader__.load({
74
78
  'cli.source': '来源',
75
79
  'action.refresh': '刷新',
76
80
  'action.loading': '读取中…',
77
- 'action.runDemo': '运行 demo(创建账本)',
78
- 'action.runDrill': '运行恢复演练',
81
+ 'action.runDemo': '运行 demo',
82
+ 'action.runDrill': '运行演练',
83
+ 'action.confirmRun': '再次点击:清空 {records} 条记录并运行',
79
84
  'action.running': '运行中…',
80
85
  'ledger.actions': '显式操作',
81
- 'ledger.actionsHint': '这些按钮会运行内置 CLI 并写入账本;面板本身不会自动写入。',
86
+ 'ledger.actionsHint': '这些按钮运行内置 CLI;账本已存在时会先清空,保证每次从一致基线开始。',
87
+ 'ledger.resetHint': '账本已存在:运行会先清空账本段再执行;再次点击确认。',
82
88
  'ledger.lastAction': '最近操作',
83
89
  'meta.updated': '更新于 {time}',
84
90
  'meta.readonly': '只读视图:面板不会自行写入账本,只有上方按钮会写入。',
@@ -263,7 +269,9 @@ window.__ModuleLoader__.load({
263
269
  }
264
270
 
265
271
  function LedgerCard({ ledger, cliFound, busy, onAction, lastResult }) {
272
+ const [pending, setPending] = React.useState(null)
266
273
  const exists = Boolean(ledger && ledger.exists)
274
+ const needsReset = exists && Number(ledger.segments ?? 0) > 0
267
275
  const integrityTone = !exists ? 'none' : ledger.integrity === 'ok' ? 'ok' : 'error'
268
276
  const integrityText = !exists ? t('integrity.none') : ledger.integrity === 'ok' ? t('integrity.ok') : t('integrity.failed')
269
277
  const entries = [
@@ -272,12 +280,29 @@ window.__ModuleLoader__.load({
272
280
  ]
273
281
  if (exists) {
274
282
  entries.push({ key: 'records', label: t('ledger.records'), value: h('span', { style: C.mono }, String(ledger.records ?? '—')) })
283
+ entries.push({ key: 'segments', label: t('ledger.segments'), value: h('span', { style: C.mono }, String(ledger.segments ?? '—')) })
275
284
  entries.push({ key: 'files', label: t('ledger.files'), value: h('span', { style: C.mono }, String(ledger.files ?? '—')) })
276
285
  }
277
286
  if (exists && ledger.detail) {
278
287
  entries.push({ key: 'detail', label: t('ledger.detail'), value: h('span', { style: { ...C.mono, wordBreak: 'break-word' } }, ledger.detail) })
279
288
  }
280
289
  const disabled = Boolean(busy) || !cliFound
290
+ /** A non-empty ledger is cleared first; that run needs a second click. */
291
+ const run = (action) => {
292
+ if (needsReset && pending !== action) {
293
+ setPending(action)
294
+ return
295
+ }
296
+ setPending(null)
297
+ onAction(needsReset ? `reset-${action}` : action)
298
+ }
299
+ const labelOf = (action, idle) => {
300
+ if (busy === action || busy === `reset-${action}`) return t('action.running')
301
+ if (needsReset && pending === action) return t('action.confirmRun', { records: ledger.records ?? '?' })
302
+ return t(idle)
303
+ }
304
+ const confirmStyle = (action) =>
305
+ needsReset && pending === action ? { ...C.actionBtn, color: '#b45309', borderColor: '#f59e0b' } : C.actionBtn
281
306
  return h(
282
307
  'section',
283
308
  { style: C.card },
@@ -294,18 +319,11 @@ window.__ModuleLoader__.load({
294
319
  h(
295
320
  'div',
296
321
  { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginTop: 10 } },
297
- h(
298
- 'button',
299
- { type: 'button', style: C.actionBtn, disabled, onClick: () => onAction('demo') },
300
- busy === 'demo' ? t('action.running') : t('action.runDemo'),
301
- ),
302
- h(
303
- 'button',
304
- { type: 'button', style: C.actionBtn, disabled, onClick: () => onAction('drill') },
305
- busy === 'drill' ? t('action.running') : t('action.runDrill'),
306
- ),
322
+ h('button', { type: 'button', style: confirmStyle('demo'), disabled, onClick: () => run('demo') }, labelOf('demo', 'action.runDemo')),
323
+ h('button', { type: 'button', style: confirmStyle('drill'), disabled, onClick: () => run('drill') }, labelOf('drill', 'action.runDrill')),
307
324
  h('span', { style: { ...C.muted, fontSize: 11.5 } }, t('ledger.actionsHint')),
308
325
  ),
326
+ needsReset ? h('p', { style: { ...C.muted, fontSize: 12, margin: '8px 0 0' } }, t('ledger.resetHint')) : null,
309
327
  lastResult
310
328
  ? h(
311
329
  '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', 'reset-drill'])
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' || action === 'reset-drill') {
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.startsWith('reset-') ? action.slice('reset-'.length) : 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
  })
@@ -183,6 +190,13 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
183
190
  output: stringOutput,
184
191
  async execute(args, exec) {
185
192
  const outcome = await invoke({ ctx, config, exec, subcommand: 'drill', dataDir: args?.data_dir })
193
+ if (!outcome.ok) {
194
+ const text = `${outcome.payload.stdout || ''}\n${outcome.payload.stderr || ''}`
195
+ if (/reopened ledger|seed allocate/i.test(text)) {
196
+ outcome.payload.hint =
197
+ '账本已被此前的演练写入:再次演练会重放旧事件并拒绝重新分配已吊销的凭据。请清空该数据目录下的 seg-*.log(或换一个空 data_dir)后重试;面板的「运行演练」会自动先清空。'
198
+ }
199
+ }
186
200
  return toolResult(outcome.payload)
187
201
  },
188
202
  })
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.4",
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",