@restregular/dsh-memory 0.36.1 → 0.38.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/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  本项目的版本记录。安装 id 与 npm 版本一一对应。
4
4
 
5
+ ## 0.38.0 — 规则代码卡片重做:批准即开关、折叠、筛选、真实试跑输出
6
+
7
+ - **批准成为唯一开关,移除启用/停用**:provider 新增 `revokeHookApproval()`(清 `approvedHash`,代码保留、变回待批准),面板 API 加 `action:'revoke-approval'`,`memory_hooks` 加同名 action(`enable`/`disable` 降级为旧别名)。`HookStore.forRun` 不再看 `enabled`;老数据里 `enabled:false` 一次性迁成"未批准"(清指纹),不会突然开始运行。未批准不运行、批准后运行。
8
+ - **试跑结果按运行时机分开展示**:保存前校验显示"允许保存 / 拒绝保存"、保存后观察显示"观察 / 附注"、注入前解析显示"改写后正文 / 整条丢弃";并新增 `HookOutcome.raw` 回显脚本**真实返回值**(连同 `log()` 输出),不再只给规范化结论。
9
+ - **面板规则代码卡片**:批准 / 撤销批准按钮替代启用停用;卡片**默认折叠**(点标题或箭头展开);顶部按**时机 / 生效作用域 / 是否批准**筛选;试跑输出可点「×」手动关闭。试验新输出再次点试跑会重新打开。
10
+ - 回归守卫:`hooks.test.ts` 加撤销批准与 raw 两例,`hooks-tool.test.ts` 加 revoke 用例,`tools.test.ts` 加分时机渲染用例,`bundled-skills.test.ts` 静态守卫面板卡片四项交互。全套 62 个测试文件 0 失败,`client.js` 通过 node --check。
11
+
12
+ ## 0.37.0 — 钩子可读设置数据 + memory_list 完整时间戳 + 去掉冗余 key
13
+
14
+ - **钩子沙箱可读设置(ctx.settings)**:`HookRunInput` 新增可选 `settings`(只读快照:`digestChars` / `impressionChars` / `recallChars`),经 `runHookCode` 序列化进沙箱 `ctx.settings`;`parseForInject` 从实时 `injectSettings()` 取值(摘要 160 字、印象字数面板可改、召回 300 字)传入,`memory_hooks run` 试跑也带默认快照。before-inject 规则代码从此能按"当前摘要字数限制"截断,不写死数字。
15
+ - **新增规则代码**:挂了一条 `before-inject` 钩子「注入摘要只取概括句」——注入摘要时只保留记忆里第一个全角冒号「:」前的内容,没有冒号就用全文,超长按 `ctx.settings` 里的摘要字数上限截断。已试跑验证。
16
+ - **memory_list fields=full_time**:`fields` 参数新增 `full_time`,传了就给每条记录 `fullTime:{createdAt,updatedAt,expiresAt?}`(ISO 8601 精确到秒,无毫秒),渲染文案同步显示「创建/更新/过期」。不传则不带时间字段,保持旧行为。
17
+ - **去掉 save 提示里冗余的作用域 key**:`memory_save` 结果文案此前既在头部 `@ <scope>`、又追加一行「保存到的目标作用域 key:」说同一件事;现在只在头部 `@ <原始 key>` 出现一次,开头格式不变(`memorySaveResultIds` 按 UUID 抽取不受影响)。
18
+ - 回归守卫:`hooks.test.ts` 加 ctx.settings 透传与跟随实时设置两例,`tools.test.ts` 加 full_time 数据与渲染一例,`apply-registration.test.ts` 守卫 key 不再重复。全套 62 个测试文件 0 失败。
19
+
5
20
  ## 0.36.1 — 删除钩子加二次确认
6
21
 
7
22
  - **问题**:用户误点面板「删除」把「记忆内容规范(概括句:正文)」校验钩子删掉了——`memory_hooks delete` 与面板删除都是硬删除(`hooks.json` 直接 filter 后原子覆盖,没有回收站、没有 .bak),一次点击/一次调用代码就没了,且没有任何确认。
