diff --git a/SECURITY.md b/SECURITY.md index e1afda23..5fc81a13 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -153,7 +153,7 @@ The token is a lock on the **write** surface, not a wall around the whole API. - **The real boundary is loopback + the DSH host listener.** The host-side routes (`/api/dsh-mneme/*`) are mounted on the DSH port, which binds `127.0.0.1`. Every one of them asks the host for a verdict before doing anything else — `ctx.connection.requestRejection(req)` — so the host's own fence against DNS rebinding and cross-site browser requests applies to this plugin's routes too: a page open in your browser cannot call them, and gets `403` (fence) or `401` (not signed in to the host) instead of memory data. That fence is not identity: any process already running locally, and any page in the host's own origin, is inside the perimeter. When the host provides no `connection` service (headless, an older host, tests), the check is skipped and behaviour falls back to what it was before this gate existed — a missing host service must not 401 the panel. - **Authentication is opt-in and fail-open.** `apiToken` defaults to empty; while it is empty, `isAuthorized()` returns true for every request — reads *and* writes. Setting a token gates the write routes and the sensitive reads; it does not gate plain reads. -- **Open reads (no token even when one is configured)**: `GET /`, `/info`, `/version-check`, `/list`, `/recall-stats`, `/search`, `/semantic`, `/semantic/llm-audit`, `/semantic/llm-audit/stats`, `/semantic/consolidation-stats`, `/semantic/graph/*`, `/entities`, `/memories/entities`, `/dream-status`, `/inject-status`, `/inject-preview`, `/pipeline`, `/candidates`, `/diary`, `/diary/entry`, `/diary/library`, `/diary/library/entry`, `/llm-providers`, `/config-keys`, plus the `GET`/`HEAD` branches of `/profile`, `/rules`, `/persona`, `/persona/session`, `/profile-facts`, `/profile-digest`, `/mode`, `/features`, `/commands`, `/nudge`, `/diary/compose`, `/diary/export`, of the two share-receive routes `/receive` and `/receive/undo`, of `/profile-facts/apply`, of the six chorography read routes `/choro/repos`, `/choro/modules`, `/choro/page`, `/choro/search`, `/choro/claims`, `/choro/run` (M1/finale: they read repo-local wiki pages and `choro_*` index tables — not memory rows; with `chorographyEnabled` off they uniformly answer `409 disabled`, the #497 mount-anyway-gate-in-logic pattern), of the two T1 job routes `/choro/t1` and `/choro/t1/status` (same `token-write` shape as `/choro/run`: the only token-exempt branch is a `405`, and the POST itself answers `409 disabled` unless both `chorographyEnabled` and `chorographyT1FromPanel` are on), and of the three `token-write` knowledge-base routes `/kb/collections`, `/kb/ingest` and `/kb/search` (again only a `405` is genuinely open on them, because `needsToken()` exempts `GET`/`HEAD` under `token-write`; the two plain-`token` reads under `/kb/*` stay gated even on `GET`). `/choro/run` is the same shape as `/receive`: a `token-write` route whose GET branch is token-exempt, so the only genuinely open thing on that path is a `405` — the POST write itself stays gated. Treat them as readable by anything local. `/receive` and `/receive/undo` belong on this list even though they write: under the `token-write` policy, `needsToken()` exempts `GET`/`HEAD` from the token, so the only thing genuinely open on those two paths is a `405` — no read branch exists. `/profile-facts/apply` is POST-only for the same reason (its only open branch is a `405`). The `GET` branch of `/profile-facts` stays open even while `profileFactsEnabled` is off: facts survive a switch-off and the panel must be able to show them (same reasoning as `GET /profile`). This section mirrors the policy declarations rather than anyone's intent, which is why a write route shows up under "open reads"; `dsh-mneme/test/security-doc.test.js` compares both lists against the routes actually mounted, in both directions. +- **Open reads (no token even when one is configured)**: `GET /`, `/info`, `/version-check`, `/list`, `/recall-stats`, `/search`, `/semantic`, `/semantic/llm-audit`, `/semantic/llm-audit/stats`, `/semantic/consolidation-stats`, `/semantic/graph/*`, `/entities`, `/memories/entities`, `/dream-status`, `/inject-status`, `/inject-preview`, `/pipeline`, `/candidates`, `/diary`, `/diary/entry`, `/diary/library`, `/diary/library/entry`, `/diary/agent-audit`, `/llm-providers`, `/config-keys`, plus the `GET`/`HEAD` branches of `/profile`, `/rules`, `/persona`, `/persona/session`, `/profile-facts`, `/profile-digest`, `/mode`, `/features`, `/commands`, `/nudge`, `/diary/compose`, `/diary/export`, of the two share-receive routes `/receive` and `/receive/undo`, of `/profile-facts/apply`, of the six chorography read routes `/choro/repos`, `/choro/modules`, `/choro/page`, `/choro/search`, `/choro/claims`, `/choro/run` (M1/finale: they read repo-local wiki pages and `choro_*` index tables — not memory rows; with `chorographyEnabled` off they uniformly answer `409 disabled`, the #497 mount-anyway-gate-in-logic pattern), of the two T1 job routes `/choro/t1` and `/choro/t1/status` (same `token-write` shape as `/choro/run`: the only token-exempt branch is a `405`, and the POST itself answers `409 disabled` unless both `chorographyEnabled` and `chorographyT1FromPanel` are on), and of the three `token-write` knowledge-base routes `/kb/collections`, `/kb/ingest` and `/kb/search` (again only a `405` is genuinely open on them, because `needsToken()` exempts `GET`/`HEAD` under `token-write`; the two plain-`token` reads under `/kb/*` stay gated even on `GET`). `/choro/run` is the same shape as `/receive`: a `token-write` route whose GET branch is token-exempt, so the only genuinely open thing on that path is a `405` — the POST write itself stays gated. Treat them as readable by anything local. `/receive` and `/receive/undo` belong on this list even though they write: under the `token-write` policy, `needsToken()` exempts `GET`/`HEAD` from the token, so the only thing genuinely open on those two paths is a `405` — no read branch exists. `/profile-facts/apply` is POST-only for the same reason (its only open branch is a `405`). The `GET` branch of `/profile-facts` stays open even while `profileFactsEnabled` is off: facts survive a switch-off and the panel must be able to show them (same reasoning as `GET /profile`). This section mirrors the policy declarations rather than anyone's intent, which is why a write route shows up under "open reads"; `dsh-mneme/test/security-doc.test.js` compares both lists against the routes actually mounted, in both directions. - **Gated routes (when a token is configured)**: every write — `/create`, `/update`, `/delete`, `/import`, `/bootstrap`, `/vector-config`, `/vector-reindex`, `/runtime/provision`, `/maintenance/reclaim`, `/maintenance/backfill` (POST-only: the batch pass over imported DeepSeek-export sessions; it has no read branch — any other method is a `404` — and `dryRun` defaults to true, so the first call spends nothing; only a run with `"dryRun": false` reaches the host LLM), `/test-model`, `/conflicts/resolve`, `/profile/extract` (POST-only: one host-LLM call that returns a profile **draft**; other methods get 405 before any side effect), `/profile-facts/apply` (POST-only: per-fact manual corrections from the panel; writes the `profile_facts` tables, never `user_settings`), `/semantic/graph/affective/apply` (POST-only: per-group manual corrections on `affective_context` edges — rename/archive/restore/promote/demote; writes edge metadata plus the `affective_journal` ledger, never `user_settings`; its GET branch is open under the wildcard above — no gated read exists there), `/profile-facts/run` (POST-only, `token` policy like `/profile/extract`: one host-LLM maintenance pass with no read branch; 409 while `profileFactsEnabled` is off), `/profile-digest/generate` (POST-only, `token` policy: one host-LLM distillation of the fact list into a readable digest; 409 while `profileDigestEnabled` is off; the digest is panel-reading only and is never injected), `/scope/promote` (POST-only, plain `token`: re-stamps the `workspace_scope` of selected rows, one at a time, with a `scope_changes` audit row per success — it moves memories out of a hard-walled import area, so an unauthenticated caller must never reach it), `/choro/run` (POST-only: the panel "rebuild skeleton" write path, re-running T0 into the repo's `.chorography/**`; with `chorographyEnabled` off it uniformly answers 409 disabled), `/choro/t1` (POST-only: spawns a real T1 run through the choro CLI — a host-LLM pass that costs money, so it carries its own `chorographyT1FromPanel` switch on top of `chorographyEnabled`), `/choro/t1/status` (the job poll: its `logTail` carries CLI/model output, so it is not a public-repo read like the rest of `/choro/*`), `/kb/collections`, `/kb/search` (POST-only writes; the only token-exempt branch is the `405`, same shape as `/choro/run`), `/kb/ingest` (POST-only: pulls a configured local source into the knowledge base; source-level failures still answer `200` with `ok:false`, which is a result, not a permission), `/kb/docs`, `/kb/doc` (plain `token`: they hand back whatever collection content the user ingested — that is private material, unlike the repo-documentation `/choro/*` reads), `/receive`, `/receive/undo` (the two share-receive routes write into *this* machine's library, which is why they are `token-write`), `/diary/compose` (POST-only: one host-LLM call that writes `/diaries//YYYY-MM-DD.md`; 409 while `diaryEnabled` is off), `/diary/export` (POST-only: copies one entry into the *user's* bound project directory, which is outside every path the plugin otherwise owns — 409 on an existing target unless `overwrite` is explicit), and the non-`GET` branches of `/profile`, `/rules`, `/persona`, `/persona/session`, `/profile-facts`, `/profile-digest`, `/mode`, `/features`, `/commands`, `/nudge` — plus seven reads: `/export`, `/external-api`, `/conflicts`, `/conflicts/ledger` (read-only triage ledger — tier/status/detection timestamps and title-level info, same sensitivity as `/conflicts`), `/health`, `/share`, `/memory/provenance`. `/share` is gated because the share pack is a whole-library read delivered over POST, and it answers 405 to GET — no open read path exists. `/memory/provenance` is gated because it returns the **verbatim raw text** of distilled conversation windows (opt-in via `distillRecords.enabled`); chained with the open list route it would otherwise let any local process enumerate ids and then pull that text back, which reaches the same result as `/export` in a different shape. - **The standalone data plane** (`127.0.0.1:8790`) is the opposite shape: every route except `GET /health` requires its own Bearer token. Pointing `externalApiHost` at a non-loopback address therefore turns it into a plaintext, token-only HTTP surface — an explicit operator decision. - **Consequence**: if you expose the plugin beyond loopback (reverse proxy, non-loopback bind), set `apiToken` *and* check that the plain reads above are acceptable to expose — they are not covered by it. @@ -551,7 +551,7 @@ Token 是**写**面上的锁,不是把整个 API 围起来的墙。 - **真正的边界是回环 + 宿主监听器。** 宿主侧路由(`/api/dsh-mneme/*`)挂在 DSH 端口上,该端口绑 `127.0.0.1`。**每一条路由在动手之前都先问宿主一句 `ctx.connection.requestRejection(req)`**,所以宿主挡 DNS rebinding 与跨站浏览器请求的那道围栏,对插件的路由同样生效:浏览器里开着的网页调不动它们,拿到的是 `403`(围栏不过)或 `401`(没登录宿主),而不是记忆数据。这道围栏**不建立身份**:任何本地进程、以及任何跑在宿主同源页面里的脚本,都在这道围栏之内。宿主没提供 `connection` 服务时(headless、旧宿主、测试)这道检查跳过,行为退回加它之前的样子——缺一个宿主服务不能让整个面板 401。 - **鉴权是 opt-in 且 fail-open。** `apiToken` 默认为空;为空期间 `isAuthorized()` 对每个请求都返回 true——读和写都放行。配了 token 之后,它守的是写路由与敏感读,不守普通读。 -- **开放读(即使配了 token 也不需要)**:`GET /`、`/info`、`/version-check`、`/list`、`/recall-stats`、`/search`、`/semantic`、`/semantic/llm-audit`、`/semantic/llm-audit/stats`、`/semantic/consolidation-stats`、`/semantic/graph/*`、`/entities`、`/memories/entities`、`/dream-status`、`/inject-status`、`/inject-preview`、`/pipeline`、`/candidates`、`/diary`、`/diary/entry`、`/diary/library`、`/diary/library/entry`、`/llm-providers`、`/config-keys`,以及 `/profile`、`/rules`、`/persona`、`/persona/session`、`/profile-facts`、`/profile-digest`、`/mode`、`/features`、`/commands`、`/nudge`、`/diary/compose`、`/diary/export`、`/receive`、`/receive/undo`、`/profile-facts/apply`、`/choro/repos`、`/choro/modules`、`/choro/page`、`/choro/search`、`/choro/claims`、`/choro/run`、`/choro/t1`、`/choro/t1/status`、`/kb/collections`、`/kb/ingest`、`/kb/search` 的 `GET`/`HEAD` 分支。`/choro/run` 与 `/receive` 同款:token-write 的 GET 分支免 token 后真正开放的只有一个 405(它只收 POST),出现在这里是 policy 声明的忠实投影。把它们当作「本地任何东西都能读」。`/receive`、`/receive/undo` 明明是写路由也出现在这一串里,这不是笔误:`token-write` 下 `needsToken()` 对 `GET`/`HEAD` 免 token,所以这两条路径上真正「开放」的只有一个 `405`,压根没有可读分支;`/profile-facts/apply` 同理只收 POST,开放的唯一分支是一个 `405`。`/profile-facts` 的 `GET` 分支在 `profileFactsEnabled` 关着时同样开放:开关关掉后存量事实还在库里,面板要能展示(与 `GET /profile` 同一理由)。`/choro/*` 六条(chorography 仓库地志读侧,M1 + 收尾档)读的是**仓库里的 MD 页与 choro_* 索引表**,不是记忆行——内容是代码仓库的公开文档面,`chorographyEnabled` 关着时统一回 409 disabled(路由挂着、逻辑层挡,#497 先例),不因为开放读而绕过这个闸。这一节照 policy 声明抄、不照意图写,`dsh-mneme/test/security-doc.test.js` 会拿真实装配出来的路由双向比对这两行。 +- **开放读(即使配了 token 也不需要)**:`GET /`、`/info`、`/version-check`、`/list`、`/recall-stats`、`/search`、`/semantic`、`/semantic/llm-audit`、`/semantic/llm-audit/stats`、`/semantic/consolidation-stats`、`/semantic/graph/*`、`/entities`、`/memories/entities`、`/dream-status`、`/inject-status`、`/inject-preview`、`/pipeline`、`/candidates`、`/diary`、`/diary/entry`、`/diary/library`、`/diary/library/entry`、`/diary/agent-audit`、`/llm-providers`、`/config-keys`,以及 `/profile`、`/rules`、`/persona`、`/persona/session`、`/profile-facts`、`/profile-digest`、`/mode`、`/features`、`/commands`、`/nudge`、`/diary/compose`、`/diary/export`、`/receive`、`/receive/undo`、`/profile-facts/apply`、`/choro/repos`、`/choro/modules`、`/choro/page`、`/choro/search`、`/choro/claims`、`/choro/run`、`/choro/t1`、`/choro/t1/status`、`/kb/collections`、`/kb/ingest`、`/kb/search` 的 `GET`/`HEAD` 分支。`/choro/run` 与 `/receive` 同款:token-write 的 GET 分支免 token 后真正开放的只有一个 405(它只收 POST),出现在这里是 policy 声明的忠实投影。把它们当作「本地任何东西都能读」。`/receive`、`/receive/undo` 明明是写路由也出现在这一串里,这不是笔误:`token-write` 下 `needsToken()` 对 `GET`/`HEAD` 免 token,所以这两条路径上真正「开放」的只有一个 `405`,压根没有可读分支;`/profile-facts/apply` 同理只收 POST,开放的唯一分支是一个 `405`。`/profile-facts` 的 `GET` 分支在 `profileFactsEnabled` 关着时同样开放:开关关掉后存量事实还在库里,面板要能展示(与 `GET /profile` 同一理由)。`/choro/*` 六条(chorography 仓库地志读侧,M1 + 收尾档)读的是**仓库里的 MD 页与 choro_* 索引表**,不是记忆行——内容是代码仓库的公开文档面,`chorographyEnabled` 关着时统一回 409 disabled(路由挂着、逻辑层挡,#497 先例),不因为开放读而绕过这个闸。这一节照 policy 声明抄、不照意图写,`dsh-mneme/test/security-doc.test.js` 会拿真实装配出来的路由双向比对这两行。 - **受门控的路由(配了 token 之后)**:全部写操作——`/create`、`/update`、`/delete`、`/import`、`/bootstrap`、`/vector-config`、`/vector-reindex`、`/runtime/provision`、`/maintenance/reclaim`、`/maintenance/backfill`(只收 POST:把导入的 DeepSeek 导出会话按批过一遍蒸馏;没有读分支,其它方法一律 `404`;`dryRun` 默认 true,第一次调用一个 token 都不花,只有显式 `"dryRun": false` 才真的走到宿主 LLM)、`/test-model`、`/conflicts/resolve`、`/profile/extract`(只收 POST:花一次宿主 LLM 产一段画像**草稿**,其它方法在产生任何副作用之前就 405)、`/profile-facts/apply`(只收 POST:面板的逐条人工修正;写的是 profile_facts 三表,绝不碰 user_settings)、`/semantic/graph/affective/apply`(只收 POST:情绪的逐组人工修正——改词/归档/恢复/升格/降格,作用于 affective_context 边;写的是边的 metadata 加 affective_journal 账本,绝不碰 user_settings;其 GET 分支按上方通配开放,那里没有受门控的读分支)、`/profile-facts/run`(只收 POST,`token` 政策与 `/profile/extract` 同款:一次宿主 LLM 维护轮,无读分支;`profileFactsEnabled` 关着时 409)、`/profile-digest/generate`(只收 POST,`token` 政策:一次宿主 LLM 蒸馏,把事实清单改成可扫读的摘要;`profileDigestEnabled` 关着时 409;摘要只作阅读面,注入不读)、`/scope/promote`(只收 POST,`token` 政策:把选中条目的 `workspace_scope` 逐条改写出去,每条成功都落一行 `scope_changes` 审计——它负责把记忆搬出硬墙导入区,绝不能给未鉴权的调用方)、`/choro/run`(只收 POST:面板「重建骨架」的写入口,重跑 T0 落仓库磁盘的 `.chorography/**`——chorographyEnabled 关着时统一 409 disabled)、`/choro/t1`(只收 POST:经 choro CLI 真起一次 T1——一次要花模型额度的宿主 LLM 作业,所以在 `chorographyEnabled` 之上另有一枚 `chorographyT1FromPanel` 闸)、`/choro/t1/status`(任务轮询:`logTail` 里带 CLI 与模型的原始输出,不属 `/choro/*` 其余几条那种「仓库公开文档面」)、`/kb/collections`、`/kb/search`(只收 POST 的写入口,token-write 下真正开放的只有一个 405,与 `/choro/run` 同款)、`/kb/ingest`(只收 POST:把用户配置的本地来源抽进知识库;来源级失败仍回 `200` + `ok:false`,那是结果不是权限)、`/kb/docs`、`/kb/doc`(纯 `token`:回的是用户导进来的集合内容,属私料,与 `/choro/*` 那类仓库文档读侧不同量级)、`/receive`、`/receive/undo`(这两条写的是**本机自己的库**,所以归 `token-write`)、`/diary/compose`(只收 POST:花一次宿主 LLM 写 `/diaries/<项目键>/YYYY-MM-DD.md`;`diaryEnabled` 关着时 409)、`/diary/export`(只收 POST:把某一篇**复制**进用户绑定的项目目录——那是插件本来不拥有的路径,目标已存在时默认 409,要覆盖必须显式传 `overwrite`),以及 `/profile`、`/rules`、`/persona`、`/persona/session`、`/profile-facts`、`/profile-digest`、`/mode`、`/features`、`/commands`、`/nudge` 的非 `GET` 分支——外加七条读:`/export`、`/external-api`、`/conflicts`、`/conflicts/ledger`(矛盾分诊账本的只读面:tier/status/检出时间与标题级信息,与 `/conflicts` 同级——处置由 enforce 档自动完成,行不是待办)、`/health`、`/share`(分享包是「用 POST 递出来的全库读取」,GET 一律 405,没有开放的读分支)、`/memory/provenance`(它回的是蒸馏窗口的**逐字会话原文**,并自 #512 起按窗口带出 `distill_run_id` / `run_type` / `trigger_source` / `run_status` 的运行归因;`distillRecords.enabled` 打开才有;否则把它和上面那个开放的列表路由串起来,任何本地进程都能先枚举 id、再按 id 把那些原文捞回去——可达结果与 `/export`(一次拿全库)同量级,只是换了形状)。 - **独立数据面**(`127.0.0.1:8790`)是反过来的形状:除 `GET /health` 外每条路由都要自己的 Bearer token。因此把 `externalApiHost` 指向非回环地址,就等于把它变成一个「明文、只靠 token」的 HTTP 面——这是运营者的显式决定。 - **推论**:如果你把插件暴露到回环之外(反代、绑非回环地址),请设 `apiToken`,**并**核对上面那串开放读是否也能被看到——它们不受 token 保护。 diff --git a/dsh-mneme/CHANGELOG.md b/dsh-mneme/CHANGELOG.md index 9948c3e5..136eaffb 100644 --- a/dsh-mneme/CHANGELOG.md +++ b/dsh-mneme/CHANGELOG.md @@ -2,6 +2,18 @@ ## [Unreleased] +- **日记静默失败现在会落盘:总账、触发侧失败、面板可见(#760)**。#758 复盘时发现一个比 bug 本身更麻烦的事:那 24 小时里日记一次没写,磁盘上**一个字节的痕迹都没有**——`runs.jsonl` 连一行 skip 都没有,报告人只能靠「今天怎么没日记」发现。根因是诊断面全挂在落点上:桶内账本的位置由「算出来的目录」决定,而最需要留痕的两种失败恰好是**目录算不出来**(`project-unknown` 项目标签缺失、`agent-invalid` 身份形状不合法)。`root` 为 null ⇒ `auditFile` 也是 null ⇒ `audit()` 直接 return。桌面端又没有控制台可看(`app.asar` 里读不到,`%APPDATA%` 下只有十月的 crash 日志),于是失败真正变成了静默。 + + 现在多加一本**总账**,落点固定在日记根目录(`/diaries/runs.jsonl`),与落点算不算得出来无关。写入口收在一处:`compose.js` 的 `recordRoot(record)` 负责补 `v`/`ts` 与换行,`diaryRootAuditPath()` 负责算路径,三层(compose 自身、触发侧、接口)都走它,不各拼一份格式。三类此前无声的失败各自补上:① 落点算不出来时记 `skipped` + `agent-invalid`/`project-unknown`,带上 agentId、projectRoot、chatId/sessionId——**这条分支以前连 skip 都不写**;② compose 抛出未捕获异常时记 `failed` + `compose-threw`,然后**原样把异常抛回去**(不能吞,调用方还要靠这次 reject 判失败);③ 触发侧的三种失败(`agent-resolve-failed`、`timer-scan-failed`、`timer-tick-failed`)走新增的 `composer.noteFailure()`——它们根本到不了 compose,以前只有一行 `log?.warn`。`auto.js` 里另三处(`runOne` 的 compose failed、`catchUp` 的 agent/project 两条)**故意保持只 warn**:compose 出口已经记了 `compose-threw`,同一次失败记两行会让「跑过几次」失去意义。 + + 面板跟着能看到原因:`GET /diary` 的返回体多一个 `rootAudit`(按 `projectRoot` 精确过滤,不回退成「全库都给你看」;老 composer 没实现时退回空数组而不是 500),日记页 footer 现在画两本账——「最近运行」与「没写成的原因」,各取末 6 条。日期用本地时区拼,不能 `toISOString()`(UTC 会让北京时间早八点前显示成前一天)。控制台日志文案**保持旧措辞**:`record()` 的第四参 `logText` 让 kebab reason 只进磁盘,`log?.warn` 照旧打 "diary timer scan failed"——旧日志和既有测试都按那句话搜。 + + **只接项目页救不了 #758 现场**(这条是自查出来的设计漏洞)。项目日记页读 `GET /diary`,而 #758 出事的是 **agent 日记页**:`DiaryLibraryPanel` 读 `/diary/library`,根本不碰 `/diary`;更关键的是 `/diary` 第一件事就要 `project`,而 agent 桶的落点是 `agents//`、**没有 projectRoot**——照原方案,最需要看原因的那一页一行都拿不到。于是 `readRootAudit` 的问法扩成三种:给 `agentId` 按 agent 过滤、`agentOnly` 只取 `agentMode === true` 的行、都不给返回空(绝不退成「全库都给你看」);另开一条 `GET /diary/agent-audit`,**「不带 agent」是合法问法**(#758 现场 `diaries/agents/` 下只有 `sessions.json`、页面根本拿不到 agentId,这种「一次都没跑起来」正是要看的情况),给了 agent 就用 `isBucketName` 校验、路径语义的名字回 400 `agent-invalid`。面板侧选中 agent 桶时带 `?agent=`、选中项目桶时改问 `GET /diary?project=`、一本都没选中(或压根没有桶)时问 agent 域,读失败只置空不显示假的「一切正常」。**只问 agent 域同样不够**——那会让项目桶上摆一排人格的失败,比不显示更误导;两种桶问的是两个问题,就得分两路问。另修一处会漏记的:`agent-resolve-failed` 发生在「还不知道身份」的时候,原先不带 `projectRoot`,于是 `readRootAudit({ projectRoot })` 永远过滤不到它、项目页看不到真正让今天没写的那一下。现在先从会话的 `header.cwd` 取(读失败也只是不记这一字段,不许因诊断自己抛错而丢整条记录),取不到就不写这个键——宁缺,不把失败记到别人项目头上。 + + **第二轮评审又四条,全部核实属实。**① 聚合视图不分人:一本桶都没有时页面问的是「agent 域全部」,`alice` 和 `bob` 同一天都没写成,页脚只有两行一模一样的「身份解析失败」,用户分不清哪条是谁的——`diaryAuditLine` 加 `showAgent`,只在聚合视图把 `agentId` 写进行内,单本视图保持紧凑。② 切桶会串账:从 A 桶切到 B 桶时旧的 `rootAudit` 还躺在 state 里,`dead` 只挡迟到的响应、管不了已经存下来的那批,于是 B 的响应回来之前页脚把 A 的失败当成 B 的摆出来——改成把结果**与它对应的问法一起存**(`{key, rows}`),只画 key 与当前问法一致的那批,不一致就短暂空着。③ **写入失败后不刷新**:服务端刚记下 `compose-threw`,客户端却在非 2xx 分支 `return` 掉了、`tick` 不动,于是「为什么没写成」要等用户手动重读才出现,等于白记——`runCompose` 与 `DiaryPane` 的失败分支(含网络异常)都补上刷新。④ 触发侧失败缺运行域:`agentResolver` 抛错那行没有 `agentMode`,`readRootAudit({ agentOnly: true })` 直接把它排除掉,而那正是「连桶都没有时最该看到的原因」;`timer-scan-failed`/`timer-tick-failed` 同样按这一轮实际扫的是不是 agent 名单补上(项目模式的记录仍不带这个字段,两边不串)。 + + **测试** 3,723 → **3,736**:先前所有日记用例只验「写成功」与「桶内账本写了 skip」,没有一条验「落点算不出来时磁盘有东西」——这正是 #758 能潜伏 24 小时的原因。新增 6 条锁总账(项目根为空 / agentId 不合法 / 正常写入不重复记 / compose 抛出时记完再抛 / 触发侧失败也进总账 / 没有 noteFailure 时退回只 warn),2 条锁项目维度(身份解析失败带上 `projectRoot`;没有 cwd 时**不硬填假路径**,宁缺也别记到别人项目头上),2 条锁本轮第 ④ 条(解析失败与 agent 名单扫描各自标上 `agentMode`,且**从真实触发走到 `readRootAudit({ agentOnly: true })` 真的读得回**——桩 composer 只能证明「传了什么」,证明不了「按 agent 域问得到」,而 #758 现场坏的正是后者),1 条锁 `readRootAudit` 的项目过滤(读得回自己那行、不同项目互不串、什么都不问时返回空而不退成「全库都给你看」)。`test/api.test.js` +4 锁接口(`/diary` 两本账都按项目过滤且带 limit、老 composer 不 500、agent 页按 agentId 与按 agent 域各一次问对参数、路径语义的 agent 名一律 400 而老 composer 仍 200)。变异自证五处各一次:删掉 `!root` 分支的 `recordRoot` → 前两条红;删掉 `compose-threw` 记录 → 第三条红;删掉 `composer.noteFailure(...)` 调用 → 触发侧那条红;抹掉解析失败的 `agentMode` → 项目那条与 agent 域读回那条一起红;抹掉定时扫描的 `agentMode` → agent 名单扫描那条红。跨层验证另跑一次:`src`/`lib` 五对文件 md5 逐对一致(`npm run sync` 在 `dsh-mneme/` 子目录里跑),`node --check` 过六个改动文件。新路由同时进 `SECURITY.md` 的开放读清单——`test/security-doc.test.js` 拿装配出来的真实路由双向比对,漏登记会直接红(这次就是它先响的)。 + - **agent 日记桶第一天永远开不了张:名单来源、身份丢失、桶键三处(#758)**。现场是 `diaries/agents/` 下只有 `sessions.json`(3 条会话 → agent `standard`),一个 `/` 桶都没有;此后 24 小时零写入,连 `runs.jsonl` 的 skip 记录都没有——素材经 SQL 复算完全够(11-17 58 条 / 11-18 71 条 / 11-19 44 条),模型一次没被叫。 三处各自独立,缺一条都还是哑的:① **名单来源错了**。`knownAgents()` 只扫「已经写过日记的桶」,而建桶发生在写入时,于是桶不存在 ⇒ 名单为空 ⇒ 定时巡检与启动补写都 `Promise.all([])` 直接 resolve,不建桶、不写账本、不留痕迹。权威来源改成 `agents/sessions.json` 的映射值(`settleAgent` 在 turn/end 时就写下了),并与已有桶取**并集**——手工建的桶、旧版遗留的桶即便不在映射里也该继续被巡检,收紧成「只看映射」会让那些书从此不再更新而界面上看不出来;空目录不进名单(建了一半的不该让巡检每天白跑)。② **身份在调度层就丢了**(这条不是「没建桶」,建桶治不了)。`scheduleAgent(agentId, …)` 把 `payload` 原样放进 `pending`,却没把 `agentId` 存进去,而 `runOne` 恰恰从 `payload.agentId` 取身份——一路 `undefined` 下去,`diaryAgentDir` 拿空 id 返回 null,`compose` 落 `agent-invalid`;更糟的是 root 为 null 时 `auditFile` 也是 null,连那条 skip 都写不出来。这就是「手工建好桶之后仍然毫无动静」的原因。③ **桶键两套口径**。清单给 agent 桶的键是 `agents/`,而 `library/entry` 路由拿 `isBucketName` 直接校验——那把尺按「单层目录名」设计、显式禁 `/`,必然 400 `bucket-required`,面板永远卡在「正在读…」。桶键解析现在抽成 `resolveBucketDir` 一处:剥掉 `agents/` 前缀后同一把尺量剩下的那段,清单、单篇读取、路由白名单三层同一个判据,`agents/../x` 一类仍然照样 400。 diff --git a/dsh-mneme/lib/api.js b/dsh-mneme/lib/api.js index 5cfdf63e..682d7276 100644 --- a/dsh-mneme/lib/api.js +++ b/dsh-mneme/lib/api.js @@ -56,7 +56,9 @@ import { // 桶键解析也走同一处:清单、单篇读取、路由白名单三层必须用同一道判据,否则会 // 出现「列得出来、点进去 400」——#758 就是这么坏的(`agents/` 键过不了 // 按单层目录名设计的 isBucketName)。 - listDiaryLibrary, readLibraryEntry, resolveBucketDir + listDiaryLibrary, readLibraryEntry, resolveBucketDir, + // agent 诊断口按 agentId 校验:agent 身份是单层目录名,与桶名同一把尺。 + isBucketName } from "./diary/index.js"; import { readCandidateDoc } from "./candidates.js"; // M.O. 自动沉淀:/nudge 是 pipeline-nudge.js 的第一个运行时消费者(此前它只有测试在用, @@ -3760,8 +3762,12 @@ export function createApi(ctx, service, settings, commands, embedder, semantic = try { const dir = diaryDir({ memoryDir: config.memoryDir, projectRoot: project, configured: config.diaryDir }); // 账本一起带走:面板要回答「今天为什么没有日记」时必须读它,不能靠猜。 + // #760:两本都要——桶内那本记「落点算出来之后的失败」,总账记「连落点都 + // 没算出来的那些」(compose 在落点之前抛掉)。只读前者,用户看到的仍是 + // 「今天没写」,而真正的原因一直躺在总账里没人看。 const audit = diary.readAudit({ projectRoot: project, limit: 20 }); - sendJson(res, 200, { contract: "mneme.diary/v1", project, dir, diaries: listDiaries(dir), audit }); + const rootAudit = typeof diary.readRootAudit === "function" ? diary.readRootAudit({ projectRoot: project, limit: 20 }) : []; + sendJson(res, 200, { contract: "mneme.diary/v1", project, dir, diaries: listDiaries(dir), audit, rootAudit }); } catch (error) { sendJson(res, 500, { error: "diary-unreadable", detail: String((error && error.message) || error) }); } @@ -3796,6 +3802,41 @@ export function createApi(ctx, service, settings, commands, embedder, semantic = } }); + // #760:agent 日记页的诊断口。 + // + // 为什么不能复用 `GET /diary`:那条路由第一件事就是 `diaryProject` 要 `project`, + // 而 agent 桶**没有 projectRoot**(agentMode 的落点是 `agents//`)。 + // 于是 agent 页要么传一个假 project(读到的全是别人的账),要么根本读不到—— + // 而 #758 出事的恰恰就是 agent 桶第一天开不了张。按 agentId 单独给一个口, + // 页面才可能在「一篇都没有」的时候说清「一次都没跑起来」还是「跑了但没写」。 + register({ + kind: "exact", + path: "/api/dsh-mneme/diary/agent-audit", + policy: "open", + handler(req, res) { + if (!diaryGate(req, res)) return; + const agentId = new URL(req.url, "http://localhost").searchParams.get("agent"); + // 不给 agent 是**合法**的第三种问法:agent 桶一个都还没建起来时(#758 现场 + // 就是 `diaries/agents/` 下只有 sessions.json),页面连一本书都列不出来, + // 也就拿不到 agentId。那时候要回答的正是「一次都没跑起来,为什么」。 + if (agentId !== null && agentId !== "" && !isBucketName(agentId)) { + sendJson(res, 400, { error: "agent-invalid", detail: agentId }); + return; + } + try { + const query = agentId === null || agentId === "" + ? { agentOnly: true, limit: 20 } + : { agentId, limit: 20 }; + const rootAudit = typeof diary.readRootAudit === "function" + ? diary.readRootAudit(query) + : []; + sendJson(res, 200, { contract: "mneme.diary/v1", agent: agentId || null, rootAudit }); + } catch (error) { + sendJson(res, 500, { error: "diary-unreadable", detail: String((error && error.message) || error) }); + } + } + }); + register({ kind: "exact", path: "/api/dsh-mneme/diary/compose", diff --git a/dsh-mneme/lib/client.js b/dsh-mneme/lib/client.js index e4119a74..6f16c864 100644 --- a/dsh-mneme/lib/client.js +++ b/dsh-mneme/lib/client.js @@ -1062,6 +1062,7 @@ window.__ModuleLoader__.load({ "memory.diary.skip.noMaterial": "今天这个项目没有可用的对话素材,所以没写。", "memory.diary.skip.other": "这一轮没有写成。", "memory.diary.auditTitle": "最近几轮", + "memory.diary.rootAuditTitle": "没写成的原因", "memory.diary.status.written": "写了", "memory.diary.status.skipped": "跳过", "memory.diary.status.failed": "失败", @@ -2287,6 +2288,7 @@ window.__ModuleLoader__.load({ "memory.diary.skip.noMaterial": "No usable conversation material in this project today, so nothing was written.", "memory.diary.skip.other": "Nothing was written this round.", "memory.diary.auditTitle": "Recent runs", + "memory.diary.rootAuditTitle": "Why it was not written", "memory.diary.status.written": "written", "memory.diary.status.skipped": "skipped", "memory.diary.status.failed": "failed", @@ -12722,6 +12724,30 @@ window.__ModuleLoader__.load({ return renderWikiMarkdown(lines.slice(i).join("\n")); } + // #760:账本行的日期。总账的行不一定带 date(触发侧在落点之前失败时没有 + // 「今天」这个概念),但有 ts。**用本地时区拼**,不能用 toISOString——那是 + // UTC,北京时间早上八点前会显示成前一天。 + function diaryAuditDay(ts) { + const d = new Date(Number(ts)); + if (Number.isNaN(d.getTime())) return ""; + const p = (n) => String(n).padStart(2, "0"); + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`; + } + + // 两本账(桶内 runs.jsonl 与总账)的行形状一致,渲染也共用这一处: + // 「哪天 · 什么状态 · 为什么 · 详情」。项目页与 agent 页都用它。 + /** + * 一条失败原因。`showAgent` 只在**聚合视图**用(没指定 agent、一次取回多本人格的 + * 账):那种时候不写是谁,alice 和 bob 同一天都没写成,用户分不清哪条是谁的。 + * 单本视图本来就知道是谁,再重复一遍只是噪音。 + */ + function diaryAuditLine(h, t, a, i, showAgent = false) { + const who = showAgent && a && a.agentId ? String(a.agentId) : ""; + return h("div", { key: "a" + i, className: "mneme-diary-auditrow" }, + [a.date || diaryAuditDay(a.ts), t("memory.diary.status." + (a.status || "skipped")), who, a.reason || "", a.detail || a.error || ""] + .filter(Boolean).join(" · ")); + } + function DiaryPane(props) { const { t, project, agent, session } = props; const [doc, setDoc] = useState(undefined); // undefined=读中 null=读不出 对象=拿到 @@ -12805,7 +12831,9 @@ window.__ModuleLoader__.load({ .then((res) => res.json().then((body) => ({ ok: res.ok, body }))) .then((r) => { const b = r.body || {}; - if (!r.ok) { say("bad", t("memory.diary.composeFailed") + (b.error ? " (" + b.error + ")" : "")); return; } + // 失败更要刷新:服务端会把 compose-threw 记进总账,而诊断块只在 tick 变 + // 的时候重取——不刷的话「为什么没写成」要等用户手动重读才出现,等于白记。 + if (!r.ok) { say("bad", t("memory.diary.composeFailed") + (b.error ? " (" + b.error + ")" : "")); setTick((n) => n + 1); return; } // skip 也是 200——「今天写过 / 今天没聊」都是正常结果,必须说清是哪一种, // 否则用户看到的是一句「成功了」但什么都没变(假成功)。 // 写成时不能借用「已存到」那句文案——写和入库是两件事, @@ -12817,7 +12845,7 @@ window.__ModuleLoader__.load({ else say("ok", t("memory.diary.skip.other")); setTick((n) => n + 1); }) - .catch((err) => { console.warn("[dsh-mneme] diary compose failed:", err); say("bad", t("memory.diary.composeFailed")); }) + .catch((err) => { console.warn("[dsh-mneme] diary compose failed:", err); say("bad", t("memory.diary.composeFailed")); setTick((n) => n + 1); }) .finally(() => setBusy("")); }; @@ -12889,12 +12917,24 @@ window.__ModuleLoader__.load({ } const audit = (doc && doc.audit) || []; - const foot = audit.length - ? h("div", { className: "mneme-diary-audit" }, - h("div", { className: "mneme-diary-audithead" }, t("memory.diary.auditTitle")), - audit.slice(-6).reverse().map((a, i) => h("div", { key: "a" + i, className: "mneme-diary-auditrow" }, - [a.date, t("memory.diary.status." + (a.status || "skipped")), a.reason || ""].filter(Boolean).join(" · ")))) - : null; + // #760:总账那本。桶内账本只覆盖「落点已算出之后」的失败;compose 在落点之前 + // 就炸掉的(模型、注入时钟)只留在总账里。面板若不显示它,用户看到的永远只有 + // 「今天没写」四个字——而原因其实一直躺在磁盘上。 + const rootAudit = (doc && doc.rootAudit) || []; + // 日期换算与行渲染都提到模块级(diaryAuditDay / diaryAuditLine):agent 页 + // 也要画同一本总账,两处各写一份的话迟早只有一处修得到。 + const auditBlocks = []; + if (audit.length) { + auditBlocks.push(h("div", { className: "mneme-diary-audit" }, + h("div", { className: "mneme-diary-audithead" }, t("memory.diary.auditTitle")), + audit.slice(-6).reverse().map((a, i) => diaryAuditLine(h, t, a, i)))); + } + if (rootAudit.length) { + auditBlocks.push(h("div", { className: "mneme-diary-audit" }, + h("div", { className: "mneme-diary-audithead" }, t("memory.diary.rootAuditTitle")), + rootAudit.slice(-6).reverse().map((a, i) => diaryAuditLine(h, t, a, i)))); + } + const foot = auditBlocks.length ? h("div", null, auditBlocks) : null; return h("div", { className: "mneme-diary" }, head, @@ -13098,6 +13138,54 @@ window.__ModuleLoader__.load({ return () => { dead = true; }; }, [activeItem && activeItem.key]); + // #760:诊断面。agent 页**不读** `/diary`——那条路由第一件事就是要 `project`, + // 而 agent 桶没有 projectRoot(落点是 agents//)。于是 #758 那种 + // 「桶第一天开不了张」在这页上永远只显示「还没写过」,原因(身份丢了、名单 + // 空了)一直躺在总账里没人读。 + // + // 三种问法各对不同的桶: + // - 选中的是 agent 桶 → 按 agentId 问那个人的失败; + // - 选中的是项目桶 → 按 projectRoot 问这个项目的失败(`/diary` 已经把它带出来); + // - 一本都没选中/一本都没有 → 不带 agent 问 agent 域(#758 现场页面连 agentId + // 都拿不到,而「一次都没跑起来」正是要回答的)。 + // 只走前一种会把项目级的失败藏起来:项目桶上摆一排人格的失败,比不显示更误导。 + // 结果与**它对应的问法**一起存。只存结果是不够的:从 A 桶切到 B 桶时旧的一批 + // 还躺在 state 里,`dead` 只挡迟到的响应,管不了已经存下来的那批——于是 B 的 + // 响应回来之前,页脚会把 A 的失败当成 B 的失败摆出来。 + const [rootAudit, setRootAudit] = useState({ key: "", rows: [] }); + const activeBucketKey = (activeItem && activeItem.bucket) || ""; + const activeBucketRoot = (() => { + const b = buckets.find((x) => x.key === activeBucketKey); + return (b && typeof b.projectRoot === "string" && b.projectRoot) || ""; + })(); + const auditKey = activeBucketKey.startsWith("agents/") + ? "agent:" + activeBucketKey.slice("agents/".length) + : activeBucketRoot + ? "project:" + activeBucketRoot + : "agent:*"; + useEffect(() => { + let dead = false; + const url = auditKey.startsWith("agent:") + ? (auditKey === "agent:*" + ? "/api/dsh-mneme/diary/agent-audit" + : "/api/dsh-mneme/diary/agent-audit?agent=" + encodeURIComponent(auditKey.slice("agent:".length))) + : "/api/dsh-mneme/diary?project=" + encodeURIComponent(auditKey.slice("project:".length)); + apiFetch(url) + .then((res) => res.json().then((body) => ({ ok: res.ok, body }))) + .then((r) => { + if (dead) return; + const rows = r.ok && r.body && Array.isArray(r.body.rootAudit) ? r.body.rootAudit : []; + setRootAudit({ key: auditKey, rows }); + }) + .catch((err) => { + // 读不到就什么都不显示,不拿一条假的「没有失败」顶上——那句「一切正常」 + // 会让人放弃去看真正的原因。 + console.warn("[dsh-mneme] diary root audit failed:", err); + if (!dead) setRootAudit({ key: auditKey, rows: [] }); + }); + return () => { dead = true; }; + }, [auditKey, tick]); + // 当前这一篇属于哪个项目:桶是 projectKey(projectRoot) 的产物,反推不回路径, // 所以只能读 diaries/state.json 里 compose 自己记的账(library.js 已并进桶上)。 const activeBucket = activeItem @@ -13122,7 +13210,8 @@ window.__ModuleLoader__.load({ .then((res) => res.json().then((body) => ({ ok: res.ok, body }))) .then((r) => { const b = r.body || {}; - if (!r.ok) { say("bad", t("memory.diary.composeFailed") + (b.error ? " (" + b.error + ")" : "")); return; } + // #760:失败也刷新总账——服务端刚记下的那条 compose-threw 正等着被读出来。 + if (!r.ok) { say("bad", t("memory.diary.composeFailed") + (b.error ? " (" + b.error + ")" : "")); setTick((n) => n + 1); return; } // skip 不是错:already-written / no-material 都是关于这本书的答案, // 说清楚比笼统报「没写成」有用。 if (b.status === "written") say("ok", t("memory.diary.writtenOk").replace("{path}", String(b.path || ""))); @@ -13134,6 +13223,7 @@ window.__ModuleLoader__.load({ .catch((err) => { console.warn("[dsh-mneme] diary compose failed:", err); say("bad", t("memory.diary.composeFailed")); + setTick((n) => n + 1); }) .then(() => setBusy("")); }; @@ -13256,7 +13346,20 @@ window.__ModuleLoader__.load({ }, notice.text) : null; - return h("div", { className: "mneme-diary" }, head, noticeRow, body); + // #760:库页的页底也画总账——问的是「当前这本为什么没写成」,跟着选中的桶走。 + // 项目页画的是「这个项目的」失败;这里画的是「这一本/这个人格的」——两者选的 + // 桶不同,问的就不是同一个问题,所以各画各的。 + // 只画**问法与当前问法一致**的那批:不一致说明新的还没回来,宁可短暂空着, + // 也不把上一个桶的失败冒充成这一个桶的。 + const auditRows = rootAudit.key === auditKey ? rootAudit.rows : []; + const auditShowAgent = auditKey === "agent:*"; + const rootAuditFoot = auditRows.length + ? h("div", { className: "mneme-diary-audit" }, + h("div", { className: "mneme-diary-audithead" }, t("memory.diary.rootAuditTitle")), + auditRows.slice(-6).reverse().map((a, i) => diaryAuditLine(h, t, a, i, auditShowAgent))) + : null; + + return h("div", { className: "mneme-diary" }, head, noticeRow, body, rootAuditFoot); } diff --git a/dsh-mneme/lib/diary/auto.js b/dsh-mneme/lib/diary/auto.js index 9204a666..9a6139d3 100644 --- a/dsh-mneme/lib/diary/auto.js +++ b/dsh-mneme/lib/diary/auto.js @@ -33,6 +33,29 @@ export function createDiaryAutoRun({ listAgents = null } = {}) { const log = logger || (ctx && ctx.logger) || null; + /** + * #760:把一处失败同时写进控制台与**磁盘总账**。 + * + * 为什么要两条腿:`log?.warn` 在桌面端等于没写——app.asar 里的插件控制台没人 + * 看得到,`%APPDATA%` 下只有 10 月的 crash 日志(#758 报告人的原话)。这次故障 + * 的实际信号是「用户自己发现今天没日记」,而那一刻离出事已经隔了一天。 + * + * 只用 composer.noteFailure 一个口子,不给 auto.js 拼账本路径的理由:账本格式 + * (补换行、v/ts 字段)只该有一处实现。composer 缺席(旧接线/测试桩)就只剩 warn, + * 与改动前逐字节相同。 + */ + const record = (reason, detail, extra = {}, logText = null) => { + // 控制台那句沿用改动前的措辞(旧日志、旧测试都按它搜),账本里用 kebab 的 + // reason——两个面服务两种读法,没必要为了统一把既有的 grep 习惯改掉。 + log?.warn?.("[dsh-mneme] " + (logText || reason) + ": " + detail); + try { + if (composer && typeof composer.noteFailure === "function") { + composer.noteFailure({ reason, detail, ...extra }); + } + } catch { + // 诊断面失败不许反过来打断派发链。 + } + }; let disposed = false; let timer = null; /** 定时写的钟。与 timer(setTimeout(0) 的派发器)是两回事:那个只把待判项目挪到下一帧。 */ @@ -77,6 +100,9 @@ export function createDiaryAutoRun({ // compose 是异步的(要等模型),绝不能返回给 session/event 的派发方去 await—— // 那会把回合收尾吊在模型延迟上(本机实测 p90 五十秒级)。 return Promise.resolve(task).catch((error) => { + // 这里**不**再记总账:compose 自己的出口已经写了 compose-threw(#760), + // 同一次失败记两行会让「跑过几次」失去意义。控制台的 warn 保留——两条腿 + // 各自服务不同的读法。 log?.warn?.("[dsh-mneme] diary compose failed (" + key + "): " + String((error && error.message) || error)); return null; }); @@ -136,7 +162,28 @@ export function createDiaryAutoRun({ try { resolved = agentResolver(session); } catch (error) { - log?.warn?.("[dsh-mneme] diary agent resolve failed: " + String((error && error.message) || error)); + // 这条失败发生在「还不知道身份」的时候,但它未必与项目无关:会话带着 + // header.cwd 时,项目页应该看得到这一行(否则项目页永远只报自己的毛病, + // 而真正让今天没写的是身份解析这一下)。读取本身再包一层——诊断面不许 + // 因为诊断自己抛错而丢掉整条记录。 + let projectRoot = null; + try { + projectRoot = projectRootOf(session); + } catch { projectRoot = null; } + record( + "agent-resolve-failed", + String((error && error.message) || error), + { + trigger: "turn-end", + // 这一刻还不知道是谁,但**这次运行确实走的是 agent 维度**(解析器在场才会 + // 进来)。不标 agentMode 的话,agent 页按 agentOnly 问总账永远问不到这一行 + // ——而那正是「连桶都没有时用户最该看到的原因」。 + agentMode: true, + sessionId: session && typeof session === "object" ? (session.id ?? null) : null, + ...(projectRoot ? { projectRoot } : {}) + }, + "diary agent resolve failed" + ); } if (resolved && resolved.agentId) { scheduleAgent(resolved.agentId, { session }); @@ -189,7 +236,9 @@ export function createDiaryAutoRun({ } } } catch (error) { - log?.warn?.("[dsh-mneme] diary timer scan failed: " + String((error && error.message) || error)); + // 运行域跟着这一轮实际扫的名单走:扫的是 agent 名单就是 agent 域。不标的话 + // agent 页按 agentOnly 问不到它,而「名单本身就炸了」恰恰是那次没写的正因。 + record("timer-scan-failed", String((error && error.message) || error), { trigger: "timer", agentMode: !!agentResolver }, "diary timer scan failed"); } arm(); }; @@ -198,7 +247,7 @@ export function createDiaryAutoRun({ if (disposed || everyMs <= 0 || ticker) return; ticker = setTimeout(() => { Promise.resolve(tick()).catch((error) => { - log?.warn?.("[dsh-mneme] diary timer tick failed: " + String((error && error.message) || error)); + record("timer-tick-failed", String((error && error.message) || error), { trigger: "timer", agentMode: !!agentResolver }, "diary timer tick failed"); }); }, everyMs); // unref:不因为一根日记的钟让宿主退不出去。 @@ -225,6 +274,7 @@ export function createDiaryAutoRun({ return Promise.all( list.map((agentId) => Promise.resolve(composer.compose({ trigger: "startup", agentMode: true, agentId })).catch((error) => { + // 与 runOne 同理:compose 出口已经记过 compose-threw,这里只留控制台。 log?.warn?.("[dsh-mneme] diary startup catch-up failed (" + agentId + "): " + String((error && error.message) || error)); return null; }) @@ -235,6 +285,7 @@ export function createDiaryAutoRun({ return Promise.all( list.map((projectRoot) => Promise.resolve(composer.compose({ trigger: "startup", projectRoot })).catch((error) => { + // 同上:compose 出口已记 compose-threw。 log?.warn?.("[dsh-mneme] diary startup catch-up failed (" + projectRoot + "): " + String((error && error.message) || error)); return null; }) diff --git a/dsh-mneme/lib/diary/compose.js b/dsh-mneme/lib/diary/compose.js index 231c66bf..e21d1e3c 100644 --- a/dsh-mneme/lib/diary/compose.js +++ b/dsh-mneme/lib/diary/compose.js @@ -27,7 +27,17 @@ import { collectQqInbox, resolveInboxDir } from "./qq-inbox.js"; import { collectSessionTranscript } from "./session-provider.js"; import { collectMemoryMaterial } from "./memory-provider.js"; import { readAgentSessions, agentSessionIds, UNNAMED_AGENT } from "./agent-bucket.js"; -import { DIARY_FILE_RE, diaryAuditPath, diaryAgentDir, diaryDir, diaryFilePath, diaryRoot, agentsRoot, isBucketName } from "./dir.js"; +import { + DIARY_FILE_RE, + diaryAuditPath, + diaryRootAuditPath, + diaryAgentDir, + diaryDir, + diaryFilePath, + diaryRoot, + agentsRoot, + isBucketName, +} from "./dir.js"; import { localDateString, shouldRollDay } from "./rollover.js"; /** 正文太短当失败:模型偶尔只回一句「今天聊了聊天」,那不是日记,落盘就是噪音。 */ @@ -68,6 +78,26 @@ function appendAudit(file, record) { appendFileSync(file, prefix + JSON.stringify(record) + "\n", "utf8"); } +/** 读一本账本(JSONL)。坏行跳过,一条坏行不拖死整份读取。读不到就是空账本。 */ +function readAuditFile(file, limit) { + let text = ""; + try { + text = readFileSync(file, "utf8"); + } catch { + return []; + } + const rows = []; + for (const line of text.split("\n")) { + if (!line.trim()) continue; + try { + rows.push(JSON.parse(line)); + } catch { + // 坏行跳过。 + } + } + return limit === undefined ? rows : rows.slice(-limit); +} + /** 目录里最新一篇的日期。用来在状态文件缺失时自愈(状态丢了不至于重写去年那篇)。 */ export function latestDiaryDate(dir) { if (!dir) return null; @@ -136,6 +166,34 @@ export function createDiaryComposer({ ctx, config, logger, service = null, setti return run; }; + /** + * 总账:与落点无关的那本(`/runs.jsonl`,见 dir.js 的 diaryRootAuditPath)。 + * + * 只在**桶内账本写不了**的地方补记:`root` 算不出来(agent-invalid / + * project-unknown)、以及 compose 自己抛异常(那条以前只进 log?.warn,而桌面端 + * 读不到控制台,用户唯一的信号是「今天又没日记」)。正常写入与 skip 仍记在桶里 + * 那本——就近可查,也避免同一次运行写两处。 + * + * 写不进去就吞掉:诊断日志不许反过来把主流程搞挂。 + */ + function recordRoot(record) { + try { + // 时间戳单独兜一层:这条路径正是「主流程已经炸了」时才走的,而炸点可能是 + // 注入的 now() 本身。诊断面不许因为同一个炸点一起消失。 + let ts = Date.now(); + try { + const at = now(); + if (at && typeof at.getTime === "function") ts = at.getTime(); + } catch { + // 退回墙钟。 + } + const file = diaryRootAuditPath({ memoryDir, configured: config?.diaryDir }); + appendAudit(file, { v: 1, ts, ...record }); + } catch { + // 诊断面失败不改判主流程。 + } + } + async function readState(root) { const file = join(root, "state.json"); try { @@ -193,6 +251,20 @@ export function createDiaryComposer({ ctx, config, logger, service = null, setti // 拒 project-not-absolute 同语义)。 const reason = agentMode ? "agent-invalid" : "project-unknown"; audit({ status: "skipped", reason }); + // #760:这里以前是**唯一什么都不留**的失败——桶不存在 ⇒ 桶内账本也算不出来 ⇒ + // audit() 静默 return。总账跟落点无关,所以这一条必须补上,否则「为什么没写」 + // 在磁盘上没有任何痕迹,只能等用户问「今天怎么没日记」。 + recordRoot({ + status: "skipped", + reason, + date: today, + trigger, + agentMode, + agentId: agentMode ? (agentId ?? null) : null, + projectRoot: projectRoot ?? null, + chatId: chatId ?? null, + sessionId: session && typeof session === "object" ? (session.id ?? null) : null, + }); return { ok: true, status: "skipped", reason, date: today }; } // stateRoot 在 root 判空之后算:root 为 null 时 join(null, "..") 会 TypeError, @@ -499,7 +571,27 @@ export function createDiaryComposer({ ctx, config, logger, service = null, setti } return { - compose: (input) => enqueue(() => compose(input)), + compose: (input) => + enqueue(() => + Promise.resolve() + .then(() => compose(input)) + .catch((error) => { + // #760:抛出来的失败以前只有调用方那行 `log?.warn`,而桌面端的 + // app.asar 读不到控制台——用户在磁盘上找不到任何痕迹。总账是唯一 + // 与落点无关的落点,所以在这里补一条再原样抛出去(不能吞:调用方 + // 还要靠这次 reject 判失败)。 + recordRoot({ + status: "failed", + reason: "compose-threw", + trigger: (input && input.trigger) || "rollover", + agentMode: Boolean(input && input.agentMode), + agentId: (input && input.agentId) ?? null, + projectRoot: (input && input.projectRoot) ?? null, + error: String((error && error.message) || error), + }); + throw error; + }) + ), knownProjects, /** * #613:agent 名单(catchUp 与定时巡检的输入)。 @@ -542,23 +634,49 @@ export function createDiaryComposer({ ctx, config, logger, service = null, setti readAudit({ projectRoot, limit = 50 } = {}) { const root = diaryDir({ memoryDir, projectRoot, configured: config?.diaryDir }); if (!root) return []; - const file = diaryAuditPath(root); - let text = ""; - try { - text = readFileSync(file, "utf8"); - } catch { - return []; - } - const rows = []; - for (const line of text.split("\n")) { - if (!line.trim()) continue; - try { - rows.push(JSON.parse(line)); - } catch { - // 坏行跳过(账本纪律:坏行不拖死整份读取)。 - } - } - return rows.slice(-limit); + return readAuditFile(diaryAuditPath(root), limit); + }, + /** + * 总账的对外写口(#760)。 + * + * 触发侧(auto.js)有三处失败根本到不了 compose:身份解析抛错、定时扫名单抛错、 + * 启动补写的 promise 被 reject。那些以前只进 `log?.warn`,而桌面端的 app.asar + * 读不到控制台——用户唯一的信号是「今天又没日记」。给一个方法而不是让 auto.js + * 自己去拼文件路径:账本格式(补换行、v/ts 字段)只该有一处实现。 + */ + noteFailure(record = {}) { + recordRoot({ status: "failed", ...record }); + }, + /** + * 只读总账里**属于这个项目**的那些行(#760)。 + * + * 面板问的是「今天为什么没有日记」,而 bucket 账本只覆盖「落点已算出」之后 + * 的失败。compose 在落点之前就抛掉的(模型炸了、注入的时钟炸了)只留在总账, + * 面板若不读它,用户看到的仍是「今天没写」四个字。 + * + * 按 projectRoot 精确过滤,不回退成「全库都给你看」——那会把别的项目的失败 + * 混进这一本的诊断里,比不显示更误导。 + */ + readRootAudit({ projectRoot, agentId, agentOnly = false, limit = 20 } = {}) { + const wantProject = String(projectRoot ?? "").trim(); + const wantAgent = String(agentId ?? "").trim(); + // 什么都不给 ⇒ 返回空,绝不退成「全库都给你看」:总账里混着所有项目与所有 + // agent 的失败,整本端出去会把别的书的诊断混进这一本,比不显示更误导。 + // `agentOnly` 是显式的第三种问法(给「我连桶都还没有」的 agent 页用): + // 只要 agent 域的行,按 agentId 分组不归并,让页面自己说「是谁没跑起来」。 + if (!wantProject && !wantAgent && !agentOnly) return []; + const file = diaryRootAuditPath({ memoryDir, configured: config?.diaryDir }); + return readAuditFile(file) + .filter((row) => { + if (!row) return false; + if (wantAgent) return String(row.agentId ?? "").trim() === wantAgent; + // #760:agent 桶没有 projectRoot(agentMode 的落点是 agents/), + // 所以 agent 页必须能按 agentId 查——否则 #758 那种「agent 桶第一天 + // 开不了张」在面板上仍然是「今天没写」四个字。 + if (agentOnly) return row.agentMode === true; + return String(row.projectRoot ?? "").trim() === wantProject; + }) + .slice(-limit); } }; } diff --git a/dsh-mneme/lib/diary/dir.js b/dsh-mneme/lib/diary/dir.js index 8ba961d2..c3d76ad2 100644 --- a/dsh-mneme/lib/diary/dir.js +++ b/dsh-mneme/lib/diary/dir.js @@ -96,3 +96,20 @@ export function diaryFilePath(dir, dateLocal) { export function diaryAuditPath(dir) { return join(dir, "runs.jsonl"); } + +/** + * **总账**:`/runs.jsonl`(与各桶内同名文件是两回事)。 + * + * 为什么还要第二本账:桶内 `runs.jsonl` 的位置由落点决定,而 #758 的三处故障里 + * 有两处**恰好是落点算不出来**——`agent-invalid`(身份丢了)与 `project-unknown` + * 时 root 为 null,于是 `auditFile` 也是 null,连那条 skip 都无处可写。现场表现 + * 就是「24 小时零写入、runs.jsonl 一行没有」,只能等用户自己发现「今天没写日记」。 + * 总账放在根上,与落点无关,所以**任何一次 compose 都至少能在这里留一行**: + * 「几点、哪次触发、因为什么没写、身份/项目是什么」。 + * + * 它记的是「跑过」,不是「写过」——正常写成功的账仍记在桶里那本(就近可查), + * 总账只补上桶那边记不到的那部分。两本账都用同一个 appendAudit 形状。 + */ +export function diaryRootAuditPath({ memoryDir, configured = "" } = {}) { + return join(diaryRoot({ memoryDir, configured }), "runs.jsonl"); +} diff --git a/dsh-mneme/lib/diary/index.js b/dsh-mneme/lib/diary/index.js index 44c79b18..e24e9b4d 100644 --- a/dsh-mneme/lib/diary/index.js +++ b/dsh-mneme/lib/diary/index.js @@ -21,7 +21,7 @@ export { collectSessionTranscript, sessionAgentId, MAX_ITEM_CHARS } from "./sess // #613:agent 维度——身份解析/落定、agents/ 桶路径、全局记忆素材。 export { settleAgent, resolveAgentId, sessionTitleOf, personaAgentNames, backfillColdSessions, readAgentSessions, UNNAMED_AGENT } from "./agent-bucket.js"; export { collectMemoryMaterial, localDayWindow, localTzOffsetMinutes } from "./memory-provider.js"; -export { diaryDir, diaryAgentDir, agentsRoot, diaryRoot, diaryFilePath, diaryAuditPath, memoryBase, expandHome, DIARY_FILE_RE } from "./dir.js"; +export { diaryDir, diaryAgentDir, agentsRoot, diaryRoot, diaryFilePath, diaryAuditPath, diaryRootAuditPath, memoryBase, expandHome, DIARY_FILE_RE } from "./dir.js"; export { localDateString, shouldRollDay, dayGap, MAX_CATCH_UP_DAYS } from "./rollover.js"; export { listDiaries, readDiary, exportDiary, EXPORT_SUBDIR } from "./export.js"; // 左侧「ta 的日记」面板读的是**跨桶**清单(它拿不到当前会话的项目), diff --git a/dsh-mneme/src/api.js b/dsh-mneme/src/api.js index 5cfdf63e..682d7276 100644 --- a/dsh-mneme/src/api.js +++ b/dsh-mneme/src/api.js @@ -56,7 +56,9 @@ import { // 桶键解析也走同一处:清单、单篇读取、路由白名单三层必须用同一道判据,否则会 // 出现「列得出来、点进去 400」——#758 就是这么坏的(`agents/` 键过不了 // 按单层目录名设计的 isBucketName)。 - listDiaryLibrary, readLibraryEntry, resolveBucketDir + listDiaryLibrary, readLibraryEntry, resolveBucketDir, + // agent 诊断口按 agentId 校验:agent 身份是单层目录名,与桶名同一把尺。 + isBucketName } from "./diary/index.js"; import { readCandidateDoc } from "./candidates.js"; // M.O. 自动沉淀:/nudge 是 pipeline-nudge.js 的第一个运行时消费者(此前它只有测试在用, @@ -3760,8 +3762,12 @@ export function createApi(ctx, service, settings, commands, embedder, semantic = try { const dir = diaryDir({ memoryDir: config.memoryDir, projectRoot: project, configured: config.diaryDir }); // 账本一起带走:面板要回答「今天为什么没有日记」时必须读它,不能靠猜。 + // #760:两本都要——桶内那本记「落点算出来之后的失败」,总账记「连落点都 + // 没算出来的那些」(compose 在落点之前抛掉)。只读前者,用户看到的仍是 + // 「今天没写」,而真正的原因一直躺在总账里没人看。 const audit = diary.readAudit({ projectRoot: project, limit: 20 }); - sendJson(res, 200, { contract: "mneme.diary/v1", project, dir, diaries: listDiaries(dir), audit }); + const rootAudit = typeof diary.readRootAudit === "function" ? diary.readRootAudit({ projectRoot: project, limit: 20 }) : []; + sendJson(res, 200, { contract: "mneme.diary/v1", project, dir, diaries: listDiaries(dir), audit, rootAudit }); } catch (error) { sendJson(res, 500, { error: "diary-unreadable", detail: String((error && error.message) || error) }); } @@ -3796,6 +3802,41 @@ export function createApi(ctx, service, settings, commands, embedder, semantic = } }); + // #760:agent 日记页的诊断口。 + // + // 为什么不能复用 `GET /diary`:那条路由第一件事就是 `diaryProject` 要 `project`, + // 而 agent 桶**没有 projectRoot**(agentMode 的落点是 `agents//`)。 + // 于是 agent 页要么传一个假 project(读到的全是别人的账),要么根本读不到—— + // 而 #758 出事的恰恰就是 agent 桶第一天开不了张。按 agentId 单独给一个口, + // 页面才可能在「一篇都没有」的时候说清「一次都没跑起来」还是「跑了但没写」。 + register({ + kind: "exact", + path: "/api/dsh-mneme/diary/agent-audit", + policy: "open", + handler(req, res) { + if (!diaryGate(req, res)) return; + const agentId = new URL(req.url, "http://localhost").searchParams.get("agent"); + // 不给 agent 是**合法**的第三种问法:agent 桶一个都还没建起来时(#758 现场 + // 就是 `diaries/agents/` 下只有 sessions.json),页面连一本书都列不出来, + // 也就拿不到 agentId。那时候要回答的正是「一次都没跑起来,为什么」。 + if (agentId !== null && agentId !== "" && !isBucketName(agentId)) { + sendJson(res, 400, { error: "agent-invalid", detail: agentId }); + return; + } + try { + const query = agentId === null || agentId === "" + ? { agentOnly: true, limit: 20 } + : { agentId, limit: 20 }; + const rootAudit = typeof diary.readRootAudit === "function" + ? diary.readRootAudit(query) + : []; + sendJson(res, 200, { contract: "mneme.diary/v1", agent: agentId || null, rootAudit }); + } catch (error) { + sendJson(res, 500, { error: "diary-unreadable", detail: String((error && error.message) || error) }); + } + } + }); + register({ kind: "exact", path: "/api/dsh-mneme/diary/compose", diff --git a/dsh-mneme/src/diary/auto.js b/dsh-mneme/src/diary/auto.js index 9204a666..9a6139d3 100644 --- a/dsh-mneme/src/diary/auto.js +++ b/dsh-mneme/src/diary/auto.js @@ -33,6 +33,29 @@ export function createDiaryAutoRun({ listAgents = null } = {}) { const log = logger || (ctx && ctx.logger) || null; + /** + * #760:把一处失败同时写进控制台与**磁盘总账**。 + * + * 为什么要两条腿:`log?.warn` 在桌面端等于没写——app.asar 里的插件控制台没人 + * 看得到,`%APPDATA%` 下只有 10 月的 crash 日志(#758 报告人的原话)。这次故障 + * 的实际信号是「用户自己发现今天没日记」,而那一刻离出事已经隔了一天。 + * + * 只用 composer.noteFailure 一个口子,不给 auto.js 拼账本路径的理由:账本格式 + * (补换行、v/ts 字段)只该有一处实现。composer 缺席(旧接线/测试桩)就只剩 warn, + * 与改动前逐字节相同。 + */ + const record = (reason, detail, extra = {}, logText = null) => { + // 控制台那句沿用改动前的措辞(旧日志、旧测试都按它搜),账本里用 kebab 的 + // reason——两个面服务两种读法,没必要为了统一把既有的 grep 习惯改掉。 + log?.warn?.("[dsh-mneme] " + (logText || reason) + ": " + detail); + try { + if (composer && typeof composer.noteFailure === "function") { + composer.noteFailure({ reason, detail, ...extra }); + } + } catch { + // 诊断面失败不许反过来打断派发链。 + } + }; let disposed = false; let timer = null; /** 定时写的钟。与 timer(setTimeout(0) 的派发器)是两回事:那个只把待判项目挪到下一帧。 */ @@ -77,6 +100,9 @@ export function createDiaryAutoRun({ // compose 是异步的(要等模型),绝不能返回给 session/event 的派发方去 await—— // 那会把回合收尾吊在模型延迟上(本机实测 p90 五十秒级)。 return Promise.resolve(task).catch((error) => { + // 这里**不**再记总账:compose 自己的出口已经写了 compose-threw(#760), + // 同一次失败记两行会让「跑过几次」失去意义。控制台的 warn 保留——两条腿 + // 各自服务不同的读法。 log?.warn?.("[dsh-mneme] diary compose failed (" + key + "): " + String((error && error.message) || error)); return null; }); @@ -136,7 +162,28 @@ export function createDiaryAutoRun({ try { resolved = agentResolver(session); } catch (error) { - log?.warn?.("[dsh-mneme] diary agent resolve failed: " + String((error && error.message) || error)); + // 这条失败发生在「还不知道身份」的时候,但它未必与项目无关:会话带着 + // header.cwd 时,项目页应该看得到这一行(否则项目页永远只报自己的毛病, + // 而真正让今天没写的是身份解析这一下)。读取本身再包一层——诊断面不许 + // 因为诊断自己抛错而丢掉整条记录。 + let projectRoot = null; + try { + projectRoot = projectRootOf(session); + } catch { projectRoot = null; } + record( + "agent-resolve-failed", + String((error && error.message) || error), + { + trigger: "turn-end", + // 这一刻还不知道是谁,但**这次运行确实走的是 agent 维度**(解析器在场才会 + // 进来)。不标 agentMode 的话,agent 页按 agentOnly 问总账永远问不到这一行 + // ——而那正是「连桶都没有时用户最该看到的原因」。 + agentMode: true, + sessionId: session && typeof session === "object" ? (session.id ?? null) : null, + ...(projectRoot ? { projectRoot } : {}) + }, + "diary agent resolve failed" + ); } if (resolved && resolved.agentId) { scheduleAgent(resolved.agentId, { session }); @@ -189,7 +236,9 @@ export function createDiaryAutoRun({ } } } catch (error) { - log?.warn?.("[dsh-mneme] diary timer scan failed: " + String((error && error.message) || error)); + // 运行域跟着这一轮实际扫的名单走:扫的是 agent 名单就是 agent 域。不标的话 + // agent 页按 agentOnly 问不到它,而「名单本身就炸了」恰恰是那次没写的正因。 + record("timer-scan-failed", String((error && error.message) || error), { trigger: "timer", agentMode: !!agentResolver }, "diary timer scan failed"); } arm(); }; @@ -198,7 +247,7 @@ export function createDiaryAutoRun({ if (disposed || everyMs <= 0 || ticker) return; ticker = setTimeout(() => { Promise.resolve(tick()).catch((error) => { - log?.warn?.("[dsh-mneme] diary timer tick failed: " + String((error && error.message) || error)); + record("timer-tick-failed", String((error && error.message) || error), { trigger: "timer", agentMode: !!agentResolver }, "diary timer tick failed"); }); }, everyMs); // unref:不因为一根日记的钟让宿主退不出去。 @@ -225,6 +274,7 @@ export function createDiaryAutoRun({ return Promise.all( list.map((agentId) => Promise.resolve(composer.compose({ trigger: "startup", agentMode: true, agentId })).catch((error) => { + // 与 runOne 同理:compose 出口已经记过 compose-threw,这里只留控制台。 log?.warn?.("[dsh-mneme] diary startup catch-up failed (" + agentId + "): " + String((error && error.message) || error)); return null; }) @@ -235,6 +285,7 @@ export function createDiaryAutoRun({ return Promise.all( list.map((projectRoot) => Promise.resolve(composer.compose({ trigger: "startup", projectRoot })).catch((error) => { + // 同上:compose 出口已记 compose-threw。 log?.warn?.("[dsh-mneme] diary startup catch-up failed (" + projectRoot + "): " + String((error && error.message) || error)); return null; }) diff --git a/dsh-mneme/src/diary/compose.js b/dsh-mneme/src/diary/compose.js index 231c66bf..e21d1e3c 100644 --- a/dsh-mneme/src/diary/compose.js +++ b/dsh-mneme/src/diary/compose.js @@ -27,7 +27,17 @@ import { collectQqInbox, resolveInboxDir } from "./qq-inbox.js"; import { collectSessionTranscript } from "./session-provider.js"; import { collectMemoryMaterial } from "./memory-provider.js"; import { readAgentSessions, agentSessionIds, UNNAMED_AGENT } from "./agent-bucket.js"; -import { DIARY_FILE_RE, diaryAuditPath, diaryAgentDir, diaryDir, diaryFilePath, diaryRoot, agentsRoot, isBucketName } from "./dir.js"; +import { + DIARY_FILE_RE, + diaryAuditPath, + diaryRootAuditPath, + diaryAgentDir, + diaryDir, + diaryFilePath, + diaryRoot, + agentsRoot, + isBucketName, +} from "./dir.js"; import { localDateString, shouldRollDay } from "./rollover.js"; /** 正文太短当失败:模型偶尔只回一句「今天聊了聊天」,那不是日记,落盘就是噪音。 */ @@ -68,6 +78,26 @@ function appendAudit(file, record) { appendFileSync(file, prefix + JSON.stringify(record) + "\n", "utf8"); } +/** 读一本账本(JSONL)。坏行跳过,一条坏行不拖死整份读取。读不到就是空账本。 */ +function readAuditFile(file, limit) { + let text = ""; + try { + text = readFileSync(file, "utf8"); + } catch { + return []; + } + const rows = []; + for (const line of text.split("\n")) { + if (!line.trim()) continue; + try { + rows.push(JSON.parse(line)); + } catch { + // 坏行跳过。 + } + } + return limit === undefined ? rows : rows.slice(-limit); +} + /** 目录里最新一篇的日期。用来在状态文件缺失时自愈(状态丢了不至于重写去年那篇)。 */ export function latestDiaryDate(dir) { if (!dir) return null; @@ -136,6 +166,34 @@ export function createDiaryComposer({ ctx, config, logger, service = null, setti return run; }; + /** + * 总账:与落点无关的那本(`/runs.jsonl`,见 dir.js 的 diaryRootAuditPath)。 + * + * 只在**桶内账本写不了**的地方补记:`root` 算不出来(agent-invalid / + * project-unknown)、以及 compose 自己抛异常(那条以前只进 log?.warn,而桌面端 + * 读不到控制台,用户唯一的信号是「今天又没日记」)。正常写入与 skip 仍记在桶里 + * 那本——就近可查,也避免同一次运行写两处。 + * + * 写不进去就吞掉:诊断日志不许反过来把主流程搞挂。 + */ + function recordRoot(record) { + try { + // 时间戳单独兜一层:这条路径正是「主流程已经炸了」时才走的,而炸点可能是 + // 注入的 now() 本身。诊断面不许因为同一个炸点一起消失。 + let ts = Date.now(); + try { + const at = now(); + if (at && typeof at.getTime === "function") ts = at.getTime(); + } catch { + // 退回墙钟。 + } + const file = diaryRootAuditPath({ memoryDir, configured: config?.diaryDir }); + appendAudit(file, { v: 1, ts, ...record }); + } catch { + // 诊断面失败不改判主流程。 + } + } + async function readState(root) { const file = join(root, "state.json"); try { @@ -193,6 +251,20 @@ export function createDiaryComposer({ ctx, config, logger, service = null, setti // 拒 project-not-absolute 同语义)。 const reason = agentMode ? "agent-invalid" : "project-unknown"; audit({ status: "skipped", reason }); + // #760:这里以前是**唯一什么都不留**的失败——桶不存在 ⇒ 桶内账本也算不出来 ⇒ + // audit() 静默 return。总账跟落点无关,所以这一条必须补上,否则「为什么没写」 + // 在磁盘上没有任何痕迹,只能等用户问「今天怎么没日记」。 + recordRoot({ + status: "skipped", + reason, + date: today, + trigger, + agentMode, + agentId: agentMode ? (agentId ?? null) : null, + projectRoot: projectRoot ?? null, + chatId: chatId ?? null, + sessionId: session && typeof session === "object" ? (session.id ?? null) : null, + }); return { ok: true, status: "skipped", reason, date: today }; } // stateRoot 在 root 判空之后算:root 为 null 时 join(null, "..") 会 TypeError, @@ -499,7 +571,27 @@ export function createDiaryComposer({ ctx, config, logger, service = null, setti } return { - compose: (input) => enqueue(() => compose(input)), + compose: (input) => + enqueue(() => + Promise.resolve() + .then(() => compose(input)) + .catch((error) => { + // #760:抛出来的失败以前只有调用方那行 `log?.warn`,而桌面端的 + // app.asar 读不到控制台——用户在磁盘上找不到任何痕迹。总账是唯一 + // 与落点无关的落点,所以在这里补一条再原样抛出去(不能吞:调用方 + // 还要靠这次 reject 判失败)。 + recordRoot({ + status: "failed", + reason: "compose-threw", + trigger: (input && input.trigger) || "rollover", + agentMode: Boolean(input && input.agentMode), + agentId: (input && input.agentId) ?? null, + projectRoot: (input && input.projectRoot) ?? null, + error: String((error && error.message) || error), + }); + throw error; + }) + ), knownProjects, /** * #613:agent 名单(catchUp 与定时巡检的输入)。 @@ -542,23 +634,49 @@ export function createDiaryComposer({ ctx, config, logger, service = null, setti readAudit({ projectRoot, limit = 50 } = {}) { const root = diaryDir({ memoryDir, projectRoot, configured: config?.diaryDir }); if (!root) return []; - const file = diaryAuditPath(root); - let text = ""; - try { - text = readFileSync(file, "utf8"); - } catch { - return []; - } - const rows = []; - for (const line of text.split("\n")) { - if (!line.trim()) continue; - try { - rows.push(JSON.parse(line)); - } catch { - // 坏行跳过(账本纪律:坏行不拖死整份读取)。 - } - } - return rows.slice(-limit); + return readAuditFile(diaryAuditPath(root), limit); + }, + /** + * 总账的对外写口(#760)。 + * + * 触发侧(auto.js)有三处失败根本到不了 compose:身份解析抛错、定时扫名单抛错、 + * 启动补写的 promise 被 reject。那些以前只进 `log?.warn`,而桌面端的 app.asar + * 读不到控制台——用户唯一的信号是「今天又没日记」。给一个方法而不是让 auto.js + * 自己去拼文件路径:账本格式(补换行、v/ts 字段)只该有一处实现。 + */ + noteFailure(record = {}) { + recordRoot({ status: "failed", ...record }); + }, + /** + * 只读总账里**属于这个项目**的那些行(#760)。 + * + * 面板问的是「今天为什么没有日记」,而 bucket 账本只覆盖「落点已算出」之后 + * 的失败。compose 在落点之前就抛掉的(模型炸了、注入的时钟炸了)只留在总账, + * 面板若不读它,用户看到的仍是「今天没写」四个字。 + * + * 按 projectRoot 精确过滤,不回退成「全库都给你看」——那会把别的项目的失败 + * 混进这一本的诊断里,比不显示更误导。 + */ + readRootAudit({ projectRoot, agentId, agentOnly = false, limit = 20 } = {}) { + const wantProject = String(projectRoot ?? "").trim(); + const wantAgent = String(agentId ?? "").trim(); + // 什么都不给 ⇒ 返回空,绝不退成「全库都给你看」:总账里混着所有项目与所有 + // agent 的失败,整本端出去会把别的书的诊断混进这一本,比不显示更误导。 + // `agentOnly` 是显式的第三种问法(给「我连桶都还没有」的 agent 页用): + // 只要 agent 域的行,按 agentId 分组不归并,让页面自己说「是谁没跑起来」。 + if (!wantProject && !wantAgent && !agentOnly) return []; + const file = diaryRootAuditPath({ memoryDir, configured: config?.diaryDir }); + return readAuditFile(file) + .filter((row) => { + if (!row) return false; + if (wantAgent) return String(row.agentId ?? "").trim() === wantAgent; + // #760:agent 桶没有 projectRoot(agentMode 的落点是 agents/), + // 所以 agent 页必须能按 agentId 查——否则 #758 那种「agent 桶第一天 + // 开不了张」在面板上仍然是「今天没写」四个字。 + if (agentOnly) return row.agentMode === true; + return String(row.projectRoot ?? "").trim() === wantProject; + }) + .slice(-limit); } }; } diff --git a/dsh-mneme/src/diary/dir.js b/dsh-mneme/src/diary/dir.js index 8ba961d2..c3d76ad2 100644 --- a/dsh-mneme/src/diary/dir.js +++ b/dsh-mneme/src/diary/dir.js @@ -96,3 +96,20 @@ export function diaryFilePath(dir, dateLocal) { export function diaryAuditPath(dir) { return join(dir, "runs.jsonl"); } + +/** + * **总账**:`/runs.jsonl`(与各桶内同名文件是两回事)。 + * + * 为什么还要第二本账:桶内 `runs.jsonl` 的位置由落点决定,而 #758 的三处故障里 + * 有两处**恰好是落点算不出来**——`agent-invalid`(身份丢了)与 `project-unknown` + * 时 root 为 null,于是 `auditFile` 也是 null,连那条 skip 都无处可写。现场表现 + * 就是「24 小时零写入、runs.jsonl 一行没有」,只能等用户自己发现「今天没写日记」。 + * 总账放在根上,与落点无关,所以**任何一次 compose 都至少能在这里留一行**: + * 「几点、哪次触发、因为什么没写、身份/项目是什么」。 + * + * 它记的是「跑过」,不是「写过」——正常写成功的账仍记在桶里那本(就近可查), + * 总账只补上桶那边记不到的那部分。两本账都用同一个 appendAudit 形状。 + */ +export function diaryRootAuditPath({ memoryDir, configured = "" } = {}) { + return join(diaryRoot({ memoryDir, configured }), "runs.jsonl"); +} diff --git a/dsh-mneme/src/diary/index.js b/dsh-mneme/src/diary/index.js index 44c79b18..e24e9b4d 100644 --- a/dsh-mneme/src/diary/index.js +++ b/dsh-mneme/src/diary/index.js @@ -21,7 +21,7 @@ export { collectSessionTranscript, sessionAgentId, MAX_ITEM_CHARS } from "./sess // #613:agent 维度——身份解析/落定、agents/ 桶路径、全局记忆素材。 export { settleAgent, resolveAgentId, sessionTitleOf, personaAgentNames, backfillColdSessions, readAgentSessions, UNNAMED_AGENT } from "./agent-bucket.js"; export { collectMemoryMaterial, localDayWindow, localTzOffsetMinutes } from "./memory-provider.js"; -export { diaryDir, diaryAgentDir, agentsRoot, diaryRoot, diaryFilePath, diaryAuditPath, memoryBase, expandHome, DIARY_FILE_RE } from "./dir.js"; +export { diaryDir, diaryAgentDir, agentsRoot, diaryRoot, diaryFilePath, diaryAuditPath, diaryRootAuditPath, memoryBase, expandHome, DIARY_FILE_RE } from "./dir.js"; export { localDateString, shouldRollDay, dayGap, MAX_CATCH_UP_DAYS } from "./rollover.js"; export { listDiaries, readDiary, exportDiary, EXPORT_SUBDIR } from "./export.js"; // 左侧「ta 的日记」面板读的是**跨桶**清单(它拿不到当前会话的项目), diff --git a/dsh-mneme/test/api.test.js b/dsh-mneme/test/api.test.js index 81f9e579..547c3080 100644 --- a/dsh-mneme/test/api.test.js +++ b/dsh-mneme/test/api.test.js @@ -3024,6 +3024,86 @@ test("#758 agent 桶键:多级或越界的 agents/ 键仍然回 400", async (t } }); +// --- #760:面板要能看到「连落点都没算出来」的失败 --------------------------- +// 桶内账本只覆盖「落点已算出之后」的失败。compose 在落点之前炸掉的那些(模型、 +// 注入的时钟、身份解析)只留在总账里;接口若不把它带出去,用户看到的仍是 +// 「今天没写」四个字,而原因一直躺在磁盘上没人读。 + +test("#760 GET /diary 把总账一起带出去(rootAudit)", async () => { + const project = portableProjectRoot(); + const rows = [{ v: 1, ts: 1_763_000_000_000, status: "failed", reason: "compose-threw", detail: "clock exploded" }]; + const seen = []; + const diary = { + readAudit: (args) => { seen.push(["bucket", args]); return [{ date: "2026-11-08", status: "skipped", reason: "no-material" }]; }, + readRootAudit: (args) => { seen.push(["root", args]); return rows; } + }; + const { routes } = setupDiary({ diaryEnabled: true }, diary); + const res = new FakeRes(); + await findHandler(routes, "/api/dsh-mneme/diary").handler(req("/api/dsh-mneme/diary?project=" + encodeURIComponent(project)), res); + assert.equal(res.statusCode, 200); + const data = JSON.parse(res.body); + assert.deepEqual(data.rootAudit, rows, "总账的行必须原样到面板"); + assert.equal(data.audit.length, 1, "桶内账本照旧带一份"); + // 两本账都按同一个项目问,且都带着 limit——不给项目就会退成「全库都给你看」。 + assert.equal(seen.length, 2); + for (const [kind, args] of seen) { + assert.equal(args.projectRoot, project, `${kind} 账本必须按项目过滤`); + assert.equal(args.limit, 20); + } +}); + +test("#760 老 composer 没有 readRootAudit 时退回空数组,不 500", async () => { + const project = portableProjectRoot(); + // 旧接线/桩只实现 readAudit:接口必须当「没有总账」处理,而不是炸成 500。 + const { routes } = setupDiary({ diaryEnabled: true }, { readAudit: () => [] }); + const res = new FakeRes(); + await findHandler(routes, "/api/dsh-mneme/diary").handler(req("/api/dsh-mneme/diary?project=" + encodeURIComponent(project)), res); + assert.equal(res.statusCode, 200); + assert.deepEqual(JSON.parse(res.body).rootAudit, []); +}); + +test("#760 agent 日记页按 agentId 问总账,不给 agent 时问「agent 域全部」", async () => { + // agent 桶没有 projectRoot(落点是 agents//),所以它读不了 /diary + // ——那条路由第一件事就是要 project。#758 出事的正是这一页:书一本都没有, + // agentId 也就拿不到,页面连问都不知道问谁。所以「不带 agent」必须是合法问法。 + const seen = []; + const diary = { + readAudit: () => [], + readRootAudit: (args) => { seen.push(args); return []; } + }; + const { routes } = setupDiary({ diaryEnabled: true }, diary); + const route = findHandler(routes, "/api/dsh-mneme/diary/agent-audit"); + + const one = new FakeRes(); + await route.handler(req("/api/dsh-mneme/diary/agent-audit?agent=standard"), one); + assert.equal(one.statusCode, 200); + assert.equal(JSON.parse(one.body).agent, "standard"); + + const all = new FakeRes(); + await route.handler(req("/api/dsh-mneme/diary/agent-audit"), all); + assert.equal(all.statusCode, 200, "一本都没有时也要能问,那是「一次都没跑起来」"); + assert.equal(JSON.parse(all.body).agent, null); + + assert.deepEqual(seen[0], { agentId: "standard", limit: 20 }); + assert.deepEqual(seen[1], { agentOnly: true, limit: 20 }); +}); + +test("#760 agent-audit 拒绝路径语义的 agent 名,老 composer 退回空数组", async () => { + const { routes } = setupDiary({ diaryEnabled: true }, { readAudit: () => [] }); + const route = findHandler(routes, "/api/dsh-mneme/diary/agent-audit"); + // agent 名是单层目录名:带分隔符/上跳的一律 400,绝不让它拼进路径。 + for (const bad of ["a/b", "..", "x/../y"]) { + const res = new FakeRes(); + await route.handler(req("/api/dsh-mneme/diary/agent-audit?agent=" + encodeURIComponent(bad)), res); + assert.equal(res.statusCode, 400, `agent 名 ${JSON.stringify(bad)} 该回 400`); + assert.equal(JSON.parse(res.body).error, "agent-invalid"); + } + const ok = new FakeRes(); + await route.handler(req("/api/dsh-mneme/diary/agent-audit?agent=standard"), ok); + assert.equal(ok.statusCode, 200, "旧 composer 没有 readRootAudit 时不许 500"); + assert.deepEqual(JSON.parse(ok.body).rootAudit, []); +}); + // --- 手动写日记必须带身份(「设定好人格的 agent 只以这个人格的口吻写日记」)----- // 自动轮(src/diary/auto.js:47)一直传 agentId,手动轮的 /diary/compose 却不传, // 于是永远落 default 人格卡:同一天从两个入口写,是两张卡的两种声音。 diff --git a/dsh-mneme/test/diary.test.js b/dsh-mneme/test/diary.test.js index 7c238566..86195cf0 100644 --- a/dsh-mneme/test/diary.test.js +++ b/dsh-mneme/test/diary.test.js @@ -12,7 +12,7 @@ import { homedir, tmpdir } from "node:os"; import { join } from "node:path"; import { localDateString, shouldRollDay, dayGap, MAX_CATCH_UP_DAYS } from "../src/diary/rollover.js"; -import { diaryDir, diaryFilePath, expandHome, memoryBase } from "../src/diary/dir.js"; +import { diaryDir, diaryFilePath, diaryRootAuditPath, expandHome, memoryBase } from "../src/diary/dir.js"; import { resolveMemoryDir } from "../src/paths.js"; import { collectQqInbox, inboxFiles, redactDigits, resolveInboxDir, textOf, isEffective } from "../src/diary/qq-inbox.js"; import { collectSessionTranscript, sessionAgentId } from "../src/diary/session-provider.js"; @@ -30,6 +30,24 @@ function fresh(name) { return dir; } +/** + * 读**总账**(`/runs.jsonl`):桶内账本的兜底,专门记「连桶都没有」的那些失败。 + * 读不出来就当空账本——账本是诊断面,不该让测试因为文件不存在而报错。 + */ +function readAuditFile(composer, memoryDir) { + const file = diaryRootAuditPath({ memoryDir }); + let text = ""; + try { + text = readFileSync(file, "utf8"); + } catch { + return []; + } + return text + .split("\n") + .filter((line) => line.trim()) + .map((line) => JSON.parse(line)); +} + test("localDateString 用本地时区,不是 UTC", () => { // 本地 00:30 这条边界是整件事的核心:用 UTC 会让北京时间早上 8 点前写的日记 // 落进「昨天」,跨天判定跟着错一天。 @@ -235,15 +253,96 @@ function fakeCtx({ body = "今天聊了很久,她说想早点睡,还说明 }; } -test("compose:项目根为空 → skip project-unknown,一个文件都不写", async () => { +test("compose:项目根为空 → skip project-unknown,不建任何桶,但总账要留一行", async () => { const memoryDir = fresh("compose-unknown"); const { ctx } = fakeCtx(); const composer = createDiaryComposer({ ctx, config: { diaryEnabled: true, language: "zh" }, memoryDir, settings: null, now: () => new Date(2026, 10, 7, 10) }); const result = await composer.compose({ trigger: "rollover", projectRoot: "" }); assert.equal(result.status, "skipped"); assert.equal(result.reason, "project-unknown"); - // 关键反向断言:memoryDir 下不该出现 diaries 目录之外的任何东西。 - assert.deepEqual(readdirSync(memoryDir), []); + // 反向断言不变:不许有桶、不许有日记正文(项目未知时落盘就是泄漏)。 + assert.deepEqual(readdirSync(memoryDir), ["diaries"]); + assert.deepEqual(readdirSync(join(memoryDir, "diaries")), ["runs.jsonl"]); + // #760:这一条以前**一个字节都不留**——桶不存在 ⇒ 桶内账本算不出来 ⇒ 连 skip + // 都无处写。现场表现就是「24 小时零写入、runs.jsonl 一行没有」,只能等用户 + // 自己发现「今天怎么没日记」。总账与落点无关,所以它必须在这里有一行。 + const rows = readAuditFile(composer, memoryDir); + assert.equal(rows.length, 1); + assert.equal(rows[0].status, "skipped"); + assert.equal(rows[0].reason, "project-unknown"); + assert.equal(rows[0].trigger, "rollover"); + assert.equal(rows[0].agentMode, false); +}); + +test("compose:agentId 不合法 → skip agent-invalid,同样在总账留痕", async () => { + const memoryDir = fresh("compose-agent-invalid"); + const { ctx } = fakeCtx(); + const composer = createDiaryComposer({ ctx, config: { diaryEnabled: true, language: "zh" }, memoryDir, settings: null, now: () => new Date(2026, 10, 7, 10) }); + for (const bad of ["../escape", "a/b", "", "."]) { + const result = await composer.compose({ trigger: "rollover", projectRoot: "D:\\proj", agentMode: true, agentId: bad }); + assert.equal(result.reason, "agent-invalid", "身份不合法必须是 agent-invalid,不许退成别的桶"); + } + const rows = readAuditFile(composer, memoryDir); + assert.equal(rows.length, 4); + for (const row of rows) { + assert.equal(row.reason, "agent-invalid"); + assert.equal(row.agentMode, true); + } + // 身份再怪也不许在 agents/ 下冒出目录。 + assert.equal(existsSync(join(memoryDir, "diaries", "agents")), false); +}); + +test("compose:正常写入的一次不往总账重复记", async () => { + const memoryDir = fresh("compose-root-mirror"); + const inboxDir = fresh("root-mirror-inbox"); + writeInbox(inboxDir, [frameOf({ ts: new Date(2026, 10, 7, 9).getTime(), text: "早" })]); + const { ctx } = fakeCtx(); + const composer = createDiaryComposer({ + ctx, + config: { diaryEnabled: true, language: "zh", diaryInboxDir: inboxDir }, + memoryDir, + settings: null, + now: () => new Date(2026, 10, 7, 20) + }); + const done = await composer.compose({ trigger: "rollover", projectRoot: "D:\\proj-mirror" }); + assert.equal(done.status, "written"); + // 写成的那本账在桶里(就近可查),总账退回「桶那边够用」的定位——同一次运行 + // 写两处会让「跑过」和「写过」混成一种信号。 + assert.equal(existsSync(join(memoryDir, "diaries", "runs.jsonl")), false); + const audit = composer.readAudit({ projectRoot: "D:\\proj-mirror" }); + assert.equal(audit.filter((r) => r.status === "written").length, 1); +}); + +test("compose:compose 自己抛异常 → 总账记 failed 再把异常原样抛出去", async () => { + const memoryDir = fresh("compose-throws"); + const boom = new Error("clock exploded"); + const composer = createDiaryComposer({ + ctx: fakeCtx().ctx, + config: { diaryEnabled: true, language: "zh" }, + memoryDir, + settings: null, + // 真实世界里能穿透 compose 的炸点很少(模型失败、素材读不到都在内部兜成 skip/ + // failed 了),所以这里挑一个**确实会冒到调用方**的位置:入口第一行的 now()。 + // 这正是那种「只进 log.warn、磁盘上一个字节都没有」的失败。 + now: () => { + throw boom; + } + }); + await assert.rejects( + () => composer.compose({ trigger: "rollover", projectRoot: "D:\\proj-throws" }), + (error) => { + assert.match(String(error && error.message), /clock exploded/); + return true; + } + ); + const rows = readAuditFile(composer, memoryDir); + const failed = rows.filter((r) => r.status === "failed" && r.reason === "compose-threw"); + assert.equal(failed.length, 1, "抛出过一次就必须在总账留一行"); + assert.match(failed[0].error, /clock exploded/); + assert.equal(failed[0].trigger, "rollover"); + assert.equal(failed[0].projectRoot, "D:\\proj-throws"); + // now() 本身炸了也要有时间戳(否则这一行长什么样取决于哪个注入函数先坏)。 + assert.equal(typeof failed[0].ts, "number"); }); test("compose:当天零条有效消息 → skip no-material,且绝不调模型", async () => { @@ -642,6 +741,164 @@ test("auto:listProjects 抛错不冒泡到定时器(只 warn)", async () = auto(); }); +test("auto:触发侧的失败除了 warn 还要进总账(#760)", async () => { + const { ctx } = autoCtx(); + const notes = []; + const composer = { + compose: async () => ({ status: "written" }), + noteFailure: (row) => notes.push(row) + }; + const auto = createDiaryAutoRun({ + ctx, + composer, + everyMs: 60 * 60 * 1000, + listProjects: () => { throw new Error("state file gone"); } + }); + await auto.tickNow(); + assert.equal(notes.length, 1, "定时扫名单炸了必须留一行,不能只进控制台"); + assert.equal(notes[0].reason, "timer-scan-failed"); + assert.equal(notes[0].trigger, "timer"); + assert.match(notes[0].detail, /state file gone/); + auto(); + + // 身份解析在 turn/end 里炸:这条以前只能 warn,桌面端等于没写。 + const notes2 = []; + const ctx2 = autoCtx(); + const auto2 = createDiaryAutoRun({ + ctx: ctx2.ctx, + composer: { compose: async () => ({ status: "written" }), noteFailure: (row) => notes2.push(row) }, + agentResolver: () => { throw new Error("persona card unreadable"); } + }); + const fn = ctx2.handlers.get("session/event"); + assert.ok(fn, "auto 必须注册 session/event"); + fn({ id: "s-1" }, { type: "turn/end" }); + assert.equal(notes2.length, 1); + assert.equal(notes2[0].reason, "agent-resolve-failed"); + assert.equal(notes2[0].sessionId, "s-1"); + assert.match(notes2[0].detail, /persona card unreadable/); + auto2(); +}); + +test("auto:身份解析失败的那行也带上 projectRoot,项目页才找得到它", () => { + // 身份解析失败发生在「还不知道身份」的时候,但它未必与项目无关:会话带着 + // header.cwd 时,真正让今天没写的就是这一下。不带 projectRoot,项目页按 + // 路径过滤就永远看不见它。 + const notes = []; + const { ctx, handlers } = autoCtx(); + const auto = createDiaryAutoRun({ + ctx, + composer: { compose: async () => ({ status: "written" }), noteFailure: (row) => notes.push(row) }, + agentResolver: () => { throw new Error("persona card unreadable"); } + }); + const fn = handlers.get("session/event"); + fn({ id: "s-2", header: { cwd: "/work/a" } }, { type: "turn/end" }); + assert.equal(notes.length, 1); + assert.equal(notes[0].reason, "agent-resolve-failed"); + assert.equal(notes[0].projectRoot, "/work/a"); + // 走的是 agent 维度(解析器在场才会进这个分支),运行域必须标上——否则 agent 页 + // 按 agentOnly 问总账永远问不到这一行,而那正是「连桶都没有时最该看到的原因」。 + assert.equal(notes[0].agentMode, true); + + // 没有 cwd 的会话不许硬填一个假路径:宁缺,别把失败记到别人项目头上。 + fn({ id: "s-3" }, { type: "turn/end" }); + assert.equal(notes.length, 2); + assert.equal(Object.prototype.hasOwnProperty.call(notes[1], "projectRoot"), false); + auto(); +}); + +test("auto:定时扫名单炸了时,若扫的是 agent 名单就标 agent 域", async () => { + const notes = []; + const { ctx } = autoCtx(); + const auto = createDiaryAutoRun({ + ctx, + composer: { compose: async () => ({ status: "written" }), noteFailure: (row) => notes.push(row) }, + everyMs: 60 * 60 * 1000, + agentResolver: () => null, + listAgents: () => { throw new Error("sessions.json unreadable"); } + }); + await auto.tickNow(); + auto(); + assert.equal(notes.length, 1); + assert.equal(notes[0].reason, "timer-scan-failed"); + assert.equal(notes[0].agentMode, true, "扫的是 agent 名单,就得能让 agent 页问得到"); +}); + +test("auto:真实触发失败能被 readRootAudit({ agentOnly }) 读回(#760 回归)", async () => { + // 桩 composer 验的是「传了什么」,这条验的是「落盘之后按 agent 域问得到」—— + // #758 现场就是「页面问 agent 域,总账里那一行不在 agent 域里」。 + const memoryDir = fresh("root-audit-agentonly"); + const composer = createDiaryComposer({ + ctx: fakeCtx().ctx, + config: { diaryEnabled: true, language: "zh" }, + memoryDir, + settings: null, + now: () => new Date(2026, 10, 7, 10) + }); + const { ctx, handlers } = autoCtx(); + const auto = createDiaryAutoRun({ + ctx, + composer, + agentResolver: () => { throw new Error("persona card unreadable"); } + }); + handlers.get("session/event")({ id: "s-9" }, { type: "turn/end" }); + auto(); + // 会话没有任何 cwd:项目查询本来就不该命中它,agent 域必须命中。 + assert.deepEqual(composer.readRootAudit({ projectRoot: "/work/a" }), []); + const rows = composer.readRootAudit({ agentOnly: true }); + assert.equal(rows.length, 1); + assert.equal(rows[0].reason, "agent-resolve-failed"); + assert.equal(rows[0].sessionId, "s-9"); +}); + +test("compose:readRootAudit 按 projectRoot 读得回身份解析那种失败", async () => { + const memoryDir = fresh("root-audit-projectroot"); + const composer = createDiaryComposer({ + ctx: fakeCtx().ctx, + config: { diaryEnabled: true, language: "zh" }, + memoryDir, + settings: null, + now: () => new Date(2026, 10, 7, 10) + }); + composer.noteFailure({ + reason: "agent-resolve-failed", + detail: "persona card unreadable", + trigger: "turn-end", + agentMode: true, + projectRoot: "/work/a" + }); + composer.noteFailure({ + reason: "agent-resolve-failed", + detail: "another project", + trigger: "turn-end", + agentMode: true, + projectRoot: "/work/b" + }); + const mine = composer.readRootAudit({ projectRoot: "/work/a" }); + assert.equal(mine.length, 1); + assert.equal(mine[0].reason, "agent-resolve-failed"); + assert.equal(mine[0].projectRoot, "/work/a"); + // 别人的失败不该出现在我这个项目的页上。 + assert.ok(mine.every((row) => row.projectRoot === "/work/a")); + // 什么都不问就是什么都不给:绝不退成「全库都给你看」。 + assert.deepEqual(composer.readRootAudit(), []); +}); + +test("auto:composer 没有 noteFailure 时退回「只 warn」(旧接线不改行为)", async () => { + const { ctx } = autoCtx(); + const warns = []; + ctx.logger.warn = (msg) => warns.push(String(msg)); + // 桩 composer 只实现 compose:noteFailure 缺席是合法的(旧接线/纯测试)。 + const auto = createDiaryAutoRun({ + ctx, + composer: { compose: async () => ({ status: "written" }) }, + everyMs: 60 * 60 * 1000, + listProjects: () => { throw new Error("state file gone"); } + }); + await auto.tickNow(); + assert.equal(warns.length, 1, "没有账本可写时仍要 warn,不许把失败吞掉"); + auto(); +}); + test("auto:turn/end 仍走 rollover,与定时器互不影响", () => { const { ctx, handlers } = autoCtx(); const auto = createDiaryAutoRun({