@oyasmi/pipiclaw 0.8.10-beta.4 → 0.8.10-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +26 -23
  2. package/dist/agent/channel-runner.js +16 -11
  3. package/dist/agent/job-manager.d.ts +7 -0
  4. package/dist/agent/job-manager.js +28 -1
  5. package/dist/agent/session-events.js +2 -1
  6. package/dist/log.js +3 -16
  7. package/dist/memory/commands.js +3 -2
  8. package/dist/memory/consolidation.js +7 -3
  9. package/dist/memory/extraction.js +2 -0
  10. package/dist/memory/files.d.ts +1 -5
  11. package/dist/memory/files.js +30 -21
  12. package/dist/memory/lifecycle.js +4 -3
  13. package/dist/memory/maintenance-gates.js +3 -2
  14. package/dist/memory/maintenance-jobs.js +8 -7
  15. package/dist/memory/metadata.js +9 -7
  16. package/dist/memory/prompt-safety.d.ts +6 -0
  17. package/dist/memory/prompt-safety.js +7 -0
  18. package/dist/memory/review-log.js +7 -0
  19. package/dist/memory/scheduler.js +5 -14
  20. package/dist/memory/session-search.js +18 -8
  21. package/dist/memory/session.js +4 -7
  22. package/dist/memory/task-digest.js +1 -1
  23. package/dist/memory/transcript.js +1 -1
  24. package/dist/playbooks/event-scheduling.md +1 -1
  25. package/dist/playbooks/runtime-orientation.md +1 -0
  26. package/dist/playbooks/task-closeout.md +2 -2
  27. package/dist/playbooks/task-driving.md +4 -4
  28. package/dist/playbooks/task-planning.md +2 -2
  29. package/dist/runtime/bootstrap.js +21 -10
  30. package/dist/runtime/channel-index.d.ts +94 -0
  31. package/dist/runtime/channel-index.js +300 -0
  32. package/dist/runtime/channel-paths.d.ts +1 -0
  33. package/dist/runtime/channel-paths.js +20 -0
  34. package/dist/runtime/channel-queue.d.ts +2 -0
  35. package/dist/runtime/channel-queue.js +4 -0
  36. package/dist/runtime/delivery.js +3 -1
  37. package/dist/runtime/dingtalk.d.ts +27 -0
  38. package/dist/runtime/dingtalk.js +54 -1
  39. package/dist/runtime/event-validation.d.ts +2 -0
  40. package/dist/runtime/event-validation.js +20 -5
  41. package/dist/runtime/events.d.ts +1 -1
  42. package/dist/runtime/events.js +32 -32
  43. package/dist/runtime/store.js +3 -2
  44. package/dist/runtime/task-commands.d.ts +1 -1
  45. package/dist/runtime/task-commands.js +93 -49
  46. package/dist/runtime/task-driver.d.ts +2 -2
  47. package/dist/runtime/task-driver.js +11 -19
  48. package/dist/security/config.d.ts +1 -1
  49. package/dist/security/logger.js +2 -1
  50. package/dist/settings.d.ts +1 -1
  51. package/dist/shared/{config-diagnostics.d.ts → config-diagnostic.d.ts} +1 -0
  52. package/dist/shared/local-time.d.ts +35 -0
  53. package/dist/shared/local-time.js +135 -0
  54. package/dist/subagents/tool.js +2 -1
  55. package/dist/tasks/control.d.ts +2 -0
  56. package/dist/tasks/control.js +52 -12
  57. package/dist/{shared/task-ledger.d.ts → tasks/ledger.d.ts} +1 -1
  58. package/dist/{shared/task-ledger.js → tasks/ledger.js} +8 -8
  59. package/dist/tasks/mutation-lock.d.ts +8 -0
  60. package/dist/tasks/mutation-lock.js +23 -0
  61. package/dist/tasks/store.d.ts +12 -2
  62. package/dist/tasks/store.js +22 -13
  63. package/dist/tasks/transitions.d.ts +1 -1
  64. package/dist/tasks/transitions.js +11 -3
  65. package/dist/tasks/verification.js +2 -1
  66. package/dist/tools/config.d.ts +1 -1
  67. package/dist/tools/event-manage.js +1 -1
  68. package/dist/tools/memory-manage.js +7 -4
  69. package/dist/tools/task-manage/create.js +1 -1
  70. package/dist/tools/task-manage/lifecycle.js +1 -1
  71. package/dist/tools/task-manage/schema.js +10 -3
  72. package/dist/tools/task-manage/shared.js +31 -7
  73. package/dist/tools/task-manage/verification.js +1 -1
  74. package/dist/tools/task-manage.js +14 -1
  75. package/dist/tui/turn-controller.js +2 -1
  76. package/dist/usage/ledger.js +4 -3
  77. package/dist/usage/render.js +8 -8
  78. package/package.json +1 -1
  79. /package/dist/memory/{policy.d.ts → secret-redaction.d.ts} +0 -0
  80. /package/dist/memory/{policy.js → secret-redaction.js} +0 -0
  81. /package/dist/shared/{config-diagnostics.js → config-diagnostic.js} +0 -0
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Pipiclaw
2
2
 
3
- Pipiclaw 是一个个人 AI 助手运行时(AI assistant runtime)。它以 [`pi-coding-agent`](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) 为核心,把一个编码代理变成可以长期使用的工作助手:接入钉钉、保留跨会话记忆、按计划自主推进任务,并实时告诉你它正在做什么。
3
+ Pipiclaw 是一个钉钉优先、可长期运行的 AI coding assistant runtime,个人和团队都可以使用。它以 [`pi-coding-agent`](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) 为核心,把一个编码代理变成可以长期使用的工作助手:接入钉钉、保留跨会话记忆、按计划自主推进任务,并实时告诉你它正在做什么。
4
4
 
5
5
  如果你希望 AI 助手不只是聊天,而是能在钉钉里持续工作、记住上下文、到点自己干活,那么 Pipiclaw 就是为此设计的。
6
6
 
@@ -14,13 +14,13 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
14
14
 