package/lib/client.js CHANGED
@@ -730,7 +730,13 @@ window.__ModuleLoader__.load({
730
730
  '.memp .hooks-settings{display:flex;align-items:center;gap:14px;flex-wrap:wrap;padding:9px 11px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);font-size:12px}',
731
731
  '.memp .hook-list{display:flex;flex-direction:column;gap:10px}',
732
732
  '.memp .hook-card{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;background:var(--dsw-alias-bg-layer-1);overflow:hidden}',
733
- '.memp .hook-card.off{opacity:.62}',
733
+ '.memp .hook-card.folded .hook-card-head{border-bottom:none}',
734
+ '.memp .hook-caret{cursor:pointer;user-select:none;color:var(--dsw-alias-label-secondary);font-size:12px;width:14px;flex:none}',
735
+ '.memp .hook-pill.ok{color:var(--dsw-alias-state-success-primary,#2a8);border-color:color-mix(in srgb,var(--dsw-alias-state-success-primary,#2a8) 45%,transparent);background:color-mix(in srgb,var(--dsw-alias-state-success-primary,#2a8) 8%,transparent)}',
736
+ '.memp .hook-filters{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:8px 11px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;font-size:12px}',
737
+ '.memp .hook-filters label{display:flex;align-items:center;gap:5px;color:var(--dsw-alias-label-secondary)}',
738
+ '.memp .hook-trial-raw{margin:5px 0 0;padding:6px 8px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-family:var(--ds-font-family-code,ui-monospace,monospace);font-size:11px;white-space:pre-wrap;word-break:break-all}',
739
+ '.memp .hook-trial-close{margin-left:auto}',
734
740
  '.memp .hook-card-head{display:flex;align-items:center;gap:10px;padding:10px 12px;border-bottom:1px solid var(--dsw-alias-border-l1);flex-wrap:wrap}',
735
741
  '.memp .hook-card-title{display:flex;align-items:center;gap:7px;flex:1;min-width:0;flex-wrap:wrap}',
736
742
  '.memp .hook-name{font-size:12.5px;font-weight:600}',
@@ -2874,6 +2880,13 @@ window.__ModuleLoader__.load({
2874
2880
  const [busy, setBusy] = React.useState(false)
2875
2881
  const [trial, setTrial] = React.useState(null)
2876
2882
  const [trialText, setTrialText] = React.useState('记忆内容规范:这段是合规样例')
2883
+ // 0.38.0:卡片默认折叠;筛选维度 = 时机 / 生效作用域 / 是否批准。
2884
+ const [expanded, setExpanded] = React.useState(new Set())
2885
+ const [filterPhase, setFilterPhase] = React.useState('')
2886
+ const [filterScope, setFilterScope] = React.useState('')
2887
+ const [filterApproval, setFilterApproval] = React.useState('')
2888
+ // 试跑输出可手动关闭:记录哪些卡片的试跑结果被用户关掉。
2889
+ const [trialClosed, setTrialClosed] = React.useState(new Set())
2877
2890
 
2878
2891
  const load = async () => {
2879
2892
  setError('')
@@ -2969,7 +2982,7 @@ window.__ModuleLoader__.load({
2969
2982
  const remove = async (hook) => {
2970
2983
  // 0.36.1:删除钩子不可逆(hooks.json 直接覆盖、无回收站),面板也加一道二次确认,
2971
2984
  // 与工具层的 confirm 参数对齐 —— 用户误点不再瞬间丢掉写好的规则代码。
2972
- if (!window.confirm(`确定删除钩子「${hook.name || hook.id}」吗?\n\n这一步不可逆:规则代码会从 hooks.json 直接移除,没有回收站。若只是想让它停下,请改用「停用」。`)) return
2985
+ if (!window.confirm(`确定删除钩子「${hook.name || hook.id}」吗?\n\n这一步不可逆:规则代码会从 hooks.json 直接移除,没有回收站。若只是想让它停下,请点「撤销批准」(代码保留、不再运行)。`)) return
2973
2986
  setBusy(true)
2974
2987
  setError('')
2975
2988
  try {
@@ -2983,21 +2996,25 @@ window.__ModuleLoader__.load({
2983
2996
  setBusy(false)
2984
2997
  }
2985
2998
 
2986
- const toggle = async (hook) => {
2999
+ // 0.38.0:启用/停用语义移除 —— 批准 = 代码会运行;撤销批准 = 代码保留但不再运行。
3000
+ const approve = async (hook) => {
2987
3001
  setBusy(true)
2988
3002
  try {
2989
- await api('hooks', {
2990
- action: 'save',
2991
- id: hook.id,
2992
- name: hook.name,
2993
- phase: hook.phase,
2994
- code: hook.code,
2995
- scopes: hook.scopes,
2996
- kinds: hook.kinds,
2997
- enabled: !(hook.enabled !== false),
2998
- by: 'user',
2999
- })
3003
+ await api('hooks', { action: 'approve', id: hook.id })
3000
3004
  await load()
3005
+ flash('已批准,这段代码从现在起会运行')
3006
+ } catch (e) {
3007
+ setError(String(e.message || e))
3008
+ }
3009
+ setBusy(false)
3010
+ }
3011
+
3012
+ const revokeApproval = async (hook) => {
3013
+ setBusy(true)
3014
+ try {
3015
+ await api('hooks', { action: 'revoke-approval', id: hook.id })
3016
+ await load()
3017
+ flash('已撤销批准,代码保留但不会运行')
3001
3018
  } catch (e) {
3002
3019
  setError(String(e.message || e))
3003
3020
  }
@@ -3008,6 +3025,7 @@ window.__ModuleLoader__.load({
3008
3025
  const run = async (hook) => {
3009
3026
  setBusy(true)
3010
3027
  setTrial(null)
3028
+ setTrialClosed((prev) => { const next = new Set(prev); next.delete(hook.id); return next })
3011
3029
  try {
3012
3030
  const value = await api('hooks', { action: 'run', id: hook.id, content: trialText })
3013
3031
  const outcome = Array.isArray(value.outcomes) ? value.outcomes[0] : undefined
@@ -3035,6 +3053,18 @@ window.__ModuleLoader__.load({
3035
3053
  const settings = data.settings || {}
3036
3054
  const pendingCount = hooks.filter((hook) => hook.pendingApproval).length
3037
3055
 
3056
+ // 0.38.0:筛选维度取值(从数据里收集,保证下拉里不会出现空选项)。
3057
+ const allScopes = [...new Set(hooks.flatMap((hook) => (Array.isArray(hook.scopes) ? hook.scopes : [])))]
3058
+ const shownHooks = hooks.filter((hook) => {
3059
+ if (filterPhase && hook.phase !== filterPhase) return false
3060
+ if (filterScope && !(Array.isArray(hook.scopes) && hook.scopes.includes(filterScope))) return false
3061
+ if (filterApproval === 'approved' && hook.pendingApproval) return false
3062
+ if (filterApproval === 'pending' && !hook.pendingApproval) return false
3063
+ return true
3064
+ })
3065
+
3066
+ const phaseTrialLabel = (phase) => phase === 'before-save' ? '保存前校验' : phase === 'after-save' ? '保存后观察' : phase === 'before-inject' ? '注入前解析' : '脚本'
3067
+
3038
3068
  const renderEditor = () => h('div', { className: 'hook-edit' },
3039
3069
  h('div', { className: 'hook-edit-head' },
3040
3070
  h('span', { className: 'hook-edit-title' }, draft.id === '' ? '新建规则代码' : `编辑 ${draft.name || draft.id}`),
@@ -3089,52 +3119,84 @@ window.__ModuleLoader__.load({
3089
3119
  )
3090
3120
 
3091
3121
  const renderCard = (hook) => {
3092
- const isOpen = draft !== null && draft.id === hook.id
3122
+ const editing = draft !== null && draft.id === hook.id
3123
+ const folded = !editing && !expanded.has(hook.id)
3124
+ const toggleFold = () => setExpanded((prev) => {
3125
+ const next = new Set(prev)
3126
+ if (next.has(hook.id)) next.delete(hook.id); else next.add(hook.id)
3127
+ return next
3128
+ })
3093
3129
  const trialOutcome = trial !== null && trial.hookId === hook.id ? trial.outcome : undefined
3094
- return h('div', { className: 'hook-card' + (hook.enabled === false ? ' off' : ''), key: hook.id },
3130
+ const showTrial = trialOutcome !== undefined && trialOutcome !== null && !trialClosed.has(hook.id)
3131
+ const approved = !hook.pendingApproval
3132
+ let rawText = ''
3133
+ if (trialOutcome && trialOutcome.raw !== undefined) {
3134
+ try { rawText = JSON.stringify(trialOutcome.raw) } catch { rawText = String(trialOutcome.raw) }
3135
+ }
3136
+ return h('div', { className: 'hook-card' + (folded ? ' folded' : ''), key: hook.id },
3095
3137
  h('div', { className: 'hook-card-head' },
3096
- h('div', { className: 'hook-card-title' },
3138
+ h('span', { className: 'hook-caret', role: 'button', tabIndex: 0, 'aria-expanded': !folded,
3139
+ title: folded ? '展开代码' : '折叠代码', onClick: toggleFold,
3140
+ onKeyDown: (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleFold() } } }, folded ? '▸' : '▾'),
3141
+ h('div', { className: 'hook-card-title', onClick: toggleFold, style: { cursor: 'pointer' } },
3097
3142
  h('span', { className: 'hook-name' }, hook.name),
3098
3143
  h('span', { className: 'hook-pill' }, phaseText[hook.phase] || hook.phase),
3099
- hook.pendingApproval ? h('span', { className: 'hook-pill warn' }, '待批准 · 不会运行') : null,
3100
- hook.enabled === false ? h('span', { className: 'hook-pill' }, '已停用') : null,
3144
+ approved
3145
+ ? h('span', { className: 'hook-pill ok' }, '已批准 · 会运行')
3146
+ : h('span', { className: 'hook-pill warn' }, '未批准 · 不会运行'),
3101
3147
  hook.ruleId ? h('span', { className: 'hook-pill' }, `规则 ${String(hook.ruleId).slice(0, 8)}`) : null,
3102
3148
  ),
3103
3149
  h('div', { className: 'hook-card-actions' },
3104
- h('button', { className: 'linkbtn', onClick: () => (isOpen ? setDraft(null) : edit(hook)), disabled: busy }, isOpen ? '收起' : '编辑代码'),
3150
+ h('button', { className: 'linkbtn', onClick: () => (editing ? setDraft(null) : edit(hook)), disabled: busy }, editing ? '收起' : '编辑代码'),
3105
3151
  h('button', { className: 'linkbtn', onClick: () => run(hook), disabled: busy }, '试跑'),
3106
- h('button', { className: 'linkbtn', onClick: () => toggle(hook), disabled: busy }, hook.enabled === false ? '启用' : '停用'),
3152
+ approved
3153
+ ? h('button', { className: 'linkbtn', onClick: () => revokeApproval(hook), disabled: busy }, '撤销批准')
3154
+ : h('button', { className: 'linkbtn', onClick: () => approve(hook), disabled: busy }, '批准'),
3107
3155
  h('button', { className: 'linkbtn danger', onClick: () => remove(hook), disabled: busy }, '删除'),
3108
3156
  ),
3109
3157
  ),
3110
- h('div', { className: 'hook-card-meta' },
3111
- (hook.scopes && hook.scopes.length > 0 ? `作用域 ${hook.scopes.join(' / ')}` : '作用域:全部'),
3112
- ' · ',
3113
- (hook.kinds && hook.kinds.length > 0 ? `类型 ${hook.kinds.join(' / ')}` : '类型:全部'),
3114
- hook.runCount > 0 ? ` · 运行 ${hook.runCount} 次` : ' · 还没运行过',
3115
- hook.rejectCount > 0 ? ` / 拒绝 ${hook.rejectCount}` : '',
3116
- hook.errorCount > 0 ? ` / 出错 ${hook.errorCount}` : '',
3117
- hook.lastOutcome === 'error' ? ` · 最近出错:${hook.lastMessage || '(无说明)'}` : '',
3118
- hook.lastOutcome === 'rejected' ? ` · 最近拒绝:${hook.lastMessage || '(无说明)'}` : '',
3119
- ),
3120
- isOpen
3121
- ? renderEditor()
3122
- : h('pre', { className: 'hook-code-preview' }, hook.code),
3123
- h('div', { className: 'hook-trial' },
3124
- h('input', {
3125
- type: 'text',
3126
- placeholder: '拿一段样例正文试跑(不写记忆)',
3127
- value: trialText,
3128
- onChange: (e) => setTrialText(e.target.value),
3129
- }),
3130
- trialOutcome !== undefined && trialOutcome !== null
3131
- ? h('div', { className: 'hook-trial-result ' + (trialOutcome.error ? 'err' : trialOutcome.ok ? 'ok' : 'rej') },
3132
- trialOutcome.error
3133
- ? `脚本运行失败:${trialOutcome.error}`
3134
- : trialOutcome.ok
3135
- ? `通过${trialOutcome.message ? ` · ${trialOutcome.message}` : ''}(${trialOutcome.durationMs}ms)`
3136
- : `不通过 · ${trialOutcome.message || '(脚本没给 message)'}(${trialOutcome.durationMs}ms)`)
3137
- : null,
3158
+ folded ? null : h('div', null,
3159
+ h('div', { className: 'hook-card-meta' },
3160
+ (hook.scopes && hook.scopes.length > 0 ? `作用域 ${hook.scopes.join(' / ')}` : '作用域:全部'),
3161
+ ' · ',
3162
+ (hook.kinds && hook.kinds.length > 0 ? `类型 ${hook.kinds.join(' / ')}` : '类型:全部'),
3163
+ hook.runCount > 0 ? ` · 运行 ${hook.runCount} 次` : ' · 还没运行过',
3164
+ hook.rejectCount > 0 ? ` / 拒绝 ${hook.rejectCount}` : '',
3165
+ hook.errorCount > 0 ? ` / 出错 ${hook.errorCount}` : '',
3166
+ hook.lastOutcome === 'error' ? ` · 最近出错:${hook.lastMessage || '(无说明)'}` : '',
3167
+ hook.lastOutcome === 'rejected' ? ` · 最近拒绝:${hook.lastMessage || '(无说明)'}` : '',
3168
+ ),
3169
+ editing ? renderEditor() : h('pre', { className: 'hook-code-preview' }, hook.code),
3170
+ h('div', { className: 'hook-trial' },
3171
+ h('input', {
3172
+ type: 'text',
3173
+ placeholder: '拿一段样例正文试跑(不写记忆)',
3174
+ value: trialText,
3175
+ onChange: (e) => setTrialText(e.target.value),
3176
+ }),
3177
+ showTrial
3178
+ ? h('div', { className: 'hook-trial-result ' + (trialOutcome.error ? 'err' : trialOutcome.ok ? 'ok' : 'rej') },
3179
+ h('div', { style: { display: 'flex', alignItems: 'center' } },
3180
+ h('span', null,
3181
+ `${phaseTrialLabel(hook.phase)} · `,
3182
+ trialOutcome.error
3183
+ ? `运行失败:${trialOutcome.error}`
3184
+ : hook.phase === 'before-save'
3185
+ ? (trialOutcome.ok ? '允许保存(通过)' : `拒绝保存 · ${trialOutcome.message || '(无理由)'}`)
3186
+ : hook.phase === 'after-save'
3187
+ ? (trialOutcome.ok ? '观察通过(不阻断)' : `附注 · ${trialOutcome.message || '(无说明)'}`)
3188
+ : (trialOutcome.ok ? '保留并记录(通过)' : `不通过 · ${trialOutcome.message || '(无理由)'}`),
3189
+ ` (${trialOutcome.durationMs}ms)`,
3190
+ trialOutcome.drop === true ? ' · 整条丢弃' : '',
3191
+ ),
3192
+ h('button', { className: 'linkbtn hook-trial-close', onClick: () => setTrialClosed((prev) => new Set(prev).add(hook.id)), title: '关闭试跑输出' }, '×'),
3193
+ ),
3194
+ trialOutcome.content !== undefined ? h('div', null, `改写后正文:${trialOutcome.content}`) : null,
3195
+ trialOutcome.logs && trialOutcome.logs.length > 0 ? h('div', null, `日志:${trialOutcome.logs.join(' / ')}`) : null,
3196
+ rawText !== '' ? h('pre', { className: 'hook-trial-raw' }, `脚本真实输出:${rawText}`) : null,
3197
+ )
3198
+ : null,
3199
+ ),
3138
3200
  ),
3139
3201
  )
3140
3202
  }
@@ -3176,12 +3238,30 @@ window.__ModuleLoader__.load({
3176
3238
  ? h('span', { className: 'warn' }, `${pendingCount} 条代码还在等批准,未批准不会运行`)
3177
3239
  : null,
3178
3240
  ),
3241
+ h('div', { className: 'hook-filters' },
3242
+ h('span', null, '筛选:'),
3243
+ h('label', null, '时机 ', h(Dropdown, {
3244
+ items: [{ value: '', label: '全部' }, { value: 'before-save', label: '保存前校验' }, { value: 'after-save', label: '保存后观察' }, { value: 'before-inject', label: '注入前解析' }],
3245
+ value: filterPhase, onChange: setFilterPhase,
3246
+ })),
3247
+ h('label', null, '作用域 ', h(Dropdown, {
3248
+ items: [{ value: '', label: '全部' }, ...allScopes.map((scope) => ({ value: scope, label: scope }))],
3249
+ value: filterScope, onChange: setFilterScope,
3250
+ })),
3251
+ h('label', null, '批准状态 ', h(Dropdown, {
3252
+ items: [{ value: '', label: '全部' }, { value: 'approved', label: '已批准' }, { value: 'pending', label: '未批准' }],
3253
+ value: filterApproval, onChange: setFilterApproval,
3254
+ })),
3255
+ h('span', { className: 'muted' }, `${shownHooks.length} / ${hooks.length} 条`),
3256
+ ),
3179
3257
  draft !== null && draft.id === '' ? renderEditor() : null,
3180
3258
  error && draft === null ? h('div', { className: 'err' }, error) : null,
3181
- hooks.length === 0
3259
+ shownHooks.length === 0
3182
3260
  ? h('div', { className: 'empty' },
3183
- '还没有规则代码。可以让 Agent 在 memory_save 时带 hookCode,或点右上角「新建代码」。')
3184
- : h('div', { className: 'hook-list' }, hooks.map(renderCard)),
3261
+ hooks.length === 0
3262
+ ? '还没有规则代码。可以让 Agent 在 memory_save 时带 hookCode,或点右上角「新建代码」。'
3263
+ : '没有符合筛选条件的规则代码。')
3264
+ : h('div', { className: 'hook-list' }, shownHooks.map(renderCard)),
3185
3265
  )
3186
3266
  }
3187
3267
 
@@ -8,6 +8,8 @@ export const POLICY_TEXT = `## 记忆系统
8
8
 
9
9
  memory_search 只返回印象(ID、作用域、类型、标签和少量摘要);判断相关后再用 memory_get(ids, fields) 取正文。fields 省略 = content + scope + kind + tags;只要摘要用 ["summary"],只要正文用 ["content"],需要重要度 / 时间 / 触发词等再显式加上对应字段。
10
10
 
11
+ memory_list 默认不返回时间戳;要完整时间(精确到秒)就传 fields:["full_time"],每条会给 createdAt / updatedAt / expiresAt 的 ISO 时间戳并显示在列表文案里。
12
+
11
13
  搜索命中作用域外记忆时默认**不弹审批**:结果里的 outOfScope 字段只列出命中的作用域——各几条、以及这些作用域的**用途描述**,不含任何记忆内容(也就没有摘要可引用)。确认某个作用域的用途确实与本次任务相关时,再用 memory_search 带 requestApproval=true 重新发起同一次搜索(这时才弹审批),或用 memory_scopes(action="request") 申请该作用域的本会话权限。
12
14
 
13
15
  需要知道有哪些作用域、各自用来做什么、当前能不能读/写时,用 memory_scopes(action="list")。它只返回目录元信息(名字 / 用途 / 访问状态)与初始化记录正文,不返回普通记忆正文;范围外作用域在绝对限制下仍可发现,但正文(含初始化记录)永不可读、不可申请。
package/lib/panel.js CHANGED
@@ -1288,6 +1288,15 @@ async function handle(ctx, routePath, req, res) {
1288
1288
  return
1289
1289
  }
1290
1290
 
1291
+ if (action === 'revoke-approval') {
1292
+ // 0.38.0:撤销批准 ≠ 停用 —— 代码保留、变回待批准;未批准不会运行。
1293
+ if (typeof memory.revokeHookApproval !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供撤销批准接口(请升级 @restregular/dsh-memory)')
1294
+ const id = typeof body.id === 'string' ? body.id : ''
1295
+ if (id === '') throw new ApiError(400, 'HOOK_ID_REQUIRED', 'id 不能为空')
1296
+ writeJson(res, { ok: true, value: { revoked: memory.revokeHookApproval(id) } })
1297
+ return
1298
+ }
1299
+
1291
1300
  if (action === 'delete') {
1292
1301
  if (typeof memory.deleteHook !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供记忆钩子接口')
1293
1302
  const id = typeof body.id === 'string' ? body.id : ''
@@ -414,6 +414,10 @@ export class CordisMemoryService extends Service {
414
414
  return this.impl.approveHook(id)
415
415
  }
416
416
 
417
+ revokeHookApproval(id ) {
418
+ return this.impl.revokeHookApproval(id)
419
+ }
420
+
417
421
  hookPendingApproval(id ) {
418
422
  return this.impl.hookPendingApproval(id)
419
423
  }
@@ -107,6 +107,22 @@ const PHASE_ENTRY = {
107
107
 
108
108
 
109
109
 
110
+ /**
111
+ * 钩子脚本能读到的注入设置(只读快照,随 ctx 进沙箱)。
112
+ *
113
+ * 只暴露"和摘要字数相关"的几项,不把整个 settings.json 倒进沙箱:
114
+ * 脚本用它决定"冒号前的内容如果太长,按哪个上限截断"。
115
+ * 各项与 inject-settings.ts 里的默认值一致,调用方(parseForInject)用实时设置覆盖。
116
+ */
117
+
118
+                          
119
+
120
+                      
121
+
122
+                    
123
+
124
+
125
+
110
126
  /** 一次运行的输入。 */
111
127
 
112
128
 
@@ -114,6 +130,8 @@ const PHASE_ENTRY = {
114
130
 
115
131
 
116
132
 
133
+                             
134
+
117
135
 
118
136
 
119
137
  /** 单个钩子的运行结果。 */
@@ -132,6 +150,8 @@ const PHASE_ENTRY = {
132
150
 
133
151
          
134
152
 
153
+                                     
154
+
135
155
 
136
156
 
137
157
 
@@ -276,7 +296,7 @@ export function runHookCode(
276
296
  phase ,
277
297
  input ,
278
298
  settings ,
279
- ) {
299
+ ) {
280
300
  const timeout = Math.max(20, Math.min(5000, settings.timeoutMs))
281
301
  const key = `${phase}:${hashHookCode(code)}`
282
302
  let compiled = compileCache.get(key)
@@ -300,6 +320,8 @@ export function runHookCode(
300
320
  ...(input.tool !== undefined ? { tool: input.tool } : {}),
301
321
  ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
302
322
  ...(input.description !== undefined ? { description: input.description } : {}),
323
+ // 0.37.0:只读设置快照进沙箱 ctx.settings —— 脚本能按当前摘要字数限制截断。
324
+ ...(input.settings !== undefined ? { settings: input.settings } : {}),
303
325
  now: Date.now(),
304
326
  })
305
327
  const driver = new vm.Script(
@@ -313,7 +335,10 @@ export function runHookCode(
313
335
  if (raw !== null && typeof raw === 'object' && typeof (raw ).then === 'function') {
314
336
  return { ok: true, error: '脚本返回了 Promise:钩子必须是同步函数(不允许 await)', logs }
315
337
  }
316
- return { ...normalizeHookResult(raw), logs }
338
+ // 0.38.0:raw 只保留可 JSON 序列化的部分,避免宿主对象/循环引用流到外面。
339
+ let safeRaw
340
+ try { safeRaw = JSON.parse(JSON.stringify(raw ?? null)) } catch { safeRaw = String(raw) }
341
+ return { ...normalizeHookResult(raw), logs, raw: safeRaw }
317
342
  } catch (error) {
318
343
  const message = error instanceof Error ? error.message : String(error)
319
344
  const timedOut = /timed out|Script execution timed out/i.test(message)
@@ -372,15 +397,21 @@ export class HookStore {
372
397
  this.hooks = list.filter((hook) =>
373
398
  hook !== null && typeof hook === 'object' && typeof hook.id === 'string' && typeof hook.code === 'string')
374
399
  // 老文件可能缺统计字段:补齐,避免调用方到处判空。
375
- .map((hook) => ({
376
- ...hook,
377
- enabled: hook.enabled !== false,
378
- scopes: Array.isArray(hook.scopes) ? hook.scopes : [],
379
- kinds: Array.isArray(hook.kinds) ? hook.kinds : [],
380
- runCount: Number(hook.runCount) || 0,
381
- errorCount: Number(hook.errorCount) || 0,
382
- rejectCount: Number(hook.rejectCount) || 0,
383
- }))
400
+ .map((hook) => {
401
+ // 0.38.0:移除启用/停用语义,审批成为唯一闸门。老数据里 enabled:false
402
+ // 的钩子等同于"用户不想让它跑" → 迁成"未批准"(清掉指纹),避免它突然生效。
403
+ const migrated = {
404
+ ...hook,
405
+ enabled: true,
406
+ scopes: Array.isArray(hook.scopes) ? hook.scopes : [],
407
+ kinds: Array.isArray(hook.kinds) ? hook.kinds : [],
408
+ runCount: Number(hook.runCount) || 0,
409
+ errorCount: Number(hook.errorCount) || 0,
410
+ rejectCount: Number(hook.rejectCount) || 0,
411
+ }
412
+ if (hook.enabled === false) delete migrated.approvedHash
413
+ return migrated
414
+ })
384
415
  } catch (error) {
385
416
  // 坏文件不能让记忆整体不可用:退化成"没有钩子",并在日志里说清楚。
386
417
  this.onWarn(`hooks.json 读取失败(按无钩子继续):${error instanceof Error ? error.message : String(error)}`)
@@ -419,9 +450,9 @@ export class HookStore {
419
450
  */
420
451
  forRun(phase , target , settings , ignoreApproval = false) {
421
452
  this.load()
453
+ // 0.38.0:不再看 enabled(启用/停用语义已移除)—— 唯一闸门是"是否被批准"。
422
454
  return this.hooks.filter((hook) =>
423
- hook.enabled
424
- && hook.phase === phase
455
+ hook.phase === phase
425
456
  && hookApplies(hook, target)
426
457
  && (ignoreApproval || !hookNeedsApproval(hook, settings)))
427
458
  }
@@ -442,7 +473,8 @@ export class HookStore {
442
473
  existing.name = (input.name ?? existing.name).trim() || existing.name
443
474
  existing.phase = input.phase
444
475
  existing.code = code
445
- existing.enabled = input.enabled ?? existing.enabled
476
+ // 0.38.0:enabled 不再是开关,统一保持 true;"不让跑"请用撤销批准。
477
+ existing.enabled = true
446
478
  if (Array.isArray(input.scopes)) existing.scopes = input.scopes.map(String)
447
479
  if (Array.isArray(input.kinds)) existing.kinds = input.kinds.map(String)
448
480
  if (input.description !== undefined) existing.description = input.description
@@ -469,7 +501,7 @@ export class HookStore {
469
501
  name: (input.name ?? '').trim() || `${input.phase} 规则`,
470
502
  phase: input.phase,
471
503
  code,
472
- enabled: input.enabled ?? true,
504
+ enabled: true, // 0.38.0:审批是唯一闸门,enabled 恒 true(保留字段只为兼容旧数据)。
473
505
  scopes: Array.isArray(input.scopes) ? input.scopes.map(String) : [],
474
506
  kinds: Array.isArray(input.kinds) ? input.kinds.map(String) : [],
475
507
  ...(input.description !== undefined ? { description: input.description } : {}),
@@ -528,6 +560,21 @@ export class HookStore {
528
560
  return true
529
561
  }
530
562
 
563
+ /**
564
+ * 撤销批准(0.38.0):清掉已批准的指纹 → 代码变回"待批准、不会运行"。
565
+ * 代码本身保留,用户可随时再批准回来;不改变 enabled(批准语义与启用彻底分开)。
566
+ */
567
+ revoke(id ) {
568
+ this.load()
569
+ const hook = this.hooks.find((item) => item.id === id)
570
+ if (hook === undefined) return false
571
+ if (hook.approvedHash === undefined) return false
572
+ delete hook.approvedHash
573
+ hook.updatedAt = Date.now()
574
+ this.persist()
575
+ return true
576
+ }
577
+
531
578
  /** 测试用:绕过缓存重新读盘。 */
532
579
  reload() {
533
580
  this.loaded = false
@@ -576,6 +623,7 @@ export function runHooks(
576
623
  ...(result.drop === true ? { drop: true } : {}),
577
624
  ...(crashed ? { error: result.error } : {}),
578
625
  ...(result.logs.length > 0 ? { logs: result.logs.slice(0, 20) } : {}),
626
+ ...(result.raw !== undefined ? { raw: result.raw } : {}),
579
627
  }
580
628
  try {
581
629
  store.recordRun(hook.id, {
@@ -992,6 +992,11 @@ export class LocalMemoryService {
992
992
  return this.hooks.approve(id, hashHookCode(hook.code))
993
993
  }
994
994
 
995
+ /** 撤销审批(0.38.0):代码保留、变回待批准;未批准不会运行。 */
996
+ revokeHookApproval(id ) {
997
+ return this.hooks.revoke(id)
998
+ }
999
+
995
1000
  /** 这条钩子是否还需要用户批准(代码变过也算需要)。 */
996
1001
  hookPendingApproval(id ) {
997
1002
  const hook = this.hooks.get(id)
@@ -1084,6 +1089,7 @@ export class LocalMemoryService {
1084
1089
  ...(result.drop === true ? { drop: true } : {}),
1085
1090
  ...(crashed ? { error: result.error } : {}),
1086
1091
  ...(result.logs.length > 0 ? { logs: result.logs.slice(0, 20) } : {}),
1092
+ ...(result.raw !== undefined ? { raw: result.raw } : {}),
1087
1093
  }]
1088
1094
  }
1089
1095
 
@@ -1100,6 +1106,13 @@ export class LocalMemoryService {
1100
1106
  {
1101
1107
  const settings = this.hookSettings()
1102
1108
  if (!settings.enabled || records.length === 0) return { records: [...records], changed: [], warnings: [] }
1109
+ // 0.37.0:设置快照只读一次,传给每条记录的 before-inject 钩子(ctx.settings)。
1110
+ const injectCfg = this.injectSettings()
1111
+ const settingsView = {
1112
+ digestChars: 160,
1113
+ impressionChars: injectCfg.impression.chars,
1114
+ recallChars: 300,
1115
+ }
1103
1116
  const out = []
1104
1117
  const changed = []
1105
1118
  const warnings = []
@@ -1122,6 +1135,7 @@ export class LocalMemoryService {
1122
1135
  },
1123
1136
  tool: 'inject',
1124
1137
  ...(sessionId !== undefined ? { sessionId } : {}),
1138
+ settings: settingsView,
1125
1139
  })
1126
1140
  const outcome = outcomes.find((item) => item.hook.id === hook.id)
1127
1141
  if (outcome === undefined) continue
@@ -137,18 +137,17 @@ export function apply(ctx , config = {}) {
137
137
  }
138
138
 
139
139
  register(tools.memory_save, (value, _args, exec) => {
140
- const agent = (exec )?.agent
140
+ // 0.37.0:作用域 key 只在头部出现一次 —— head 直接写原始 key(value.scope),
141
+ // 去掉了原先额外追加的那行 key 文案(它和 @ <scope> 说同一件事,重复)。
142
+ // 文案仍以「已保存记忆 <uuid> @ <key>」开头,signals.ts 按 UUID 抽取不受影响。
141
143
  const head = value.deduped
142
- ? `已更新既有记忆(内容相同,去重):${value.id} @ ${renderScope(value.scope, agent)}`
143
- : `已保存记忆 ${value.id} @ ${renderScope(value.scope, agent)}`
144
- // 0.36.0:所有 memory_save 返回统一带上保存到的目标作用域 key;用 supersedes
145
- // 修正旧记忆时额外说明修正关系(旧记录所在作用域可不同)。文案仍以
146
- // 「已保存记忆 <uuid> @ <scope>」开头,signals.ts 按 UUID 抽取不受影响。
147
- const scopeKeyLine = `保存到的目标作用域 key:${value.scope}`
144
+ ? `已更新既有记忆(内容相同,去重):${value.id} @ ${value.scope}`
145
+ : `已保存记忆 ${value.id} @ ${value.scope}`
146
+ // supersedes 场景补一条修正关系(旧记录所在作用域可不同)。
148
147
  const correctionLine = value.supersedes === undefined
149
148
  ? ''
150
149
  : `\n已用本条修正旧记忆 ${value.supersedes.id}${value.supersedes.scope !== undefined ? `(旧记录在 ${value.supersedes.scope})` : ''}`
151
- const tail = `\n${scopeKeyLine}${correctionLine}`
150
+ const tail = correctionLine
152
151
  const hook = value.hook
153
152
  if (hook === undefined) return `${head}${tail}`
154
153
  const approvalText = {
@@ -218,7 +218,7 @@ import { canonicalWorkspacePath, defaultScopeDescription, normalizeScopeInput, r
218
218
 
219
219
 
220
220
 
221
-
221
+
222
222
                  
223
223
 
224
224
                          
@@ -325,6 +325,8 @@ import { canonicalWorkspacePath, defaultScopeDescription, normalizeScopeInput, r
325
325
 
326
326
                        
327
327
 
328
+                              
329
+
328
330
                
329
331
 
330
332
                             
@@ -378,6 +380,8 @@ import { canonicalWorkspacePath, defaultScopeDescription, normalizeScopeInput, r
378
380
 
379
381
 
380
382
 
383
+                         
384
+
381
385
 
382
386
 
383
387
 
@@ -1633,16 +1637,41 @@ export function memoryForgetTool(opts )
1633
1637
  }
1634
1638
  }
1635
1639
 
1640
+ /** 毫秒时间戳 → ISO 8601 精确到秒(去掉毫秒)。非法值返回 undefined。 */
1641
+ function isoSecond(value ) {
1642
+ if (typeof value !== 'number' || !Number.isFinite(value)) return undefined
1643
+ return new Date(value).toISOString().slice(0, 19) + 'Z'
1644
+ }
1645
+
1646
+ /** memory_list 的 fields 解析:目前只认 full_time。 */
1647
+ function listWantsFullTime(fields ) {
1648
+ return Array.isArray(fields) && fields.some((field) => String(field).trim() === 'full_time')
1649
+ }
1650
+
1636
1651
 
1637
1652
 
1638
1653
 
1639
1654
 
1655
+
1656
+                         
1657
+                   
1658
+
1659
+
1640
1660
                              
1641
1661
 
1642
1662
 
1643
1663
 
1644
1664
 
1645
-
1665
+
1666
+
1667
+
1668
+
1669
+
1670
+
1671
+
1672
+                      
1673
+
1674
+
1646
1675
                                 
1647
1676
 
1648
1677
 
@@ -1661,6 +1690,11 @@ export function memoryListTool(opts )
1661
1690
  kind: { type: 'string' },
1662
1691
  limit: { type: 'number', description: '1~200' },
1663
1692
  description: { type: 'string', description: DESCRIPTION_PARAM_DESCRIPTION },
1693
+ fields: {
1694
+ type: 'array',
1695
+ items: { type: 'string' },
1696
+ description: '可选字段。`full_time` = 每条记忆给出精确到秒的完整时间戳(createdAt / updatedAt / expiresAt);不传则不带。',
1697
+ },
1664
1698
  },
1665
1699
  async execute(args , exec ) {
1666
1700
  const service = svc(opts)
@@ -1728,12 +1762,24 @@ export function memoryListTool(opts )
1728
1762
  const selected = raw
1729
1763
  .filter((record) => insideIds.has(record.id) || approvedOutsideIds.has(record.id))
1730
1764
  .slice(0, limit)
1765
+ const wantFullTime = listWantsFullTime(args.fields)
1731
1766
  records = selected.map((r) => ({
1732
1767
  id: r.id,
1733
1768
  scope: r.scope,
1734
1769
  kind: r.kind,
1735
1770
  updatedAt: r.updatedAt,
1736
1771
  content: r.content,
1772
+ ...(wantFullTime
1773
+ ? {
1774
+ fullTime: {
1775
+ createdAt: isoSecond(r.createdAt) ?? isoSecond(r.updatedAt) ?? '',
1776
+ updatedAt: isoSecond(r.updatedAt) ?? '',
1777
+ ...(r.expiresAt !== undefined && Number.isFinite(r.expiresAt)
1778
+ ? { expiresAt: isoSecond(r.expiresAt) }
1779
+ : {}),
1780
+ },
1781
+ }
1782
+ : {}),
1737
1783
  }))
1738
1784
  const denied = outside.length - approvedOutside.length
1739
1785
  if (denied > 0) {
@@ -2337,7 +2383,7 @@ export function memoryBlockTool(opts )
2337
2383
  }
2338
2384
 
2339
2385
  /** `memory_hooks` 支持的 action。 */
2340
-
2386
+
2341
2387
 
2342
2388
 
2343
2389
 
@@ -2413,12 +2459,11 @@ export function memoryHooksTool(opts )
2413
2459
  parameters: {
2414
2460
  action: {
2415
2461
  type: 'string',
2416
- enum: ['list', 'get', 'save', 'delete', 'approve', 'enable', 'disable', 'run'],
2462
+ enum: ['list', 'get', 'save', 'delete', 'approve', 'revoke-approval', 'enable', 'disable', 'run'],
2417
2463
  required: true,
2418
- description: 'list=列全部(不含代码);get=读代码;save=新建/更新;delete=删除(不可逆,**必须二次确认**:先不带 confirm 调用拿预览,再带 confirm="<钩子的 name 或 id>" 重复调用才真删);approve=请用户批准代码(首次或改代码后);'
2419
- + 'enable/disable=开关;run=拿一段正文试跑(不写记忆)。',
2464
+ description: 'list=列全部(不含代码);get=读代码;save=新建/更新;delete=删除(不可逆,**必须二次确认**:先不带 confirm 调用拿预览,再带 confirm="<钩子的 name 或 id>" 重复调用才真删);approve=批准代码使其运行;revoke-approval=撤销批准(代码保留、变回待批准、不再运行);enable/disable=旧别名(等同 approve/revoke-approval);run=拿一段正文试跑(不写记忆)。',
2420
2465
  },
2421
- id: { type: 'string', description: '钩子 id(或唯一前缀 / 名字);get/delete/approve/enable/disable/run 必填' },
2466
+ id: { type: 'string', description: '钩子 id(或唯一前缀 / 名字);get/delete/approve/revoke-approval/enable/disable/run 必填' },
2422
2467
  confirm: { type: 'string', description: 'delete 专用二次确认:值必须等于目标钩子的 name 或完整 id。删除不可逆(hooks.json 直接覆盖、无回收站),不带或写错只返回待删预览、不会删除。' },
2423
2468
  code: { type: 'string', description: '脚本源码(save 必填)。入口函数名与返回约定见技能 memory-hook-scripts。' },
2424
2469
  phase: {
@@ -2566,26 +2611,47 @@ export function memoryHooksTool(opts )
2566
2611
  }
2567
2612
  }
2568
2613
 
2614
+ if (action === 'revoke-approval') {
2615
+ // 0.38.0:撤销批准 = 代码保留、变回待批准;未批准不会运行。与"停用"彻底分开。
2616
+ const hook = findHook(service, args.id ?? '')
2617
+ if (typeof service.revokeHookApproval !== 'function') {
2618
+ throw new MemoryToolError('HOOKS_UNSUPPORTED', '当前 memory provider 不支持撤销批准(请升级 @restregular/dsh-memory)')
2619
+ }
2620
+ const revoked = service.revokeHookApproval(hook.id)
2621
+ const fresh = typeof service.getHook === 'function' ? service.getHook(hook.id) : undefined
2622
+ return {
2623
+ action,
2624
+ hooks: fresh !== undefined ? [withApproval(fresh)] : [],
2625
+ note: revoked
2626
+ ? `已撤销「${hook.name}」的批准:代码保留,但变回待批准,**不会运行**。`
2627
+ : `「${hook.name}」本来就没有批准过。`,
2628
+ }
2629
+ }
2630
+
2569
2631
  if (action === 'enable' || action === 'disable') {
2632
+ // 0.38.0:保留 action 仅为向后兼容 —— 启用/停用语义已移除,统一映射到批准/撤销批准。
2570
2633
  const hook = findHook(service, args.id ?? '')
2571
- if (typeof service.saveHook !== 'function') {
2572
- throw new MemoryToolError('HOOKS_UNSUPPORTED', '当前 memory provider 不支持记忆钩子')
2634
+ if (action === 'disable') {
2635
+ if (typeof service.revokeHookApproval !== 'function') {
2636
+ throw new MemoryToolError('HOOKS_UNSUPPORTED', '当前 memory provider 不支持撤销批准(请升级 @restregular/dsh-memory)')
2637
+ }
2638
+ const revoked = service.revokeHookApproval(hook.id)
2639
+ const fresh = typeof service.getHook === 'function' ? service.getHook(hook.id) : undefined
2640
+ return {
2641
+ action,
2642
+ hooks: fresh !== undefined ? [withApproval(fresh)] : [],
2643
+ note: `「停用」已更名为「撤销批准」:${revoked ? '已撤销批准,代码保留但**不会运行**。' : '本来就未批准。'}`,
2644
+ }
2573
2645
  }
2574
- const saved = service.saveHook({
2575
- id: hook.id,
2576
- name: hook.name,
2577
- phase: hook.phase,
2578
- code: hook.code,
2579
- enabled: action === 'enable',
2580
- scopes: hook.scopes,
2581
- kinds: hook.kinds,
2582
- ...(hook.description !== undefined ? { description: hook.description } : {}),
2583
- ...(hook.ruleId !== undefined ? { ruleId: hook.ruleId } : {}),
2584
- })
2646
+ if (typeof service.approveHook !== 'function') {
2647
+ throw new MemoryToolError('HOOKS_UNSUPPORTED', '当前 memory provider 不支持批准')
2648
+ }
2649
+ service.approveHook(hook.id)
2650
+ const fresh = typeof service.getHook === 'function' ? service.getHook(hook.id) : undefined
2585
2651
  return {
2586
2652
  action,
2587
- hooks: [withApproval(saved)],
2588
- note: action === 'enable' ? `已启用「${hook.name}」。` : `已停用「${hook.name}」(代码保留,随时可再启用)。`,
2653
+ hooks: fresh !== undefined ? [withApproval(fresh)] : [],
2654
+ note: '「启用」已更名为「批准」:已批准这段代码,从现在起会运行。',
2589
2655
  }
2590
2656
  }
2591
2657
 
@@ -2609,6 +2675,8 @@ export function memoryHooksTool(opts )
2609
2675
  importance: 0.8,
2610
2676
  },
2611
2677
  tool: 'memory_hooks',
2678
+ // 0.37.0:试跑也带设置快照,脚本里读 ctx.settings.* 不会是 undefined。
2679
+ settings: { digestChars: 160, impressionChars: 120, recallChars: 300 },
2612
2680
  }
2613
2681
  const mine = service.runHookTrial(hook.id, input)
2614
2682
  const verdict = mine[0]
@@ -142,7 +142,11 @@ export function renderListResult(value , label ) {
142
142
  omitted += 1
143
143
  return shortId(record.id)
144
144
  }
145
- return `(${label(record.scope)}/${record.kind}) ${record.content}`
145
+ const full = record.fullTime
146
+ const timeLine = full === undefined
147
+ ? ''
148
+ : ` [创建 ${full.createdAt} · 更新 ${full.updatedAt}${full.expiresAt !== undefined ? ` · 过期 ${full.expiresAt}` : ''}]`
149
+ return `(${label(record.scope)}/${record.kind})${timeLine} ${record.content}`
146
150
  }).join('\n')
147
151
  const note = renderWithheldNote(value.withheld)
148
152
  const tail = [omitted > 0 ? DEDUPE_NOTE : '', note].filter((part) => part !== '').join('\n\n')
@@ -385,15 +389,31 @@ export function renderHooksResult(value , label )
385
389
 
386
390
  if (value.action === 'run') {
387
391
  const hook = value.hooks[0]
388
- const head = hook !== undefined ? describe(hook) : ''
392
+ const phase = hook?.phase
393
+ // 0.38.0:不同时机试跑结果侧重不同 —— 校验看通过/拒绝,观察看附注,解析看改写/丢弃。
394
+ const phaseLabel = phase === 'before-save' ? '保存前校验' : phase === 'after-save' ? '保存后观察' : phase === 'before-inject' ? '注入前解析' : '脚本'
395
+ const head = hook !== undefined ? `${describe(hook)} · 试跑(${phaseLabel})` : `试跑(${phaseLabel})`
389
396
  const outcomes = value.outcomes ?? []
390
397
  const detail = outcomes.length === 0
391
398
  ? '(脚本没有命中这次输入)'
392
399
  : outcomes.map((outcome) => {
393
400
  const lines = []
394
401
  if (outcome.error !== undefined) lines.push(`运行失败:${outcome.error}`)
395
- else lines.push(outcome.ok ? '判定:通过' : `判定:不通过${outcome.message !== undefined ? ` —— ${outcome.message}` : ''}`)
396
- if (outcome.content !== undefined) lines.push(`改写后正文:${outcome.content.slice(0, 400)}`)
402
+ else {
403
+ // 判定文案按时机区分。
404
+ if (phase === 'before-save') lines.push(outcome.ok ? '判定:允许保存(通过)' : `判定:拒绝保存 —— ${outcome.message ?? '(脚本没给理由)'}`)
405
+ else if (phase === 'after-save') lines.push(outcome.ok ? '判定:观察通过(不阻断)' : `判定:附注 —— ${outcome.message ?? '(无说明)'}`)
406
+ else lines.push(outcome.ok ? '判定:保留并记录(通过)' : `判定:不通过 —— ${outcome.message ?? '(脚本没给理由)'}`)
407
+ if (outcome.content !== undefined) lines.push(`改写后正文:${outcome.content.slice(0, 400)}`)
408
+ if (outcome.drop === true) lines.push('整条丢弃(drop:true)')
409
+ if (outcome.message !== undefined && phase !== 'before-save') lines.push(`脚本说明:${outcome.message}`)
410
+ // 真实输出:把脚本原始返回值原样回显,而不是只给规范化结论。
411
+ if (outcome.raw !== undefined) {
412
+ let rawText
413
+ try { rawText = JSON.stringify(outcome.raw) } catch { rawText = String(outcome.raw) }
414
+ lines.push(`脚本真实输出:${rawText}`)
415
+ }
416
+ }
397
417
  if (outcome.logs !== undefined && outcome.logs.length > 0) lines.push(`日志:${outcome.logs.join(' / ')}`)
398
418
  lines.push(`耗时 ${outcome.durationMs}ms`)
399
419
  return lines.join('\n')
@@ -412,7 +432,7 @@ export function renderHooksResult(value , label )
412
432
  const note = value.note !== undefined ? `${value.note}\n` : ''
413
433
  const settings = settingsLine()
414
434
  return `${body}${settings !== '' ? `\n\n${settings}` : ''}${note !== '' ? `\n${note}` : ''}`
415
- }
435
+ }
416
436
 
417
437
 
418
438
  //# sourceURL=source/tool-memory/src/render.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.36.1",
3
+ "version": "0.38.0",
4
4
  "description": "DeepSeek Harness 记忆系统(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 五个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",
@@ -76,7 +76,17 @@ function verify(memory) {
76
76
  `ctx` 描述这次调用:
77
77
 
78
78
  ```js
79
- { phase, tool, sessionId, description, now }
79
+ { phase, tool, sessionId, description, now, settings }
80
+ ```
81
+
82
+ `settings` 是**只读设置快照**(0.37.0 起),脚本能读到当前注入设置里的摘要字数限制,按它截断而不写死数字:
83
+
84
+ ```js
85
+ {
86
+ digestChars: 160, // 会话第一步摘要里每条正文的字数上限
87
+ impressionChars: 120, // 自动召回"印象"模式每条摘要的字数上限(面板可改)
88
+ recallChars: 300, // 自动召回完整模式每条正文的字数上限
89
+ }
80
90
  ```
81
91
 
82
92
  `tool` 是触发者(`'memory_save'` / `'memory_hooks'` / `'inject'`),可以据此分支:
@@ -137,6 +147,10 @@ function verify(memory, ctx) {
137
147
 
138
148
  改代码之后要重新批准:审批记的是**代码指纹**,改一个字符就会重新变回待批准。
139
149
 
150
+ **批准是唯一的开关(0.38.0)**:没有"启用 / 停用"了 —— 一段代码要么**已批准(会运行)**,要么**未批准(不会运行)**。面板卡片有「批准」和「撤销批准」两个按钮;`memory_hooks` 的 `approve` 批准、`revoke-approval` 撤销(`enable`/`disable` 只是这两个的旧别名)。撤销批准不会删代码,只是让它停下,随时能再批准回来。老数据里"已停用"的钩子会自动迁成"未批准",不会突然开始运行。
151
+
152
+ 试跑结果按运行时机分开呈现(0.38.0):保存前校验显示"允许保存 / 拒绝保存",保存后观察显示"观察 / 附注",注入前解析显示"改写后正文 / 整条丢弃";并会回显脚本的**真实返回值**和 `log()` 输出,不只给规范化结论。
153
+
140
154
  ## 删除钩子要二次确认(不可逆)
141
155
 
142
156
  `memory_hooks({ action: 'delete', id })` **不会一次删掉**——删除是从 `hooks.json` 直接移除、没有回收站,写好的代码找不回来(只能从会话日志里翻)。所以它分两步: