@shgroup/dsh-serenity-hooks 1.139.1 → 1.139.2

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.
@@ -1,261 +0,0 @@
1
- import { g as resolveInside, h as readUtf8 } from "./ccc-DSMqTrRU.js";
2
- import { dirname, join } from "node:path";
3
- import { existsSync, readFileSync, statSync } from "node:fs";
4
- import { fileURLToPath } from "node:url";
5
- //#region src/kernel/constants.ts
6
- /** 常量(纯模块,零 DSH 依赖) */
7
- /** 本包名 —— 上溯定位包根时的**身份核对**(同名目录家的邻居不会误命中) */
8
- const PACKAGE_NAME = "@shgroup/dsh-serenity-hooks";
9
- /** 上溯层数上限(源码态最深 `src/<域>/<子域>/` / 发布态 `lib/` ⇒ 8 层足够,且**保证有界**) */
10
- const MAX_ROOT_ASCENT = 8;
11
- /**
12
- * 包根 = 含**本包** `package.json` 的目录。
13
- *
14
- * 🔴 为什么不写 `join(here, '..')`:本模块自身的位置**随目录重构变化**
15
- * (曾 `src/`,现 `src/kernel/`),而发布态是从打包入口 `lib/index.js` 反推 ——
16
- * 两种布局的深度不同,写死层数**必然在其中一个布局下静默错位**。
17
- * 实测代价:`src/` → `src/kernel/` 之后,`join(here,'..')` 指到 `src/`(无 package.json)
18
- * ⇒ `ACC_VERSION` 落进 catch 分支变 `0.0.0`,**没有任何门禁报警**。
19
- *
20
- * ⇒ 判据改成**内容**(找带本包名的 package.json)而不是**层数**。
21
- *
22
- * @param start 起点目录(缺省 = 本模块所在目录;测试可注入)
23
- */
24
- function findPackageRoot(start) {
25
- let dir = start ?? dirname(fileURLToPath(import.meta.url));
26
- for (let i = 0; i < MAX_ROOT_ASCENT; i += 1) {
27
- try {
28
- if (JSON.parse(readFileSync(join(dir, "package.json"), "utf-8")).name === PACKAGE_NAME) return dir;
29
- } catch {}
30
- const parent = dirname(dir);
31
- if (parent === dir) return null;
32
- dir = parent;
33
- }
34
- return null;
35
- }
36
- /**
37
- * ACC 版本:自动从 package.json 读取(单一真相源,消除与 CHANGELOG 的漂移)。
38
- * 发布时只需改 package.json 的 version。
39
- */
40
- const ACC_VERSION = (() => {
41
- try {
42
- const root = findPackageRoot();
43
- if (root === null) return "0.0.0";
44
- return JSON.parse(readFileSync(join(root, "package.json"), "utf-8")).version ?? "0.0.0";
45
- } catch {
46
- return "0.0.0";
47
- }
48
- })();
49
- //#endregion
50
- //#region src/trajectory/policy/rules.ts
51
- /**
52
- * trajectory/policy/rules.ts — 轨迹约束面的**纯逻辑助手**(零 DSH 依赖,可独立单测)
53
- *
54
- * ## 2026-10-19 重做后的职责边界(R↓,别再混起来)
55
- *
56
- * | 模块 | 管什么 |
57
- * |---|---|
58
- * | `./profile.ts` | **判据 + 读盘**("这是不是 轨迹约束"、"约束面是什么") |
59
- * | `./rules.ts`(本文件) | **从约束面派生出的纯函数**(白名单集合、提示词读取器、基础提示词文本) |
60
- * | `../session-create.ts` | 会话创建/复用、提问、守门查询 |
61
- *
62
- * ⇒ 本文件**不再读 `serenity.json`**:`轨迹约束.roles` 整段已退役(owner 2026-10-19 重做)。
63
- * 它只接收一个已解析好的 `TrajectoryConstraint`,因此**不涉及任何 IO**(除提示词文件,那是刻意懒读的)。
64
- *
65
- * ## S12(2026-10-19,轨迹中心重构)
66
- *
67
- * 原名 `role/轨迹约束/config.ts`。改名理由(框架 §6.3「角色不是一个概念,是一段历史」):
68
- * 它派生的是**某条轨迹的约束面**,与"配置读取"无关(本文件零配置读取,见上一段)
69
- * ⇒ `config` 这个名字描述的是**它曾经的样子**,`rules` 描述它**现在做的事**。
70
- */
71
- /** 白名单推导 ────────────────────────────────────────────────────────────── */
72
- /** 提示词来源提示串(`apply` 回执与面板共用;避免两处措辞漂) */
73
- const TRAJECTORY_CONSTRAINT_HINT = "systemPromptFile hot-reloads by mtime; the rest of trajectory-constraint.json is re-read every turn";
74
- /**
75
- * 该轨迹会话**可见**的工具面(tools ∪ `msm`)。
76
- *
77
- * 🔴 **返回值 `null` 有专门含义(D181,owner 2026-10-20 裁「不写当然不收窄」)**:
78
- *
79
- * | `tools` | `msms` | 返回 | 语义 |
80
- * |---|---|---|---|
81
- * | 缺省 | 缺省 | **`null`** | **不收窄任何工具面**(这条轨迹要的是别的设定,如只写 `resident`) |
82
- * | `[]` | 缺省 | `{'msm'?}` 空/仅 msm | **全隐藏**(除恒可用的 `skill`) |
83
- * | `['a']` | … | `{'a', …}` | 只给这些 |
84
- *
85
- * ⛔ **调用方不许把 `null` 当空集处理** —— 那正是 S196 被锁死的形态(D179(b))。
86
- * 判据是**字段在不在**,不是数组空不空。
87
- *
88
- * 🔴 `msm` 为什么自动加入:`msms` 非空意味着这个轨迹 **有 MSM 通道**,
89
- * 而 MSM 的唯一合法调用入口是 `msm` 工具(单入口纪律)——不给它 `msm` 就等于
90
- * 声明了一堆调不动的能力。⚠️ 这是**并集**,不是覆盖:`tools` 里显式写的照旧生效。
91
- *
92
- * @returns 白名单集合;**`null` = 不收窄**(调用方须显式判 `null`)
93
- */
94
- function profileToolWhitelist(profile) {
95
- if (!profile) return null;
96
- if (profile.tools === void 0 && profile.msms === void 0) return null;
97
- const out = /* @__PURE__ */ new Set();
98
- for (const t of profile.tools ?? []) out.add(t);
99
- if ((profile.msms?.length ?? 0) > 0) out.add("msm");
100
- return out;
101
- }
102
- /** 该轨迹会话可 exec 的 MSM 白名单(`msm` 工具内部再过滤;独立于工具白名单) */
103
- function profileMsmWhitelist(profile) {
104
- return new Set(profile?.msms ?? []);
105
- }
106
- /**
107
- * 该轨迹可**写**的路径前缀(owner 2026-10-20 令:「轨迹设定自己的写白名单」)。
108
- *
109
- * 🔴 与 `profileToolWhitelist` 共用同一条判据(D181/D183):**字段在不在,不是数组空不空**。
110
- *
111
- * | `writes` | 返回 | 语义 |
112
- * |---|---|---|
113
- * | 缺省 | **`null`** | 不收窄(写权限 = 路径守卫那几条,与今天一致) |
114
- * | `[]` | `[]`(空数组) | **一个写都落不下**(显式意图) |
115
- * | `['a/']` | `['a/']` | 写目标必须落在 `a/` 之内 |
116
- *
117
- * ⛔ **调用方不许把 `null` 当 `[]`** —— 那会把"我没想到这件事"读成"我不许写任何东西",
118
- * 正是 S196 被静默锁死的形态(D179(b))。
119
- *
120
- * ⚠️ 返回的是**原始条目**(相对 CCC 根或绝对路径都可),解析成绝对路径由调用方按自己的 root 做 ——
121
- * 本模块不持有 root(判据在 `seams/guards.ts`)。
122
- */
123
- function profileWriteWhitelist(profile) {
124
- if (!profile) return null;
125
- if (profile.writes === void 0) return null;
126
- return profile.writes;
127
- }
128
- /** 轨迹纪律参与项(`profile` 缺省已在 `readTrajectoryConstraintAt` 归一为全 true) */
129
- function constraintCognitiveTrajectory(profile) {
130
- return {
131
- session: profile?.cognitiveTrajectory.session === true,
132
- keeper: profile?.cognitiveTrajectory.keeper === true,
133
- rebuild: profile?.cognitiveTrajectory.rebuild === true
134
- };
135
- }
136
- /**
137
- * 解析约束面声明的**系统提示词全文**(一次性读取;`create` / `validate` / `list` 用)。
138
- *
139
- * 顺序:`systemPromptFile`(**推荐**:超长提示词在 JSON 里内嵌不可读)→ 内嵌 `systemPrompt` → 空串。
140
- * 文件缺失/逃逸 ⇒ **抛错**(调用方 catch 降级;`validate` 据此报 issue)。
141
- *
142
- * ⚠️ 热路径**不用**它(那会用每次工具调用去读盘)——热路径用 `createProfilePromptReader`。
143
- */
144
- function resolveConstraintSystemPrompt(root, profile) {
145
- if (!profile) return "";
146
- const file = profile.systemPromptFile?.trim();
147
- if (file) {
148
- const abs = resolveInside(root, file);
149
- if (!existsSync(abs)) throw new Error(`轨迹约束 "${profile.code}": systemPromptFile "${file}" not found (resolved: ${abs})`);
150
- return readUtf8(abs).trim();
151
- }
152
- return profile.systemPrompt ?? "";
153
- }
154
- /**
155
- * 提示词来源(`list`/`validate` 展示用)。
156
- *
157
- * 🔴 **2026-10-19 修(T4 的漏网面)**:v1.72.0 起提示词有两代来源——**新形态**
158
- * 是轨迹目录里的 `PROMPT.md`(`trajectory/prompt.ts`,**优先**),旧形态才是
159
- * `systemPromptFile` / `systemPrompt`。本函数原先只认旧形态 ⇒ 两条只写了 `PROMPT.md`
160
- * 的轨迹在 `container_admin config list` 里恒显示 `promptSource: 'none'`。
161
- *
162
- * 那是**读数器过时**,不是配置缺失:`validate` 侧早已按两条来源判(见
163
- * `trajectory-constraint-admin.ts` 的 `hasTrajectoryPromptOrLegacy`),而 `list` 侧漏了。
164
- * ⇒ 返 **四种**值,把"有章程但来源是新形态"这一格单独说出来。
165
- *
166
- * @param hasPromptFile 该轨迹目录下**是否真有** `PROMPT.md`(调用方查,本函数不做 IO)
167
- */
168
- function constraintSystemPromptSource(profile, hasPromptFile = false) {
169
- if (hasPromptFile) return "trajectory-file";
170
- if (profile?.systemPromptFile?.trim()) return "file";
171
- if (profile?.systemPrompt?.trim()) return "inline";
172
- return "none";
173
- }
174
- /**
175
- * 提示词**读取器**(长期热更新;改文件即生效,无需重启)。
176
- *
177
- * 为什么返回函数而不是字符串(R↓,实证代价):旧实现在创建时把提示词**快照**进系统提示词段闭包
178
- * ⇒ CCC 改了提示词文件必须重启 dsh web 才生效(实测:改完 18KB 提示词,live agent 仍用旧文本)。
179
- * 现形态由系统提示词段的 `text()` **每轮调用**本读取器:
180
- * - `systemPromptFile`:按 **mtime + size** 缓存重读(命中缓存零 IO;未变不解析)
181
- * - 内嵌 `systemPrompt`:静态(改 JSON 仍需重载配置,这与文件热更的差别是**必然**的 —— 文件有 mtime,JSON 没有)
182
- * - 读取失败:返回**上次成功内容**(⛔ 绝不返回空——空提示词会让角色失去人格与纪律),并按标签去重告警一次
183
- *
184
- * @param root CCC 根
185
- * @param profile 约束面
186
- */
187
- function createProfilePromptReader(root, profile) {
188
- const file = profile?.systemPromptFile?.trim();
189
- if (!file) {
190
- const inline = profile?.systemPrompt ?? "";
191
- return () => inline;
192
- }
193
- let abs = null;
194
- try {
195
- abs = resolveInside(root, file);
196
- } catch (err) {
197
- console.warn(`[serenity-hooks] ✗ 轨迹约束提示词路径非法(${file}): ${String(err?.message ?? err)}`);
198
- }
199
- if (abs === null) return () => "";
200
- const absPath = abs;
201
- let cachedMtime = -1;
202
- let cachedSize = -1;
203
- let cachedText = "";
204
- let warned = false;
205
- return () => {
206
- try {
207
- const st = statSync(absPath);
208
- if (st.mtimeMs === cachedMtime && st.size === cachedSize) return cachedText;
209
- const text = readUtf8(absPath).trim();
210
- const isReload = cachedMtime !== -1;
211
- cachedMtime = st.mtimeMs;
212
- cachedSize = st.size;
213
- cachedText = text;
214
- warned = false;
215
- if (isReload) console.info(`[serenity-hooks] ↻ 轨迹约束提示词已热重载(${file},${text.length} 字符)`);
216
- return text;
217
- } catch (err) {
218
- if (!warned) {
219
- warned = true;
220
- console.warn(`[serenity-hooks] ✗ 轨迹约束提示词读取失败(${file})——沿用上次成功内容: ${String(err?.message ?? err)}`);
221
- }
222
- return cachedText;
223
- }
224
- };
225
- }
226
- /**
227
- * 轨迹约束 基础提示词(dsp 只给这部分;CCC 的 `systemPrompt` 段由调用方拼接)。
228
- *
229
- * ## 🔴 为什么**不再枚举**清单(owner 2026-10-19 令)
230
- *
231
- * 旧版在这里抄了两份清单(`MSMs: a, b, c` / `Tools: read, grep, …`)。那是**第二真相源**,
232
- * 而真相源本来就在模型自己手里:
233
- * · **工具清单** = 这一轮实际注册给它的 tool schema —— 模型已经看得见,抄一遍只会漂
234
- * · **MSM 清单** = `msm()` 无参调用返回的目录 —— 已按白名单过滤,且**每次实时读配置**
235
- *
236
- * ⚠️ **漂移不是理论风险,是已发生的缺陷**(2026-10-19):角色配置早就长到 8 个工具,
237
- * 而这个函数是从**创建时冻结的快照**求值的 ⇒ 提示词里一直写着旧的 4 个
238
- * ⇒ 模型照着提示词办事,**它自己以为没有的能力就不去调** ⇒ 症状是"工具用不了",
239
- * 而守卫那边(每调用实时读配置)其实是放行的。两个真相源打架,输的总是提示词。
240
- *
241
- * ⇒ 现在只声明**边界与发现路径**,不抄内容:清单在哪,怎么取,越界会怎样。
242
- *
243
- * @param code 轨迹编码(轨迹约束的身份 —— 不是"角色名",那个概念已退役)
244
- */
245
- function buildTrajectoryBasePrompt(code) {
246
- return [
247
- "=== Serenity 轨迹约束 ===",
248
- `Cognitive trajectory: ${code} (this is the trajectory you ARE, not a role you play)`,
249
- "Your capability boundary is enforced mechanically by this CCC — anything outside it is rejected at the call site, not by your judgment.",
250
- "Discover your surface, do not memorize it (both are generated from the live config on every turn):",
251
- " · Your tools are exactly the tool schemas you see in this session — if a tool is not in your schema, it is not available.",
252
- " · Your MSMs are listed by calling msm() with no arguments — that directory is already filtered to this trajectory.",
253
- " · Usage for any MSM: msm(\"<name>\", [], inspect=true) or pass \"--help\" as the first argument.",
254
- "Do not infer unavailability from anything you remember or from an earlier list: this surface changes when the CCC configuration changes, and it takes effect without restarting.",
255
- "",
256
- "---",
257
- ""
258
- ].join("\n");
259
- }
260
- //#endregion
261
- export { createProfilePromptReader as a, profileWriteWhitelist as c, findPackageRoot as d, constraintSystemPromptSource as i, resolveConstraintSystemPrompt as l, buildTrajectoryBasePrompt as n, profileMsmWhitelist as o, constraintCognitiveTrajectory as r, profileToolWhitelist as s, TRAJECTORY_CONSTRAINT_HINT as t, ACC_VERSION as u };
@@ -1,282 +0,0 @@
1
- import { s as loadSerenityConfig, t as DEFAULT_SERENITY_CONFIG_PATHS } from "./ccc-DSMqTrRU.js";
2
- import { join } from "node:path";
3
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
4
- //#region src/tools/localstore/service.ts
5
- /**
6
- * tools/localstore/service.ts — localstore 纯逻辑层(零 DSH 依赖,可独立单测)
7
- *
8
- * S134 重设计(v1.16.7):存储从 ~/.serenity/ 迁到 **CCC 根根目录 localstore.json**
9
- * (JSON 格式——方便 MSM 直接 read + JSON.parse 读取,零解析依赖)。
10
- *
11
- * git 提交策略(可靠机制 × 用户自由):
12
- * - 配置:.opencode/serenity.json `localstore.gitTrack`: "allow"(可提交)| "deny"(禁提交)
13
- * - **缺省 deny(没配就是不提交)**;且 deny 的保证**不依赖 dsh 运行**——
14
- * 写入时自动确保 .gitignore 含 localstore.json(物理保证:即使 dsh 不在、
15
- * 用户手动 git commit 也不会误提交),container_git 检查为第二道防线(拒绝 + 提示)
16
- * - allow:放行(文件可提交,用户自行管理 .gitignore)
17
- *
18
- * 存储结构(JSON 顶层分节):
19
- * { "credentials": { "HOME_GITLAB_TOKEN": "xxx" }, "<config节>": { "<key>": "v" } }
20
- * credentials 为保留节(credential 命名空间,key 大写蛇形);其余节归 config 命名空间
21
- * (path = section.key,如 my-feature.someKey)。
22
- */
23
- const LOCALSTORE_SCOPES = ["credential", "config"];
24
- /** 存储文件名(CCC 根根目录) */
25
- const LOCALSTORE_FILENAME = "localstore.json";
26
- /** 凭据保留节名(JSON 顶层) */
27
- const CREDENTIALS_SECTION = "credentials";
28
- /** 凭据 key 规范:大写蛇形,如 HOME_GITLAB_TOKEN */
29
- const CREDENTIAL_KEY_RE = /^[A-Z][A-Z0-9_]*$/;
30
- /** 配置节名规范:小写字母数字连字符 */
31
- const CONFIG_SECTION_RE = /^[a-z][a-z0-9-]*$/;
32
- /** 配置 key 规范(节内):小驼峰,如 defaultModel */
33
- const CONFIG_KEY_RE = /^[a-z][a-zA-Z0-9_]*$/;
34
- /** 存储文件绝对路径(CCC 根根目录) */
35
- function localstorePath(root) {
36
- return join(root, LOCALSTORE_FILENAME);
37
- }
38
- /** git 策略:serenity.json localstore.gitTrack,缺省 deny(不提交) */
39
- function readGitTrack(root, paths = DEFAULT_SERENITY_CONFIG_PATHS) {
40
- return loadSerenityConfig(root, paths).localstore?.gitTrack === "allow" ? "allow" : "deny";
41
- }
42
- /** .gitignore 是否已覆盖 localstore 文件(非空非注释行含文件名即算) */
43
- function isLocalstoreGitignored(root) {
44
- const gi = join(root, ".gitignore");
45
- if (!existsSync(gi)) return false;
46
- return readFileSync(gi, "utf-8").split("\n").some((l) => {
47
- const t = l.trim();
48
- return t !== "" && !t.startsWith("#") && t.includes("localstore.json");
49
- });
50
- }
51
- /**
52
- * 确保 .gitignore 含 localstore 文件(deny 时的物理保证,不依赖 dsh 运行):
53
- * 写入 localstore 时调用——deny(含缺省)且 .gitignore 未覆盖 → 自动追加一行。
54
- * allow → 不写入(放行,文件可提交)。
55
- */
56
- function ensureLocalstoreGitignored(root) {
57
- if (readGitTrack(root) === "allow") return { status: "allow" };
58
- if (isLocalstoreGitignored(root)) return { status: "ignored" };
59
- const gi = join(root, ".gitignore");
60
- const existing = existsSync(gi) ? readFileSync(gi, "utf-8") : "";
61
- const line = `${LOCALSTORE_FILENAME} # ACC localstore (localstore.gitTrack defaults to deny — do not commit)`;
62
- writeFileSync(gi, (existing.endsWith("\n") || existing === "" ? existing : existing + "\n") + line + "\n", "utf-8");
63
- return { status: "appended" };
64
- }
65
- /**
66
- * container_git 联动检查(第二道防线):文件存在 && deny && .gitignore 未覆盖 → 不通过。
67
- * 调用方(container_git commit)据此拒绝提交;status 可输出 warning。
68
- */
69
- function checkLocalstoreGitCompliance(root) {
70
- if (!existsSync(localstorePath(root))) return { ok: true };
71
- if (readGitTrack(root) === "allow") return { ok: true };
72
- if (isLocalstoreGitignored(root)) return { ok: true };
73
- return {
74
- ok: false,
75
- reason: `localstore.json must not be committed (localstore.gitTrack=deny default) but .gitignore does not cover it — add ${LOCALSTORE_FILENAME} to .gitignore (or set localstore.gitTrack=allow to explicitly permit)`
76
- };
77
- }
78
- /** 已告警的坏 localstore 路径(进程级去重;F-07:凭据文件损坏不得静默) */
79
- const warnedBrokenStores = /* @__PURE__ */ new Set();
80
- /** 读取全文件(顶层分节);文件不存在 → 空;**坏 JSON → 空 + 响亮告警**(每路径一次) */
81
- function readAll(root) {
82
- const p = localstorePath(root);
83
- if (!existsSync(p)) return {};
84
- try {
85
- const v = JSON.parse(readFileSync(p, "utf-8").replace(/^\uFEFF/, ""));
86
- if (v && typeof v === "object" && !Array.isArray(v)) return v;
87
- return {};
88
- } catch (err) {
89
- if (!warnedBrokenStores.has(p)) {
90
- warnedBrokenStores.add(p);
91
- console.warn(`[serenity-hooks] ✗ localstore 解析失败,已按空存储继续(其中凭据/配置对工具表现为"未设置",请修 JSON): ${p} — ${String(err?.message ?? err)}`);
92
- }
93
- return {};
94
- }
95
- }
96
- /** 写回全文件(2 空格缩进 + 尾换行,方便 MSM 直接读取) */
97
- function writeAll(root, data) {
98
- writeFileSync(localstorePath(root), JSON.stringify(data, null, 2) + "\n", "utf-8");
99
- }
100
- /** 读取命名空间全部条目:credential → 扁平;config → 分节(剔除 credentials 保留节) */
101
- function readStore(root, scope) {
102
- const all = readAll(root);
103
- if (scope === "credential") return all[CREDENTIALS_SECTION] ?? {};
104
- const { [CREDENTIALS_SECTION]: _cred, ...rest } = all;
105
- return rest;
106
- }
107
- /** 校验凭据 key 合法(大写蛇形);不合法抛错 */
108
- function assertCredentialKey(key) {
109
- if (!CREDENTIAL_KEY_RE.test(key)) throw new Error(`credential key "${key}" must match UPPER_SNAKE ^[A-Z][A-Z0-9_]*$ (e.g. HOME_GITLAB_TOKEN)`);
110
- }
111
- /** 校验 config 路径(节.key);不合法抛错 */
112
- function assertConfigPath(path) {
113
- const idx = path.indexOf(".");
114
- if (idx <= 0 || idx === path.length - 1) throw new Error(`config path "${path}" must be section.key (e.g. my-feature.someKey)`);
115
- const section = path.slice(0, idx);
116
- const key = path.slice(idx + 1);
117
- if (!CONFIG_SECTION_RE.test(section)) throw new Error(`config section "${section}" must match ^[a-z][a-z0-9-]*$`);
118
- if (!CONFIG_KEY_RE.test(key)) throw new Error(`config key "${key}" must match lowerCamel ^[a-z][a-zA-Z0-9_]*$ (e.g. defaultModel)`);
119
- return {
120
- section,
121
- key
122
- };
123
- }
124
- /** 写入单个条目(自动建文件;deny 默认时同步确保 .gitignore 物理保证) */
125
- function writeEntry(root, scope, name, value) {
126
- const all = readAll(root);
127
- if (scope === "credential") {
128
- assertCredentialKey(name);
129
- all[CREDENTIALS_SECTION] ??= {};
130
- all[CREDENTIALS_SECTION][name] = value;
131
- } else {
132
- const { section, key } = assertConfigPath(name);
133
- all[section] ??= {};
134
- all[section][key] = value;
135
- }
136
- writeAll(root, all);
137
- ensureLocalstoreGitignored(root);
138
- }
139
- /** 删除单个条目(不存在返回 false);空节自动移除 */
140
- function unsetEntry(root, scope, name) {
141
- const all = readAll(root);
142
- if (scope === "credential") {
143
- assertCredentialKey(name);
144
- const sec = all[CREDENTIALS_SECTION];
145
- if (!sec || !(name in sec)) return false;
146
- delete sec[name];
147
- if (Object.keys(sec).length === 0) delete all[CREDENTIALS_SECTION];
148
- } else {
149
- const { section, key } = assertConfigPath(name);
150
- const sec = all[section];
151
- if (!sec || !(key in sec)) return false;
152
- delete sec[key];
153
- if (Object.keys(sec).length === 0) delete all[section];
154
- }
155
- writeAll(root, all);
156
- return true;
157
- }
158
- /** 读取单个条目值;不存在返回 null */
159
- function getEntry(root, scope, name) {
160
- const all = readAll(root);
161
- if (scope === "credential") {
162
- assertCredentialKey(name);
163
- return all[CREDENTIALS_SECTION]?.[name] ?? null;
164
- }
165
- const { section, key } = assertConfigPath(name);
166
- return all[section]?.[key] ?? null;
167
- }
168
- /** 列出 key(凭据只返回 key 名,不返回值) */
169
- function listKeys(root, scope) {
170
- const data = readStore(root, scope);
171
- if (scope === "credential") return Object.keys(data);
172
- return Object.entries(data).flatMap(([section, entries]) => Object.keys(entries).map((key) => `${section}.${key}`));
173
- }
174
- /**
175
- * doc 说明文本:输出存储位置/格式/key 规范/git 策略/读写方法。
176
- * agent 据此可直接用 fs 工具(read/write)自己读写凭据/配置。
177
- */
178
- function docText(root) {
179
- const path = localstorePath(root);
180
- return [
181
- "# localstore — ACC local credential/config storage (standard, S134 redesign)",
182
- "",
183
- "One tool manages two namespaces: credential (credentials) + config (preferences).",
184
- `Stored at the CCC root in ${path} (JSON format; MSMs can read + JSON.parse directly).`,
185
- "",
186
- "## Git commit policy",
187
- "- Config: .opencode/serenity.json `localstore.gitTrack`: `\"allow\"` (may commit) | `\"deny\"` (must not commit; .dsh fallback)",
188
- "- **Default deny (unset = not committed)**; when deny, writes automatically ensure .gitignore contains localstore.json",
189
- " (physical guarantee, independent of dsh runtime); container_git commit checks and refuses",
190
- "- To commit: set `\"localstore\": { \"gitTrack\": \"allow\" }` and remove localstore.json from .gitignore",
191
- "",
192
- "## Format (JSON top-level sections)",
193
- "```json",
194
- "{",
195
- " \"credentials\": {",
196
- " \"HOME_GITLAB_TOKEN\": \"xxx\"",
197
- " },",
198
- " \"my-feature\": {",
199
- " \"someKey\": \"some-value\"",
200
- " }",
201
- "}",
202
- "```",
203
- "- credentials is a reserved section (credentials, UPPER_SNAKE keys); other sections = config (path = section.key)",
204
- "",
205
- "## Key conventions",
206
- "- credential key: ^[A-Z][A-Z0-9_]*$ (e.g. HOME_GITLAB_TOKEN)",
207
- "- config path: section.key (section ^[a-z][a-z0-9-]*$, key lowerCamel ^[a-z][a-zA-Z0-9_]*$, e.g. my-feature.someKey)",
208
- "",
209
- "## Reading (agents may use fs tools directly)",
210
- `- Read ${path} with the read tool → JSON.parse`,
211
- "- Or use localstore get <name> [--scope credential|config]",
212
- "",
213
- "## Writing",
214
- "- Recommended: localstore set <name> <value> [--scope ...] (auto-creates file / preserves other entries / syncs .gitignore)",
215
- "- Or modify the file directly with write/edit, keeping the JSON valid",
216
- "",
217
- "## Security boundary",
218
- "- list/show return only key names for credentials, never values",
219
- "- Credential values should be used internally by the agent; never write them into conversation or logs",
220
- "- Default deny: the file is not committed to git (.gitignore physical guarantee + container_git check fallback)",
221
- ""
222
- ].join("\n");
223
- }
224
- /** 运行 localstore 操作(纯逻辑;返回 JSON 值供工具 render) */
225
- function runLocalStore(root, args) {
226
- const scope = args.scope === "config" ? "config" : "credential";
227
- switch (args.action) {
228
- case "list": return {
229
- scope,
230
- keys: listKeys(root, scope)
231
- };
232
- case "get": {
233
- if (!args.name) throw new Error("get requires name");
234
- const value = getEntry(root, scope, args.name);
235
- if (value === null) throw new Error(`not found: ${args.name} (scope=${scope})`);
236
- return {
237
- scope,
238
- name: args.name,
239
- value,
240
- source: scope
241
- };
242
- }
243
- case "set": {
244
- if (!args.name) throw new Error("set requires name");
245
- if (args.value === void 0) throw new Error("set requires value");
246
- writeEntry(root, scope, args.name, args.value);
247
- const git = checkLocalstoreGitCompliance(root);
248
- return {
249
- scope,
250
- name: args.name,
251
- set: true,
252
- path: localstorePath(root),
253
- gitTrack: readGitTrack(root),
254
- gitOk: git.ok,
255
- git: git.reason ? { warning: git.reason } : null
256
- };
257
- }
258
- case "unset": {
259
- if (!args.name) throw new Error("unset requires name");
260
- const removed = unsetEntry(root, scope, args.name);
261
- return {
262
- scope,
263
- name: args.name,
264
- removed
265
- };
266
- }
267
- case "show": {
268
- if (!args.name) throw new Error("show requires name");
269
- const exists = getEntry(root, scope, args.name) !== null;
270
- return {
271
- scope,
272
- name: args.name,
273
- exists,
274
- path: localstorePath(root)
275
- };
276
- }
277
- case "doc": return { doc: docText(root) };
278
- default: throw new Error(`Unknown subcommand: ${args.action} (available: list/get/set/unset/show/doc)`);
279
- }
280
- }
281
- //#endregion
282
- export { readGitTrack as a, unsetEntry as c, localstorePath as i, writeEntry as l, checkLocalstoreGitCompliance as n, readStore as o, getEntry as r, runLocalStore as s, LOCALSTORE_SCOPES as t };