15
15
  **记得住事。** 每个会话通道(channel)有自己的分层记忆:`SESSION.md`(当前工作态)、`MEMORY.md`(稳定事实与偏好)、`HISTORY.md`(更早摘要),工作区层还有 `SOUL.md`(身份语气)与 `AGENTS.md`(工作规则)。运行时按当前请求做相关召回(relevant recall),后台维护调度器在本地闸门通过后才做 LLM 整理,不烧无谓的 token。冷存储历史可用 `session_search` 按需检索,`memory_manage` 支持按需保存、检索、忘记。
16
16
 
17
- **自己推进长程工作。** 定时事件支持立即、单次、周期三类,`preAction` 可用脚本做零 token 的触发前门控。语义更高一层的是任务台账(task ledger):任务以 Markdown 文件持久存在,内建 task driver 到点自动恢复、有进展有界续跑、停滞自动退避;配套受预算约束的恢复、独立验收、外部副作用授权,以及 `/tasks` 系列零 LLM 成本的控制面命令。
17
+ **自己推进长程工作。** 定时事件支持单次、周期两类,`preAction` 可用脚本做零 token 的触发前门控;当前回合能做的事直接做,不再创建 immediate 事件。语义更高一层的是任务台账(task ledger):任务以 Markdown 文件持久存在,内建 task driver 到点自动恢复、有进展有界续跑、停滞自动退避;配套受预算约束的恢复、独立验收、外部副作用授权,以及 `/tasks` 系列零 LLM 成本的控制面命令。
18
18
 
19
- **会用工具、能委派。** 内建 `bash`(支持 `async` 后台作业)、`read`(含目录树与 PDF)、`write` / `edit`、结构化 `grep`、`web_search` / `web_fetch`(结果缓存与分页续读),以及 `send_media`——生成好的报表、截图、导出文件可以作为原生附件直接发回钉钉,而不是丢给你一个打不开的主机路径。工作区配置的子代理可以把 reviewer、researcher 这类角色沉淀成可复用能力,支持独立验收(verify);workspace skills 沉淀你自己的流程知识。完整清单见 [docs/tools.md](./docs/tools.md)。
19
+ **会用工具、能委派。** 内建 `bash`(支持 `async` 后台作业)、`read`(含目录树与 PDF)、`write` / `edit`、结构化 `grep`、`web_search` / `web_fetch`(结果缓存与分页续读),以及 `send_media`——生成好的报表、截图、导出文件可以作为原生附件直接发回钉钉,而不是丢给你一个打不开的主机路径。工作区配置的子代理可以把 reviewer、researcher 这类角色沉淀成可复用能力,支持独立验收(verify);workspace skills 沉淀你自己的流程知识。完整清单见 [docs/tools.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/tools.md)。
20
20
 
21
- **有安全护栏。** 所有文件、命令、网络工具都经过安全守卫:`bash` 命令拦截、统一路径检查、常见凭据与敏感位置默认拒绝、阻断写入审计日志;可通过 `security.json` 做实例级策略调整。详见 [docs/security.md](./docs/security.md)。
21
+ **有安全护栏。** 所有文件、命令、网络工具都经过安全守卫:`bash` 命令拦截、统一路径检查、常见凭据与敏感位置默认拒绝、阻断写入审计日志;可通过 `security.json` 做实例级策略调整。详见 [docs/security.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/security.md)。
22
22
 
23
- **知识不随升级漂移。** Runtime 机制知识以 playbooks 随 npm 包发布、按需加载,系统提示只保留小型索引;`AGENTS.md` 与 workspace skills 完全归你和团队所有,升级不会覆盖,也不需要抄录产品文档。详见 [docs/runtime-playbooks.md](./docs/runtime-playbooks.md)。
23
+ **知识不随升级漂移。** Runtime 机制知识以 playbooks 随 npm 包发布、按需加载,系统提示只保留小型索引;`AGENTS.md` 与 workspace skills 完全归你和团队所有,升级不会覆盖,也不需要抄录产品文档。详见 [docs/runtime-playbooks.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/runtime-playbooks.md)。
24
24
 
25
25
  ## 快速开始(Quickstart)
26
26
 
@@ -92,7 +92,7 @@ pipiclaw
92
92
  - `robotCode` 留空时回退到 `clientId`。
93
93
  - `cardTemplateId` 建议配置(正常使用推荐启用 AI Card);示例先留空是为了让第一轮接入更稳,排查链路时也建议临时留空。
94
94
  - `allowFrom` 为 `[]` 或省略时允许所有人;灰度期可填测试人员的 staff ID。
95
- - 更多字段(`busyMessageDefault`、`responseMode`、`cardAutoLayout`)见[配置手册](./docs/configuration.md)。
95
+ - 更多字段(`busyMessageDefault`、`responseMode`、`cardAutoLayout`)见[配置速查](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md)和[字段参考](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration-reference.md)。
96
96
 
97
97
  ### 6. 配置模型(Configure Models)
98
98
 
@@ -131,7 +131,7 @@ export ANTHROPIC_API_KEY=sk-ant-...
131
131
 
132
132
  - `apiKey` 可以写真实 key、环境变量名,或 `!command`;不想把凭据写进 `models.json`,可在 `auth.json` 写同名 provider 的凭据。
133
133
  - 很多 OpenAI-compatible 服务不支持 `developer` role / `reasoning_effort`,遇到兼容问题先保留上面的 `compat`。
134
- - 完整字段与更多场景(Ollama、企业代理等)见[配置手册](./docs/configuration.md)。
134
+ - 完整字段与更多场景(Ollama、企业代理等)见[配置速查](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md)和[字段参考](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration-reference.md)。
135
135
 
136
136
  ### 7. 可选:设置默认模型(Optional: Set a Default Model)
137
137
 
@@ -163,7 +163,7 @@ pipiclaw
163
163
  2. 填入搜索 provider 的 `apiKey`(默认示例为 Brave)
164
164
  3. 如需代理,设置 `tools.web.proxy`(未设置时回退到标准的 `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` / `NO_PROXY`)
165
165
 
166
- 搜索后端支持 `duckduckgo`、`brave`、`tavily`、`jina`、`searxng`,完整字段见[配置手册](./docs/configuration.md)。
166
+ 搜索后端支持 `duckduckgo`、`brave`、`tavily`、`jina`、`searxng`,完整字段见[配置速查](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md)和[字段参考](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration-reference.md)。
167
167
 
168
168
  ### 10. 在钉钉中验证(Verify in DingTalk)
169
169
 
@@ -175,7 +175,7 @@ pipiclaw
175
175
 
176
176
  如果一切正常,配置了 AI Card 时你会看到过程更新,否则机器人直接发普通消息回复;Pipiclaw 会在本地创建对应的会话通道目录,后续会话复用该通道的工作区与记忆。
177
177
 
178
- **第一次没跑通?** 最常见的三类原因:`channel.json` 残留 `your-*` 占位值(进程启动即退出);模型凭据或 `models.json` 配置不可用(能收消息但首次调用失败);`allowFrom` 挡住了你的账号或 Stream Mode 未开启(收到消息但不回复)。系统化排查见[部署与运维指南](./docs/deployment-and-operations.md);设置 `PIPICLAW_DEBUG=1` 可在会话通道目录写出 `last_prompt.json` 检查精确提示词。
178
+ **第一次没跑通?** 最常见的三类原因:`channel.json` 残留 `your-*` 占位值(进程启动即退出);模型凭据或 `models.json` 配置不可用(能收消息但首次调用失败);`allowFrom` 挡住了你的账号或 Stream Mode 未开启(收到消息但不回复)。系统化排查见[部署与运维指南](https://github.com/oyasmi/pipiclaw/blob/main/docs/deployment-and-operations.md);设置 `PIPICLAW_DEBUG=1` 可在会话通道目录写出 `last_prompt.json` 检查精确提示词。
179
179
 
180
180
  ### 让 AI Agent 帮你完成安装(For AI Agent)
181
181
 
@@ -215,41 +215,44 @@ pipiclaw
215
215
  | `/steer <message>` | 当前任务继续执行时追加引导信息 |
216
216
  | `/followup <message>` | 排队新请求,等当前任务结束后执行 |
217
217
  | `/events list\|show\|delete\|history` | 查看与管理 `workspace/events/` 中的定时事件 |
218
- | `/tasks [show\|archive\|approve\|pause\|resume\|run\|stats\|doctor]` | 查看与治理任务台账,`approve` 是外部副作用的唯一授权入口 |
218
+ | `/tasks [show\|archive\|approve\|pause\|resume\|run\|set\|stats\|doctor]` | 查看与治理任务台账,`approve` 是外部副作用的唯一授权入口,`set` 可零 LLM 成本直改 wake/next/priority/attempts/deadline |
219
219
  | `/status` | 运行时状态:执行状态、当前模型、上下文用量、运行时长、版本 |
220
220
  | `/usage [7d\|month]` | 本通道与全局的 LLM 成本,按类型和 Top 模型拆分 |
221
221
  | `/context [detail]` | 当前发给模型的上下文构成:system prompt 各 section 体量与 fingerprint、工具 schema 开销、上一轮动态上下文 |
222
222
  | `/new` | 开启新会话 |
223
223
  | `/compact [instructions]` | 手动压缩当前会话上下文 |
224
+ | `/memory [status\|list\|show\|pending]` | 查看当前频道的活动记忆、metadata、墓碑和待处理建议 |
224
225
  | `/session` | 当前会话状态、消息统计、token 使用量 |
225
226
  | `/model [引用]` | 查看或切换模型 |
226
227
  | `/thinking [level\|cycle]` | 查看、设置或轮换当前会话的 thinking level(默认 `medium`,按模型能力自动 clamp) |
227
228
 
228
229
  说明:
229
230
 
230
- - 前九条由传输层直接处理,**忙碌时也可用**(`/context` 是只读统计,零 LLM 成本);后五条会话命令仅空闲时可用(忙碌时会收到提示)。
231
+ - 前九条由传输层直接处理,**忙碌时也可用**(`/context` 是只读统计,零 LLM 成本);后六条会话命令仅空闲时可用(忙碌时会收到提示)。
231
232
  - 忙碌时的普通消息默认等价于 `/steer`,可通过 `channel.json` 的 `busyMessageDefault` 改为排队(`followUp`)。
232
233
  - 未知的斜杠命令会被直接拒绝并提示 `/help`,不会作为普通消息发给模型(避免 `/modle` 这类笔误变成一整轮 LLM 调用)。workspace skill 也可作为命令调用(`/skill:<名称>`)。
233
234
  - `/model` 依次尝试精确 `provider/modelId`、精确 `modelId`、对完整引用的子串匹配,只有唯一命中时才切换,例如 `/model turbo`。
234
235
 
235
- 事件与任务的详细用法见 [docs/events-and-tasks.md](./docs/events-and-tasks.md);子代理见 [docs/sub-agents.md](./docs/sub-agents.md)。
236
+ 事件与任务的详细用法见 [docs/events-and-tasks.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/events-and-tasks.md);子代理见 [docs/sub-agents.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/sub-agents.md)。
236
237
 
237
238
  ## 文档地图(Documentation)
238
239
 
239
- 完整索引见 **[docs/README.md](./docs/README.md)**(按使用者 / 管理员 / 开发者分组)。常用入口:
240
+ 完整索引见 **[docs/README.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/README.md)**(按使用者 / 管理员 / 开发者分组)。常用入口:
240
241
 
241
242
  | 文档 | 内容 |
242
243
  |------|------|
243
- | [docs/tools.md](./docs/tools.md) | 工具总览:每个能力做什么、开关在哪、子代理是否可用 |
244
- | [docs/memory.md](./docs/memory.md) | 记忆分层:它记得什么、怎么让它记住或忘掉 |
245
- | [docs/configuration.md](./docs/configuration.md) | 全部配置项:钉钉、模型、settings、tools、TUI、记忆与工作区文件 |
246
- | [docs/events-and-tasks.md](./docs/events-and-tasks.md) | 定时事件(含 `preAction` 门控、`event_manage`)、任务台账、内建 task driver、`/tasks` 控制面与 `task_manage` 工具 |
247
- | [docs/sub-agents.md](./docs/sub-agents.md) | 工作区配置子代理:委派与独立验收 |
248
- | [docs/security.md](./docs/security.md) | 默认安全策略、`security.json` 配置与已知边界 |
249
- | [docs/deployment-and-operations.md](./docs/deployment-and-operations.md) | 长期运行、日志、可观测性、升级、备份与排障 |
250
- | [docs/scaling-and-concurrency.md](./docs/scaling-and-concurrency.md) | 并发模型与容量边界 |
251
- | [docs/architecture.md](./docs/architecture.md) | as-implemented 架构:运行时拓扑、消息生命周期、并发表、磁盘布局 |
252
- | [docs/runtime-playbooks.md](./docs/runtime-playbooks.md) | Runtime playbooks 与知识分层模型 |
244
+ | [docs/tools.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/tools.md) | 工具总览:每个能力做什么、开关在哪、子代理是否可用 |
245
+ | [docs/memory.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/memory.md) | 记忆分层:它记得什么、怎么让它记住或忘掉 |
246
+ | [docs/configuration.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md) | 配置速查:现在该改哪个文件 |
247
+ | [docs/configuration-reference.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration-reference.md) | 字段参考:钉钉、模型、settings、tools、TUI、记忆与工作区文件 |
248
+ | [docs/runtime-mechanisms.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/runtime-mechanisms.md) | 机制说明:fallback、记忆维护、事件、后台作业、任务 driver |
249
+ | [docs/events-and-tasks.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/events-and-tasks.md) | 定时事件(含 `preAction` 门控、`event_manage`)、任务台账、内建 task driver、`/tasks` 控制面与 `task_manage` 工具 |
250
+ | [docs/sub-agents.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/sub-agents.md) | 工作区配置子代理:委派与独立验收 |
251
+ | [docs/security.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/security.md) | 默认安全策略、`security.json` 配置与已知边界 |
252
+ | [docs/deployment-and-operations.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/deployment-and-operations.md) | 长期运行、日志、可观测性、升级、备份与排障 |
253
+ | [docs/scaling-and-concurrency.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/scaling-and-concurrency.md) | 并发模型与容量边界 |
254
+ | [docs/architecture.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/architecture.md) | as-implemented 架构:运行时拓扑、消息生命周期、并发表、磁盘布局 |
255
+ | [docs/runtime-playbooks.md](https://github.com/oyasmi/pipiclaw/blob/main/docs/runtime-playbooks.md) | Runtime playbooks 与知识分层模型 |
253
256
 
254
257
  ## 开发(Development)
255
258
 
@@ -1,6 +1,6 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
2
  import { clampThinkingLevel } from "@earendil-works/pi-ai/compat";
3
- import { AgentSession, AgentSessionRuntime, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SessionManager, } from "@earendil-works/pi-coding-agent";
3
+ import { AgentSession, AgentSessionRuntime, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SettingsManager as SDKSettingsManager, SessionManager, } from "@earendil-works/pi-coding-agent";
4
4
  import { mkdir, readFile, writeFile } from "fs/promises";
5
5
  import { dirname, join, resolve } from "path";
6
6
  import { createExecutor } from "../executor.js";
@@ -18,7 +18,8 @@ import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatM
18
18
  import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
19
19
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
20
20
  import { PipiclawSettingsManager } from "../settings.js";
21
- import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
21
+ import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
22
+ import { formatLocalTime, localStampForFilename } from "../shared/local-time.js";
22
23
  import { countPromptUnits } from "../shared/prompt-units.js";
23
24
  import { errorMessage } from "../shared/text-utils.js";
24
25
  import { isRecord } from "../shared/type-guards.js";
@@ -51,7 +52,17 @@ function getFinalOutcomeText(outcome) {
51
52
  return isFinalOutcome(outcome) ? outcome.text : null;
52
53
  }
53
54
  function asSdkSettingsManager(manager) {
54
- return manager;
55
+ // The upstream session needs its broad interactive SettingsManager surface, while
56
+ // Pipiclaw deliberately owns a small runtime-specific settings contract. Build a
57
+ // real upstream manager from that contract instead of making PipiclawSettingsManager
58
+ // pretend to implement dozens of unrelated no-op UI preferences.
59
+ return SDKSettingsManager.inMemory({
60
+ defaultProvider: manager.getDefaultProvider(),
61
+ defaultModel: manager.getDefaultModel(),
62
+ defaultThinkingLevel: manager.getDefaultThinkingLevel(),
63
+ compaction: manager.getCompactionSettings(),
64
+ retry: manager.getRetrySettings(),
65
+ });
55
66
  }
56
67
  const DEFAULT_MAIN_THINKING_LEVEL = "medium";
57
68
  export class ChannelRunner {
@@ -639,7 +650,7 @@ export class ChannelRunner {
639
650
  try {
640
651
  const dir = join(this.channelDir, "inbox");
641
652
  await mkdir(dir, { recursive: true });
642
- const path = join(dir, `message-${new Date().toISOString().replace(/[:.]/g, "-")}.txt`);
653
+ const path = join(dir, `message-${localStampForFilename()}.txt`);
643
654
  await writeFile(path, text.replace(/\r/g, ""), { mode: 0o600 });
644
655
  return path;
645
656
  }
@@ -649,13 +660,7 @@ export class ChannelRunner {
649
660
  }
650
661
  }
651
662
  formatUserMessage(text, userName, now = new Date()) {
652
- const pad = (n) => n.toString().padStart(2, "0");
653
- const offset = -now.getTimezoneOffset();
654
- const offsetSign = offset >= 0 ? "+" : "-";
655
- const offsetHours = pad(Math.floor(Math.abs(offset) / 60));
656
- const offsetMins = pad(Math.abs(offset) % 60);
657
- const timestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}${offsetSign}${offsetHours}:${offsetMins}`;
658
- return `[${timestamp}] [${userName || "unknown"}]: ${text}`;
663
+ return `[${formatLocalTime(now)}] [${userName || "unknown"}]: ${text}`;
659
664
  }
660
665
  /**
661
666
  * Single source of truth for the busy-message window: steer is accepted while
@@ -67,6 +67,7 @@ export declare class ChannelJobManager {
67
67
  private readonly executor;
68
68
  private readonly jobs;
69
69
  private sweepTimer?;
70
+ private garbageCollectionTimer?;
70
71
  private sweeping;
71
72
  private readonly options;
72
73
  private readonly sweepIntervalMs;
@@ -80,6 +81,12 @@ export declare class ChannelJobManager {
80
81
  * Called from the sweeper and from restore, so leftovers never outlive a daemon restart.
81
82
  */
82
83
  private collectGarbage;
84
+ /**
85
+ * Arrange the next terminal-record cleanup independently of future job activity. A repeating
86
+ * sweeper is necessary while processes are running; after that, one unref'ed timeout is enough
87
+ * to enforce the retention promise without keeping an idle channel awake every few seconds.
88
+ */
89
+ private scheduleGarbageCollection;
83
90
  get channel(): string;
84
91
  runningCount(): number;
85
92
  /** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
@@ -1,5 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { chmod, mkdir, readdir, readFile, unlink } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
3
4
  import { join } from "node:path";
4
5
  import * as log from "../log.js";
5
6
  import { writeFileAtomically } from "../shared/atomic-file.js";
@@ -28,7 +29,7 @@ export const FINISHED_JOB_RETENTION_MS = 24 * 60 * 60_000;
28
29
  /** Bytes of captured output carried inline in the completion wake. */
29
30
  const WAKE_OUTPUT_TAIL_BYTES = 2_000;
30
31
  function jobSpillPath(id) {
31
- return `/tmp/pipiclaw-job-${id}.log`;
32
+ return join(tmpdir(), `pipiclaw-job-${id}.log`);
32
33
  }
33
34
  function isTerminal(status) {
34
35
  return status !== "running";
@@ -113,6 +114,30 @@ export class ChannelJobManager {
113
114
  }
114
115
  }
115
116
  }
117
+ /**
118
+ * Arrange the next terminal-record cleanup independently of future job activity. A repeating
119
+ * sweeper is necessary while processes are running; after that, one unref'ed timeout is enough
120
+ * to enforce the retention promise without keeping an idle channel awake every few seconds.
121
+ */
122
+ scheduleGarbageCollection() {
123
+ if (this.garbageCollectionTimer) {
124
+ clearTimeout(this.garbageCollectionTimer);
125
+ this.garbageCollectionTimer = undefined;
126
+ }
127
+ const now = Date.now();
128
+ const nextExpiry = Array.from(this.jobs.values())
129
+ .filter((record) => isTerminal(record.status) && record.finishedAt)
130
+ .map((record) => record.finishedAt + FINISHED_JOB_RETENTION_MS)
131
+ .reduce((earliest, expiry) => (earliest === undefined ? expiry : Math.min(earliest, expiry)), undefined);
132
+ if (nextExpiry === undefined) {
133
+ return;
134
+ }
135
+ this.garbageCollectionTimer = setTimeout(() => {
136
+ this.garbageCollectionTimer = undefined;
137
+ void this.collectGarbage().finally(() => this.scheduleGarbageCollection());
138
+ }, Math.max(0, nextExpiry - now));
139
+ this.garbageCollectionTimer.unref?.();
140
+ }
116
141
  get channel() {
117
142
  return this.channelId;
118
143
  }
@@ -296,6 +321,7 @@ export class ChannelJobManager {
296
321
  }
297
322
  await this.persist(record);
298
323
  await this.announce(record, signal);
324
+ this.scheduleGarbageCollection();
299
325
  }
300
326
  /**
301
327
  * Wake the channel for a finished job. `notified` is persisted before anything else can run
@@ -440,6 +466,7 @@ export class ChannelJobManager {
440
466
  });
441
467
  }
442
468
  await this.collectGarbage();
469
+ this.scheduleGarbageCollection();
443
470
  this.ensureSweeper();
444
471
  return restored;
445
472
  }
@@ -1,4 +1,5 @@
1
1
  import * as log from "../log.js";
2
+ import { formatLocalTime } from "../shared/local-time.js";
2
3
  import { extractLabelFromArgs, truncate } from "../shared/text-utils.js";
3
4
  import { isRecord } from "../shared/type-guards.js";
4
5
  import { toolResultDetails } from "../tools/tool-details.js";
@@ -106,7 +107,7 @@ export async function handleSessionEvent(event, context) {
106
107
  cost: { ...subAgentDetails.usage.cost },
107
108
  });
108
109
  queue.enqueue(() => store?.logSubAgentRun(logCtx.channelId, {
109
- date: new Date().toISOString(),
110
+ date: formatLocalTime(),
110
111
  toolCallId: event.toolCallId,
111
112
  label,
112
113
  agent: subAgentDetails.agent,
package/dist/log.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { styleText } from "node:util";
2
2
  import { RUNTIME_LOG_PATH } from "./paths.js";
3
3
  import { createJsonlAppender } from "./shared/jsonl-appender.js";
4
+ import { formatLocalTime } from "./shared/local-time.js";
4
5
  const LEVEL_ORDER = { debug: 0, info: 1, warn: 2, error: 3 };
5
6
  const MAX_VALUE_LENGTH = 240;
6
7
  const MAX_COLLECTION_ITEMS = 10;
@@ -96,20 +97,6 @@ function sanitizeFields(fields) {
96
97
  }
97
98
  return result;
98
99
  }
99
- function formatTimestamp(date = new Date()) {
100
- const offsetMinutes = -date.getTimezoneOffset();
101
- const sign = offsetMinutes >= 0 ? "+" : "-";
102
- const offsetHours = String(Math.floor(Math.abs(offsetMinutes) / 60)).padStart(2, "0");
103
- const offsetRemainder = String(Math.abs(offsetMinutes) % 60).padStart(2, "0");
104
- const year = date.getFullYear();
105
- const month = String(date.getMonth() + 1).padStart(2, "0");
106
- const day = String(date.getDate()).padStart(2, "0");
107
- const hours = String(date.getHours()).padStart(2, "0");
108
- const minutes = String(date.getMinutes()).padStart(2, "0");
109
- const seconds = String(date.getSeconds()).padStart(2, "0");
110
- const milliseconds = String(date.getMilliseconds()).padStart(3, "0");
111
- return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}${sign}${offsetHours}:${offsetRemainder}`;
112
- }
113
100
  function renderField(value) {
114
101
  if (typeof value === "string")
115
102
  return JSON.stringify(value);
@@ -131,7 +118,7 @@ function formatConsoleLine(level, event, message, options) {
131
118
  .sort(([left], [right]) => left.localeCompare(right))
132
119
  .map(([key, value]) => `${key}=${renderField(value)}`)
133
120
  .join(" ");
134
- return `${formatTimestamp()} ${level.toUpperCase().padEnd(5)} ${event} ${summarizeString(message)}${suffix ? ` ${suffix}` : ""}`;
121
+ return `${formatLocalTime()} ${level.toUpperCase().padEnd(5)} ${event} ${summarizeString(message)}${suffix ? ` ${suffix}` : ""}`;
135
122
  }
136
123
  function colorFor(level) {
137
124
  if (level === "debug")
@@ -153,7 +140,7 @@ function emit(level, event, message, options) {
153
140
  const fields = sanitizeFields(options.fields);
154
141
  const details = options.details ? summarizeString(options.details) : undefined;
155
142
  fileSink.tryAppend({
156
- ts: new Date().toISOString(),
143
+ ts: formatLocalTime(),
157
144
  level,
158
145
  event,
159
146
  message: summarizeString(message),
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readOptionalTextFile } from "../shared/fs-utils.js";
3
+ import { localDayKey } from "../shared/local-time.js";
3
4
  import { clipText } from "../shared/text-utils.js";
4
5
  import { getChannelMemoryPath, parseChannelMemoryEntries, readChannelMemory } from "./files.js";
5
6
  import { syncMemoryMetadata } from "./metadata.js";
@@ -41,8 +42,8 @@ export async function handleMemoryCommand(options) {
41
42
  const records = Object.values(metadata.entries);
42
43
  const active = records.filter((entry) => entry.status === "active");
43
44
  const since = new Date();
44
- since.setUTCDate(since.getUTCDate() - 29);
45
- const sinceDay = since.toISOString().slice(0, 10);
45
+ since.setDate(since.getDate() - 29);
46
+ const sinceDay = localDayKey(since);
46
47
  const recalls30d = active.reduce((sum, entry) => sum +
47
48
  Object.entries(entry.recallByDay ?? {}).reduce((entrySum, [day, count]) => entrySum + (day >= sinceDay ? count : 0), 0), 0);
48
49
  const lastFailure = (await readOptionalTextFile(getMemoryReviewLogPath(options.channelDir)))
@@ -1,8 +1,10 @@
1
1
  import { getLatestCompactionEntry } from "@earendil-works/pi-coding-agent";
2
+ import { formatLocalTime } from "../shared/local-time.js";
2
3
  import { splitH2Sections } from "../shared/markdown-sections.js";
3
4
  import { runMemoryExtraction, toMemoryOp } from "./extraction.js";
4
5
  import { appendChannelHistoryArchive, appendChannelHistoryBlock, applyChannelMemoryOps, parseChannelMemoryEntries, rewriteChannelHistory, rewriteChannelMemory, } from "./files.js";
5
6
  import { DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE, shouldAutoWriteMemory, } from "./promotion.js";
7
+ import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
6
8
  import { runSidecarTask } from "./sidecar-worker.js";
7
9
  import { sanitizeMessagesForMemory } from "./transcript.js";
8
10
  const INLINE_TRANSCRIPT_MAX_CHARS = 28_000;
@@ -19,6 +21,7 @@ const MEMORY_CLEANUP_SYSTEM_PROMPT = `You are rewriting a Pipiclaw channel MEMOR
19
21
  Return Markdown only. Do not use code fences.
20
22
 
21
23
  Goals:
24
+ ${MEMORY_INPUT_SAFETY_RULES}
22
25
  - Keep only durable and useful channel memory.
23
26
  - Remove outdated entries, duplicates, verbose phrasing, transient working state, temporary debugging observations, and completed worklog.
24
27
  - Organize the result with stable sections where relevant.
@@ -43,6 +46,7 @@ const HISTORY_FOLDING_SYSTEM_PROMPT = `You are folding older HISTORY.md blocks f
43
46
  Return Markdown only. Do not use code fences.
44
47
 
45
48
  Goals:
49
+ ${MEMORY_INPUT_SAFETY_RULES}
46
50
  - Compress older history blocks into one concise summary block.
47
51
  - Keep important decisions, milestones, and unresolved outcomes.
48
52
  - Remove redundancy and transcript-like detail.
@@ -145,7 +149,7 @@ export async function runInlineConsolidation(options) {
145
149
  includeHistoryBlock: mode === "boundary",
146
150
  usageContext: usageContextFor(options.channelId, correlationId),
147
151
  });
148
- const timestamp = new Date().toISOString();
152
+ const timestamp = formatLocalTime();
149
153
  // The same bar the growth review applies. Consolidation used to write whatever the model
150
154
  // returned, which is how transient state reached durable memory: the strictest reviewer
151
155
  // was gated behind a keyword scan while the ungated paths wrote freely. Rejected material
@@ -242,13 +246,13 @@ export async function foldChannelHistory(options, currentHistory) {
242
246
  // Preserve the raw blocks before folding turns them lossy, so nothing is
243
247
  // permanently blurred by repeated folds.
244
248
  await appendChannelHistoryArchive(options.channelDir, {
245
- timestamp: new Date().toISOString(),
249
+ timestamp: formatLocalTime(),
246
250
  content: renderedOlder,
247
251
  });
248
252
  const prompt = `Older history blocks to fold:
249
253
  ${renderedOlder}`;
250
254
  const foldedSummary = await runWorkerPrompt("history-folding", options.model, options.resolveApiKey, HISTORY_FOLDING_SYSTEM_PROMPT, prompt, HISTORY_FOLDING_TIMEOUT_MS, usageContextFor(options.channelId, options.usageCorrelationId));
251
- const foldedHeading = `## Folded History Through ${olderSections[olderSections.length - 1]?.heading ?? new Date().toISOString()}`;
255
+ const foldedHeading = `## Folded History Through ${olderSections[olderSections.length - 1]?.heading ?? formatLocalTime()}`;
252
256
  const rebuiltHistory = [
253
257
  "# Channel History",
254
258
  "",
@@ -3,6 +3,7 @@ import { parseJsonObject } from "../shared/llm-json.js";
3
3
  import { clipText } from "../shared/text-utils.js";
4
4
  import { isRecord } from "../shared/type-guards.js";
5
5
  import { parseChannelMemoryEntries, readChannelHistory, readChannelMemory, readChannelSession, } from "./files.js";
6
+ import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
6
7
  import { runRetriedSidecarTask } from "./sidecar-worker.js";
7
8
  import { sanitizeMessagesForMemory } from "./transcript.js";
8
9
  /**
@@ -49,6 +50,7 @@ export function buildMemoryExtractionSystemPrompt(options) {
49
50
  "}",
50
51
  "",
51
52
  "Rules:",
53
+ MEMORY_INPUT_SAFETY_RULES,
52
54
  MEMORY_OPS_RULES,
53
55
  ...(options.includeHistoryBlock ? [HISTORY_BLOCK_RULES] : []),
54
56
  ].join("\n");
@@ -42,6 +42,7 @@ export interface ApplyMemoryOpsResult {
42
42
  forgotten: number;
43
43
  blockedByPolicy: number;
44
44
  blockedByTombstone: number;
45
+ skippedDuplicate: number;
45
46
  }
46
47
  /**
47
48
  * Apply add/supersede/invalidate ops to a channel MEMORY.md with line-level edits,
@@ -49,10 +50,6 @@ export interface ApplyMemoryOpsResult {
49
50
  * missing invalidate targets are skipped. Mutating edits are backed up first.
50
51
  */
51
52
  export declare function applyChannelMemoryOps(channelDir: string, ops: MemoryOp[], timestamp?: string): Promise<ApplyMemoryOpsResult>;
52
- export interface MemoryUpdateBlock {
53
- timestamp: string;
54
- entries: string[];
55
- }
56
53
  export interface HistoryBlock {
57
54
  timestamp: string;
58
55
  content: string;
@@ -68,7 +65,6 @@ export declare function readChannelSession(channelDir: string): Promise<string>;
68
65
  export declare function rewriteChannelMemory(channelDir: string, content: string): Promise<void>;
69
66
  export declare function rewriteChannelHistory(channelDir: string, content: string): Promise<void>;
70
67
  export declare function rewriteChannelSession(channelDir: string, content: string): Promise<void>;
71
- export declare function appendChannelMemoryUpdate(channelDir: string, block: MemoryUpdateBlock): Promise<void>;
72
68
  export declare function getChannelHistoryArchivePath(channelDir: string): string;
73
69
  /** Append raw history blocks to a never-rewritten archive before lossy folding. */
74
70
  export declare function appendChannelHistoryArchive(channelDir: string, block: HistoryBlock): Promise<void>;
@@ -4,8 +4,9 @@ import { copyFile, readdir, rm } from "fs/promises";
4
4
  import { basename, join } from "path";
5
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
6
6
  import { readOptionalTextFile } from "../shared/fs-utils.js";
7
+ import { formatLocalTime, localStampForFilename } from "../shared/local-time.js";
7
8
  import { syncMemoryMetadata } from "./metadata.js";
8
- import { containsSecret, REDACTED_SECRET } from "./policy.js";
9
+ import { containsSecret, REDACTED_SECRET } from "./secret-redaction.js";
9
10
  import { appendMemoryTombstone, hashMemoryContent, readMemoryTombstones } from "./tombstones.js";
10
11
  const DEFAULT_CHANNEL_MEMORY = `# Channel Memory
11
12
 
@@ -129,7 +130,7 @@ export function parseChannelMemoryEntries(content) {
129
130
  * preserving any surrounding markdown. Missing supersede targets downgrade to add;
130
131
  * missing invalidate targets are skipped. Mutating edits are backed up first.
131
132
  */
132
- export async function applyChannelMemoryOps(channelDir, ops, timestamp = new Date().toISOString()) {
133
+ export async function applyChannelMemoryOps(channelDir, ops, timestamp = formatLocalTime()) {
133
134
  const result = {
134
135
  added: 0,
135
136
  superseded: 0,
@@ -139,6 +140,7 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = new Dat
139
140
  forgotten: 0,
140
141
  blockedByPolicy: 0,
141
142
  blockedByTombstone: 0,
143
+ skippedDuplicate: 0,
142
144
  };
143
145
  if (ops.length === 0) {
144
146
  return result;
@@ -151,16 +153,22 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = new Dat
151
153
  const byId = new Map(existingEntries.map((entry) => [entry.id, entry]));
152
154
  // Reconcile legacy entries before applying removals so terminal status retains
153
155
  // the entry's provenance even when no sidecar record existed yet.
154
- await syncMemoryMetadata(channelDir, existingEntries, [], timestamp);
156
+ const currentMetadata = await syncMemoryMetadata(channelDir, existingEntries, [], timestamp);
155
157
  const tombstones = await readMemoryTombstones(channelDir);
156
158
  const tombstoneHashes = new Set(tombstones.map((tombstone) => tombstone.contentHash));
157
159
  const tombstoneSourceIds = new Set(tombstones.flatMap((tombstone) => tombstone.sourceEntryIds ?? []));
160
+ const activeContentHashes = new Set(existingEntries.map((entry) => hashMemoryContent(entry.content)));
161
+ const appliedSourceCorrelationIds = new Set(Object.values(currentMetadata.entries).flatMap((entry) => entry.sourceCorrelationIds));
158
162
  const removals = new Set();
159
163
  const replacements = new Map();
160
164
  const additions = [];
161
165
  const metadataUpdates = [];
162
166
  for (const op of ops) {
163
167
  if (op.op === "add" || op.op === "supersede") {
168
+ if (op.metadata?.sourceCorrelationId && appliedSourceCorrelationIds.has(op.metadata.sourceCorrelationId)) {
169
+ result.skippedDuplicate++;
170
+ continue;
171
+ }
164
172
  if (containsSecret(op.content) || op.content.includes(REDACTED_SECRET)) {
165
173
  result.blockedByPolicy++;
166
174
  continue;
@@ -173,8 +181,14 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = new Dat
173
181
  }
174
182
  if (op.op === "add") {
175
183
  if (op.content.trim()) {
184
+ const contentHash = hashMemoryContent(op.content);
185
+ if (activeContentHashes.has(contentHash)) {
186
+ result.skippedDuplicate++;
187
+ continue;
188
+ }
176
189
  const id = generateMemoryEntryId();
177
190
  additions.push({ content: op.content.trim(), id });
191
+ activeContentHashes.add(contentHash);
178
192
  metadataUpdates.push({ id, status: "active", metadata: op.metadata, sourceEntryIds: op.sourceEntryIds });
179
193
  result.added++;
180
194
  }
@@ -185,16 +199,20 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = new Dat
185
199
  if (target) {
186
200
  removals.add(target.lineIndex);
187
201
  if (op.op === "forget") {
202
+ const sourceEntryIds = Array.from(new Set([
203
+ ...(currentMetadata.entries[target.id]?.sourceEntryIds ?? []),
204
+ ...(op.sourceEntryIds ?? []),
205
+ ]));
188
206
  await appendMemoryTombstone(channelDir, {
189
207
  entryId: target.id,
190
208
  contentHash: hashMemoryContent(target.content),
191
209
  deletedAt: timestamp,
192
210
  scope: "channel",
193
211
  reason: op.reason?.trim() || "user forget",
194
- sourceEntryIds: op.sourceEntryIds,
212
+ sourceEntryIds,
195
213
  });
196
214
  result.forgotten++;
197
- metadataUpdates.push({ id: target.id, status: "forgotten", sourceEntryIds: op.sourceEntryIds });
215
+ metadataUpdates.push({ id: target.id, status: "forgotten", sourceEntryIds });
198
216
  }
199
217
  else {
200
218
  result.invalidated++;
@@ -224,8 +242,14 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = new Dat
224
242
  result.superseded++;
225
243
  }
226
244
  else {
245
+ const contentHash = hashMemoryContent(op.content);
246
+ if (activeContentHashes.has(contentHash)) {
247
+ result.skippedDuplicate++;
248
+ continue;
249
+ }
227
250
  const id = generateMemoryEntryId();
228
251
  additions.push({ content: op.content.trim(), id });
252
+ activeContentHashes.add(contentHash);
229
253
  metadataUpdates.push({ id, status: "active", metadata: op.metadata, sourceEntryIds: op.sourceEntryIds });
230
254
  result.downgradedToAdd++;
231
255
  result.missingTarget++;
@@ -261,7 +285,7 @@ async function backupBeforeRewrite(channelDir, sourcePath) {
261
285
  }
262
286
  const backupDir = join(channelDir, MEMORY_BACKUP_DIR);
263
287
  mkdirSync(backupDir, { recursive: true });
264
- const stamp = new Date().toISOString().replace(/[:.]/g, "-");
288
+ const stamp = localStampForFilename();
265
289
  const name = basename(sourcePath, ".md");
266
290
  await copyFile(sourcePath, join(backupDir, `${name}-${stamp}.md`));
267
291
  const files = (await readdir(backupDir))
@@ -336,21 +360,6 @@ export async function rewriteChannelSession(channelDir, content) {
336
360
  const nextContent = normalizeContent(content) || DEFAULT_CHANNEL_SESSION;
337
361
  await writeFileAtomically(getChannelSessionPath(channelDir), nextContent);
338
362
  }
339
- export async function appendChannelMemoryUpdate(channelDir, block) {
340
- if (block.entries.length === 0) {
341
- return;
342
- }
343
- await ensureChannelMemoryFiles(channelDir);
344
- const path = getChannelMemoryPath(channelDir);
345
- const existing = await readOptionalTextFile(path);
346
- const renderedBlock = [
347
- `## Update ${block.timestamp}`,
348
- ...block.entries.map((entry) => renderMemoryEntryLine(entry, generateMemoryEntryId())),
349
- ].join("\n");
350
- const nextContent = `${ensureTrailingNewlines(existing)}${renderedBlock}\n`;
351
- await writeFileAtomically(path, nextContent);
352
- await syncMemoryMetadata(channelDir, parseChannelMemoryEntries(nextContent), [], block.timestamp);
353
- }
354
363
  export function getChannelHistoryArchivePath(channelDir) {
355
364
  return join(channelDir, "HISTORY.archive.md");
356
365
  }
@@ -1,4 +1,5 @@
1
1
  import * as log from "../log.js";
2
+ import { formatLocalTime } from "../shared/local-time.js";
2
3
  import { errorMessage } from "../shared/text-utils.js";
3
4
  import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
4
5
  import { runInlineConsolidation, } from "./consolidation.js";
@@ -143,7 +144,7 @@ export class MemoryLifecycle {
143
144
  async appendReviewLog(entry) {
144
145
  try {
145
146
  await appendMemoryReviewLog(this.options.channelDir, {
146
- timestamp: new Date().toISOString(),
147
+ timestamp: formatLocalTime(),
147
148
  channelId: this.options.channelId,
148
149
  ...entry,
149
150
  });
@@ -222,7 +223,7 @@ export class MemoryLifecycle {
222
223
  await updateMemoryMaintenanceState(this.options.appHomeDir, this.options.channelId, (current) => ({
223
224
  ...current,
224
225
  lastCheckpointEntryId: sourceWindow.throughEntryId,
225
- lastCheckpointAt: new Date().toISOString(),
226
+ lastCheckpointAt: formatLocalTime(),
226
227
  failureBackoffUntil: null,
227
228
  }));
228
229
  }
@@ -281,7 +282,7 @@ export class MemoryLifecycle {
281
282
  const event = {
282
283
  kind,
283
284
  channelId: this.options.channelId,
284
- timestamp: now.toISOString(),
285
+ timestamp: formatLocalTime(now),
285
286
  latestSessionEntryId,
286
287
  };
287
288
  try {
@@ -1,3 +1,4 @@
1
+ import { parseLocalTime } from "../shared/local-time.js";
1
2
  function deny(jobKind, skipReason) {
2
3
  return { allowed: false, jobKind, skipReason };
3
4
  }
@@ -8,8 +9,8 @@ function parseTime(value) {
8
9
  if (!value) {
9
10
  return null;
10
11
  }
11
- const time = Date.parse(value);
12
- return Number.isFinite(time) ? time : null;
12
+ const time = parseLocalTime(value);
13
+ return time === undefined ? null : time;
13
14
  }
14
15
  function isBeforeOptional(now, value) {
15
16
  const time = parseTime(value ?? undefined);